D7net
Home
Console
Upload
information
Create File
Create Folder
About
Tools
:
/
usr
/
share
/
grafana
/
public
/
build
/
Filename :
AlertingRuleForm.0885ba71cda43804812f.js
back
Copy
"use strict";(self.webpackChunkgrafana=self.webpackChunkgrafana||[]).push([[5372],{27419:(Ct,me,s)=>{s.r(me),s.d(me,{default:()=>nr});var e=s(27702),Y=s(25111),Ce=s(37647),O=s(18771),d=s(42844),b=s(63439),S=s(66310),D=s(66670);function pe({title:t,children:a}){return e.createElement(b.b,{className:(0,S.wW)(It).warning,severity:"warning",title:t},e.createElement("p",null,a),e.createElement(D.Qj,{href:"alerting/list"},"To rule list"))}const It=t=>({warning:(0,d.css)` margin: ${t.spacing(4)}; `});var V=s(89949),wt=s(26129),Ie=s(52419),M=s(46089),Dt=s(7662),Tt=s(85014),Ge=s(34667),At=s(91106),J=s(22209),fe=s(1128),We=s(64022),Ue=s(62108),Pt=s(29372),$t=s(3613),Nt=s(75443),bt=s(73807),re=s(66574),ze=s(75429),Qt=s(89033),Oe=s(28722),ge=s(10027),X=s(47702),p=s(72821),ve=s(84369),$=s(85184),Ee=s(96437),Mt=s(60871),ie=s(16310),we=s(28580),Ve=s(447),Q=s(95017);const Be=({rulesSourceName:t})=>{const{control:a,watch:n,formState:{errors:r},setValue:o}=(0,M.Gc)(),i=(0,S.wW)(Ft),c=(0,ge._)(y=>y.rulerRules),l=(0,O.useDispatch)();(0,e.useEffect)(()=>{l((0,X.UR)({rulesSourceName:t}))},[t,l]);const u=c[t]?.result,g=n("namespace"),m=(0,e.useMemo)(()=>u?Object.keys(u).map(y=>({label:y,value:y})):[],[u]),E=(0,e.useMemo)(()=>g&&u?.[g]?.map(y=>({label:y.name,value:y.name}))||[],[g,u]);return e.createElement("div",{className:i.flexRow},e.createElement(J.g,{"data-testid":"namespace-picker",label:"Namespace",error:r.namespace?.message,invalid:!!r.namespace?.message},e.createElement(ie.g,{render:({field:{onChange:y,ref:h,...f}})=>e.createElement(we.LT,{...f,allowCustomValue:!0,className:i.input,onChange:C=>{o("group",""),y(C.value)},options:m,width:42}),name:"namespace",control:a,rules:{required:{value:!0,message:"Required."},validate:{pathSeparator:Q.p0}}})),e.createElement(J.g,{"data-testid":"group-picker",label:"Group",error:r.group?.message,invalid:!!r.group?.message},e.createElement(ie.g,{render:({field:{ref:y,...h}})=>e.createElement(we.LT,{...h,allowCustomValue:!0,options:E,width:42,onChange:f=>{o("group",f.value??"")},className:i.input}),name:"group",control:a,rules:{required:{value:!0,message:"Required."},validate:{pathSeparator:Q.p0}}})))},Ft=t=>({flexRow:(0,d.css)` display: flex; flex-direction: row; justify-content: flex-start; & > * + * { margin-left: ${t.spacing(3)}; } `,input:(0,d.css)` width: 330px !important; `});var Lt=s(93562),Gt=s(83639),Wt=s(60956),G=s(53933),z=s(10864),Ut=s(45383),zt=s(39343),Ot=s(56469),Vt=s(32900),Bt=s(35412),Ht=s(66784),oe=s(8508),jt=s(73289),Zt=s(40545);function Kt(t){return"expr"in t}function Yt(t){return"grafana_condition"in t}var k=s(22513);function Jt(t){if(Kt(t))return He(t,t.dataSourceUid,p.$.cloudAlerting);if(Yt(t))return He(t,k.GC,p.$.grafana);throw new Error("unsupported preview rule request")}function He(t,a,n){return(0,Bt.x)({whileLoading:De(n),source:(0,jt.i)().fetch({method:"POST",url:`/api/v1/rule/test/${a}`,data:t}).pipe((0,zt.U)(({data:r})=>De(n,{state:G.Gu.Done,series:r.instances.map(Ht.vP)})),(0,Ot.K)(r=>(0,Ut.of)(De(n,{state:G.Gu.Error,error:(0,Zt.P)(r)}))),(0,Vt.B)())})}function De(t,a={}){return{ruleType:t,data:{state:G.Gu.Loading,series:[],timeRange:(0,oe.JK)(),...a}}}var Xt=s(2701),kt=s(55925),qt=s(19221),_t=s(22323),en=s(64167);function tn(t){const{preview:a}=t,n=(0,S.wW)(nn),r={defaults:{},overrides:[{matcher:{id:qt.mi.byName,options:"Info"},properties:[{id:"custom.displayMode",value:en.h2.JSONView}]}]};if(!a)return null;const{data:o,ruleType:i}=a;return o.state===G.Gu.Loading?e.createElement("div",{className:n.container},e.createElement("span",null,"Loading preview...")):o.state===G.Gu.Error?e.createElement("div",{className:n.container},o.error?(0,ve.kk)(o.error):"Failed to preview alert rule"):e.createElement("div",{className:n.container},e.createElement("span",null,"Preview based on the result of running the query, for this moment."," ",i===p.$.grafana?"Configuration for `no data` and `error handling` is not applied.":null),e.createElement("div",{className:n.table},e.createElement(kt.Z,null,({width:c,height:l})=>e.createElement("div",{style:{width:`${c}px`,height:`${l}px`}},e.createElement(_t.$,{title:"",width:c,height:l,pluginId:"table",data:o,fieldConfig:r})))))}function nn(t){return{container:(0,d.css)` margin: ${t.spacing(2)} 0; `,table:(0,d.css)` flex: 1 1 auto; height: 135px; margin-top: ${t.spacing(2)}; border: 1px solid ${t.colors.border.medium}; border-radius: ${t.shape.borderRadius(1)}; `}}const an=["type","dataSourceName","condition","queries","expression"];function rn(){const t=(0,S.wW)(ln),[a,n]=je(),{watch:r}=(0,M.Gc)(),[o,i,c]=r(["type","condition","queries"]),{allDataSourcesAvailable:l}=(0,Xt.S)(c);if(o===p.$.cloudRecording||o===p.$.cloudAlerting)return null;const u=!!i&&l;return e.createElement("div",{className:t.container},e.createElement(We.Lh,null,l&&e.createElement(D.zx,{disabled:!u,type:"button",variant:"primary",onClick:n},"Preview alerts"),!l&&e.createElement(b.b,{title:"Preview is not available",severity:"warning"},"Cannot display the query preview. Some of the data sources used in the queries are not available.")),e.createElement(tn,{preview:a}))}function je(){const[t,a]=(0,e.useState)(),{getValues:n}=(0,M.Gc)(),r=(0,Lt.Z)(),o=(0,e.useCallback)(()=>{const i=n(an),c=on(i);Jt(c).pipe((0,Gt.o)(l=>!sn(l),!0)).subscribe(l=>{r()&&a(l)})},[n,r]);return[t,o]}function on(t){const[a,n,r,o,i]=t,c=(0,z.F)().getInstanceSettings(n);if(!c)throw new Error(`Cannot find data source settings for ${n}`);switch(a){case p.$.cloudAlerting:return{dataSourceUid:c.uid,dataSourceName:n,expr:i};case p.$.grafana:return{grafana_condition:{condition:r,data:o,now:(0,Wt.lf)(Date.now())}};default:throw new Error(`Alert type ${a} not supported by preview.`)}}function sn(t){switch(t.data.state){case G.Gu.Done:case G.Gu.Error:return!0;default:return!1}}function ln(t){return{container:(0,d.css)` margin-top: ${t.spacing(2)}; max-width: ${t.breakpoints.values.xxl}px; `}}var ce=s(82669);const cn=()=>{const t=(0,S.wW)(un),{register:a,control:n,watch:r,formState:{errors:o}}=(0,M.Gc)(),i=r("type"),c=r("dataSourceName");return e.createElement(ce.z,{stepNo:3,title:"Set alert evaluation behavior"},e.createElement(J.g,{label:"Pending period",description:"Period in which an alert rule can be in breach of the condition until the alert rule fires."},e.createElement("div",{className:t.flexRow},e.createElement(J.g,{invalid:!!o.forTime?.message,error:o.forTime?.message,className:t.inlineField},e.createElement(fe.I,{...a("forTime",{pattern:{value:/^\d+$/,message:"Must be a positive integer."}}),width:8})),e.createElement(ie.g,{name:"forTimeUnit",render:({field:{onChange:l,ref:u,...g}})=>e.createElement(we.Ph,{...g,options:Ve.qr,onChange:m=>l(m?.value),width:15,className:t.timeUnit}),control:n}))),i===p.$.cloudAlerting&&c&&e.createElement(Be,{rulesSourceName:c}),e.createElement(rn,null))},un=t=>({inlineField:(0,d.css)` margin-bottom: 0; `,flexRow:(0,d.css)` display: flex; flex-direction: row; justify-content: flex-start; align-items: flex-start; `,timeUnit:(0,d.css)` margin-left: ${t.spacing(.5)}; `});var dn=s(278),mn=s(24393),F=s(23852),q=s(73453),H=s(50230),pn=s(9848),fn=s(50115),Te=s(51317),Ze=s(21323),gn=s(85096),vn=s(86954),Ke=s(62862),En=s(52646);const hn=()=>{const{currentData:t}=En.alertmanagerApi.useGetAlertmanagerChoiceStatusQuery(void 0),a=(0,k.Rz)().map(o=>({name:o.name,img:o.meta.info.logos.small})),n=t?.alertmanagersChoice;return n===Ke.TE.Internal?[{name:k.GC,img:"public/img/grafana_icon.svg"}]:n===Ke.TE.External?a:[{name:k.GC,img:"public/img/grafana_icon.svg"},...a]},yn=(0,e.lazy)(()=>Promise.all([s.e(3504),s.e(8050)]).then(s.bind(s,8050))),xn=({alertQueries:t,customLabels:a,condition:n,folder:r,alertName:o,alertUid:i})=>{const c=(0,S.wW)(Sn),{usePreviewMutation:l}=gn.alertRuleApi,[u,{data:g=[],isLoading:m,isUninitialized:E}]=l(),y=(0,V.compact)(g.flatMap(w=>w?.labels)),h=()=>{u({alertQueries:t,condition:n,customLabels:a,folder:r,alertName:o,alertUid:i})},f=hn(),C=f.length===1,I=!g?.length&&!m;return e.createElement(vn.K,{direction:"column",gap:2},e.createElement("div",{className:c.routePreviewHeaderRow},e.createElement("div",{className:c.previewHeader},e.createElement(Ze.x,{element:"h4"},"Alert instance routing preview")),e.createElement("div",{className:c.button},e.createElement(D.zx,{icon:"sync",variant:"secondary",type:"button",onClick:h},"Preview routing"))),!I&&e.createElement("div",{className:c.textMuted},"Based on the labels added, alert instances are routed to the following notification policies. Expand each notification policy below to view more details."),m&&e.createElement("div",{className:c.textMuted},"Loading..."),I&&e.createElement("div",{className:c.previewHowToText},'When your query and labels are configured, click "Preview routing" to see the results here.'),!m&&!E&&y.length>0&&e.createElement(e.Suspense,{fallback:e.createElement(Ie.u,{text:"Loading preview..."})},f.map(w=>e.createElement(yn,{alertManagerSource:w,potentialInstances:y,onlyOneAM:C,key:w.name}))))},Sn=t=>({collapsableSection:(0,d.css)` width: auto; border: 0; `,textMuted:(0,d.css)` color: ${t.colors.text.secondary}; `,previewHowToText:(0,d.css)` display: flex; color: ${t.colors.text.secondary}; justify-content: center; font-size: ${t.typography.size.sm}; `,previewHeader:(0,d.css)` margin: 0; `,routePreviewHeaderRow:(0,d.css)` display: flex; flex-direction: row; justify-content: space-between; align-items: center; `,collapseLabel:(0,d.css)` flex: 1; `,button:(0,d.css)` justify-content: flex-end; display: flex; `,tagsInDetails:(0,d.css)` display: flex; justify-content: flex-start; flex-wrap: wrap; `,policyPathItemMatchers:(0,d.css)` display: flex; flex-direction: row; gap: ${t.spacing(1)}; `}),Rn=({alertUid:t})=>{const a=(0,S.wW)(In),{watch:n,getValues:r}=(0,M.Gc)(),[o,i,c,l,u,g]=n(["type","labels","queries","condition","folder","name"]),m=n("dataSourceName")??k.GC,E=Cn(r("labels")).length>0,y=!!l&&!!u&&o===p.$.grafana,h=()=>e.createElement("div",{className:a.stepDescription},e.createElement("div",null,"Add custom labels to change the way your notifications are routed."),e.createElement(Te.h,{contentText:e.createElement(F.K,{gap:1},e.createElement(F.K,{direction:"row",gap:0},e.createElement(e.Fragment,null,"Firing alert rule instances are routed to notification policies based on matching labels. All alert rules and instances, irrespective of their labels, match the default notification policy. If there are no nested policies, or no nested policies match the labels in the alert rule or alert instance, then the default notification policy is the matching policy."),e.createElement("a",{href:"https://grafana.com/docs/grafana/latest/alerting/fundamentals/notification-policies/notifications/",target:"_blank",rel:"noreferrer"},e.createElement("div",{className:a.infoLink},"Read about notification routing. ",e.createElement(q.J,{name:"external-link-alt"})))),e.createElement(F.K,{direction:"row",gap:0},e.createElement(e.Fragment,null,"Custom labels change the way your notifications are routed. First, add labels to your alert rule and then connect them to your notification policy by adding label matchers."),e.createElement("a",{href:"https://grafana.com/docs/grafana/latest/alerting/fundamentals/annotation-label/",target:"_blank",rel:"noreferrer"},e.createElement("div",{className:a.infoLink},"Read about Labels and annotations. ",e.createElement(q.J,{name:"external-link-alt"}))))),title:"Notification routing"}));return e.createElement(ce.z,{stepNo:o===p.$.cloudRecording?4:5,title:o===p.$.cloudRecording?"Add labels":"Configure notifications",description:o===p.$.cloudRecording?"Add labels to help you better manage your recording rules":e.createElement(h,null)},e.createElement("div",{className:a.contentWrapper},e.createElement("div",{style:{display:"flex",flexDirection:"column"}},!E&&o!==p.$.cloudRecording&&e.createElement(H.Z,{className:a.card},e.createElement(H.Z.Heading,null,"Default policy"),e.createElement(H.Z.Description,null,"All alert instances are handled by the default policy if no other matching policies are found. To view and edit the default policy, go to ",e.createElement(pn.r,{href:"/alerting/routes"},"Notification Policies"),"\xA0or contact your Admin if you are using provisioning.")),e.createElement(fn.Z,{dataSourceName:m}))),y&&l&&u&&e.createElement(xn,{alertQueries:c,customLabels:i,condition:l,folder:u,alertName:g,alertUid:t}))};function Cn(t){return t.filter(a=>a.key&&a.value)}const In=t=>({contentWrapper:(0,d.css)` display: flex; align-items: center; margin-top: ${t.spacing(2)}; `,hideButton:(0,d.css)` color: ${t.colors.text.secondary}; cursor: pointer; margin-bottom: ${t.spacing(1)}; `,card:(0,d.css)` max-width: 500px; `,flowChart:(0,d.css)` margin-right: ${t.spacing(3)}; `,title:(0,d.css)` margin-bottom: ${t.spacing(2)}; `,stepDescription:(0,d.css)` margin-bottom: ${t.spacing(2)}; display: flex; gap: ${t.spacing(1)}; )}; `,infoLink:(0,d.css)` color: ${t.colors.text.link}; `});function wn(){const{watch:t}=(0,M.Gc)(),a=t("dataSourceName");return a?e.createElement(ce.z,{stepNo:3,title:"Add namespace and group",description:"Select the Namespace and Group for your recording rule."},e.createElement(Be,{rulesSourceName:a})):null}var Dn=s(3972),Tn=s(74639),he=s(80011),An=s(89746),Pn=s(79655),$n=s(80434),se=s(55692),_=s(65946);function Ye(){const t=(0,ge._)(n=>n.dataSources);return Object.values(t).map(n=>n.result).filter(n=>!!n?.rulerConfig).map(n=>(0,k.c$)(n.name)).filter(n=>!!n)}var Nn=s(61576),ye=s(62247),bn=s(86004),Qn=s(77328),Mn=s(68614),Fn=s(18447);function Ln({fields:t}){const a=t.filter(l=>!["State","Info"].includes(l.name)),n=t.findIndex(l=>l.name==="State"),r=t.findIndex(l=>l.name==="Info"),o=a.map(l=>t.indexOf(l)),i=t[n]?.values.length??0,c=[];for(let l=0;l<i;l++){const u=o.map(E=>[t[E].name,t[E].values[l]]),g=t[n]?.values?.[l],m=t[r]?.values?.[l];(0,Fn.Yb)(g)&&c.push({state:g,info:m,labels:Object.fromEntries(u)})}return{instances:c}}function Gn({preview:t}){const a=(0,S.wW)(Wn),n=Ln(t);return e.createElement("table",{className:a.table},e.createElement("caption",null,e.createElement("div",null,"Alerts preview"),e.createElement("span",null,"Preview based on the result of running the query for this moment.")),e.createElement("thead",null,e.createElement("tr",null,e.createElement("th",null,"State"),e.createElement("th",null,"Labels"),e.createElement("th",null,"Info"))),e.createElement("tbody",null,n.instances.map(({state:r,info:o,labels:i},c)=>{const l=(0,Qn.P3)(i);return e.createElement("tr",{key:c},e.createElement("td",null,e.createElement(Mn.l,{state:r})),e.createElement("td",null,e.createElement(bn.P,{tags:l,className:a.tagList})),e.createElement("td",null,o&&e.createElement(he.u,{content:o},e.createElement(q.J,{name:"info-circle"}))))})))}const Wn=t=>({table:(0,d.css)` width: 100%; margin: ${t.spacing(2,0)}; caption { caption-side: top; color: ${t.colors.text.primary}; & > span { font-size: ${t.typography.bodySmall.fontSize}; color: ${t.colors.text.secondary}; } } td, th { padding: ${t.spacing(1,1)}; } td + td, th + th { padding-left: ${t.spacing(3)}; } thead th { &:nth-child(1) { width: 80px; } &:nth-child(2) { width: auto; } &:nth-child(3) { width: 40px; } } td:nth-child(3) { text-align: center; } tbody tr:nth-child(2n + 1) { background-color: ${t.colors.background.secondary}; } `,tagList:(0,d.css)` justify-content: flex-start; `}),Un=({value:t,onChange:a,dataSourceName:n,showPreviewAlertsButton:r=!0})=>{const o=(0,S.wW)(zn),{mapToValue:i,mapToQuery:c}=On(n),l=c({refId:"A",hide:!1},t),{error:u,loading:g,value:m}=(0,Y.Z)(()=>(0,z.F)().get(n),[n]),E=(0,e.useCallback)(T=>{a(i(T))},[a,i]),[y,h]=je(),f=async()=>{h()};if(g||m?.name!==n)return null;const C=(0,z.F)().getInstanceSettings(n);if(u||!m||!m?.components?.QueryEditor||!C){const T=u?.message||"Data source plugin does not export any Query Editor component";return e.createElement("div",null,"Could not load query editor due to: ",T)}const I=y?.data.state===G.Gu.Done,w=m?.components?.QueryEditor,W=y?.data?.series?.find(T=>T.name==="evaluation results"),L=W&&W.fields.some(T=>T.values.length>0);return e.createElement(e.Fragment,null,e.createElement(Nn.n,{instanceSettings:C},e.createElement(w,{query:l,queries:[l],app:ye.zj.CloudAlerting,onChange:E,onRunQuery:V.noop,datasource:m})),r&&e.createElement("div",{className:o.preview},e.createElement(D.zx,{type:"button",onClick:f,disabled:y?.data.state===G.Gu.Loading},"Preview alerts"),I&&!L&&e.createElement(b.b,{title:"Alerts preview",severity:"info",className:o.previewAlert},"There are no firing alerts for your query."),L&&e.createElement(Gn,{preview:W})))},zn=t=>({preview:(0,d.css)` padding: ${t.spacing(2,0)}; max-width: ${t.breakpoints.values.xl}px; `,previewAlert:(0,d.css)` margin: ${t.spacing(1,0)}; `});function On(t){return(0,e.useMemo)(()=>{switch((0,z.F)().getInstanceSettings(t)?.type){case"loki":case"prometheus":return{mapToValue:n=>n.expr,mapToQuery:(n,r)=>({...n,expr:r})};default:throw new Error(`${t} is not supported as an expression editor`)}},[t])}var Vn=s(68525);const Bn=({condition:t,onSetCondition:a,queries:n,panelData:r,onUpdateRefId:o,onRemoveExpression:i,onUpdateExpressionType:c,onUpdateQueryExpression:l})=>{const u=(0,e.useMemo)(()=>n.reduce((m,E)=>(0,se.j)(E.model)?m.concat(E.model):m,[]),[n]),g=(0,S.wW)(Hn);return e.createElement("div",{className:g.wrapper},u.map(m=>{const E=r[m.refId],y=t===m.refId,h=y&&E?(0,Q.Vp)(E.series):void 0,f=y&&E?(0,Q.Yq)(E.series):void 0;return e.createElement(Vn.A2,{key:m.refId,isAlertCondition:y,data:E,error:h,warning:f,queries:n,query:m,onSetCondition:a,onRemoveExpression:i,onUpdateRefId:o,onUpdateExpressionType:c,onChangeQuery:l})}))},Hn=t=>({wrapper:(0,d.css)` display: flex; gap: ${t.spacing(2)}; align-content: stretch; flex-wrap: wrap; `});var Je=s(85532),Ae=s(76305),jn=s(10186),Zn=s(5926),Xe=s(60644),Kn=s(47802),Yn=s(51145),Jn=s(99633),Xn=s(16532),kn=s(2184);const qn=({query:t,queryOptions:a,onChangeTimeRange:n,onChangeQueryOptions:r,index:o})=>{const i=(0,S.wW)(_n),[c,l]=(0,e.useState)(!1),u=t.relativeTimeRange?(0,Ae.relativeToTimeRange)(t.relativeTimeRange):void 0;return e.createElement(e.Fragment,null,e.createElement(Xn.P,{content:e.createElement("div",{className:i.container},e.createElement("div",null,n&&e.createElement("div",{className:i.timeRangeContainer},e.createElement("span",{className:i.timeRangeLabel},"Time Range"),e.createElement(kn.x,{timeRange:t.relativeTimeRange??(0,oe.Rr)(),onChange:g=>n(g,o)}))),e.createElement("div",{className:i.queryOptions},e.createElement(ra,{options:a,onChange:g=>r(g,o)}),e.createElement(oa,{options:a,onChange:g=>r(g,o)}))),closeButton:!0,placement:"bottom-start"},e.createElement("button",{type:"button",className:i.actionLink,onClick:()=>l(!c)},"Options ",c?e.createElement(q.J,{name:"angle-right"}):e.createElement(q.J,{name:"angle-down"}))),e.createElement("div",{className:i.staticValues},e.createElement("span",null,(0,Jn.CQ)(u?.from).locale("en").fromNow(!0)),a.maxDataPoints&&e.createElement("span",null,", MD = ",a.maxDataPoints),a.minInterval&&e.createElement("span",null,", Min. Interval = ",a.minInterval)))},_n=t=>{const a=(0,D.gN)(t);return{container:(0,d.css)` display: flex; flex-direction: column; gap: 10px; `,timeRangeContainer:(0,d.css)` display: flex; `,timeRangeLabel:(0,d.css)` width: 20%; `,queryOptions:(0,d.css)` margin-bottom: -${t.spacing(2)}; label { line-height: 12px; padding: 0px; } `,staticValues:(0,d.css)` color: ${t.colors.text.secondary}; margin-right: ${t.spacing(1)}; `,actionLink:(0,d.css)` ${a}; color: ${t.colors.text.link}; cursor: pointer; &:hover { text-decoration: underline; } `}};var ke=s(98445);const ea=43200,ta="1s",na=({data:t,error:a,dsSettings:n,index:r,onChangeDataSource:o,onChangeQuery:i,onChangeTimeRange:c,onRunQueries:l,onRemoveQuery:u,onDuplicateQuery:g,query:m,queries:E,thresholds:y,thresholdsType:h,onChangeThreshold:f,condition:C,onSetCondition:I,onChangeQueryOptions:w})=>{const W=(0,S.wW)(Pe),[L,T]=(0,e.useState)(),ee={...L?.getDefaultQuery?L.getDefaultQuery(ye.zj.UnifiedAlerting):{},...(0,V.cloneDeep)(m.model)};function P(){const A=(0,S.wW)(Pe);return e.createElement("div",{className:A.dsTooltip},e.createElement(he.u,{content:e.createElement(e.Fragment,null,"Not finding the data source you want? Some data sources are not supported for alerting. Click on the icon for more information.")},e.createElement(q.J,{name:"info-circle",onClick:()=>window.open(" https://grafana.com/docs/grafana/latest/alerting/fundamentals/data-source-alerting/","_blank")})))}function te({query:A,error:ne,index:B}){const ae={maxDataPoints:A.model.maxDataPoints,minInterval:A.model.intervalMs?(0,Ve.gS)(A.model.intervalMs):void 0},j={maxDataPoints:ae.maxDataPoints,minInterval:ae.minInterval};return e.createElement(F.K,{direction:"row",alignItems:"baseline",gap:1},e.createElement(P,null),e.createElement(qn,{onChangeTimeRange:c,query:A,queryOptions:j,onChangeQueryOptions:w,index:B}),e.createElement(Yn._,{onSetCondition:()=>I(A.refId),enabled:C===A.refId,error:ne}))}const de=t.state!==G.Gu.NotStarted;return e.createElement(F.K,{direction:"column",gap:.5},e.createElement("div",{className:W.wrapper},e.createElement(Kn.x,{alerting:!0,collapsable:!1,dataSource:n,onDataSourceLoaded:T,onChangeDataSource:A=>o(A,r),id:m.refId,index:r,key:m.refId,data:t,query:ee,onChange:A=>i(A,r),onRemoveQuery:u,onAddQuery:()=>g((0,V.cloneDeep)(m)),onRunQuery:l,queries:E,renderHeaderExtras:()=>e.createElement(te,{query:m,index:r,error:a}),app:ye.zj.UnifiedAlerting,hideDisableQuery:!0})),de&&e.createElement(ke.l,{data:t,thresholds:y,thresholdsType:h,onThresholdsChange:f?A=>f(A,r):void 0}))},aa=({children:t})=>{const a=(0,S.wW)(Pe);return e.createElement("div",{className:a.wrapper},t)};function ra({options:t,onChange:a}){const n=t.maxDataPoints??"",r=o=>{const i=parseInt(o.target.value,10),c=isNaN(i)||i===0?void 0:i;c!==t.maxDataPoints&&a({...t,maxDataPoints:c})};return e.createElement(F.K,{direction:"row",alignItems:"baseline",gap:1},e.createElement(Xe.c,{width:8,tooltip:e.createElement(e.Fragment,null,"The maximum data points per series. Used directly by some data sources and used in calculation of auto interval. With streaming data this value is used for the rolling buffer.")},"Max data points"),e.createElement(fe.I,{type:"number",className:"width-6",placeholder:ea.toLocaleString(),spellCheck:!1,onBlur:r,defaultValue:n}))}function oa({options:t,onChange:a}){const n=t.minInterval??"",r=o=>{const i=o.target.value;i!==n&&a({...t,minInterval:i})};return e.createElement(F.K,{direction:"row",alignItems:"baseline",gap:1},e.createElement(Xe.c,{width:8,tooltip:e.createElement(e.Fragment,null,"A lower limit for the interval. Recommended to be set to write frequency, for example ",e.createElement("code",null,"1m")," if your data is written every minute.")},"Min interval"),e.createElement(fe.I,{type:"text",className:"width-6",placeholder:ta,spellCheck:!1,onBlur:r,defaultValue:n}))}const Pe=t=>({wrapper:(0,d.css)` label: AlertingQueryWrapper; margin-bottom: ${t.spacing(1)}; border: 1px solid ${t.colors.border.weak}; border-radius: ${t.shape.borderRadius(1)}; button { overflow: visible; } `,queryOptions:(0,d.css)` margin-bottom: -${t.spacing(2)}; `,dsTooltip:(0,d.css)` display: flex; align-items: center; &:hover { opacity: 0.85; cursor: pointer; } `});class sa extends e.PureComponent{constructor(a){super(a),this.onRemoveQuery=n=>{const{queries:r,onQueriesChange:o}=this.props;o(r.filter(i=>i.refId!==n.refId))},this.onChangeTimeRange=(n,r)=>{const{queries:o,onQueriesChange:i}=this.props;i(o.map((c,l)=>l!==r?c:{...c,relativeTimeRange:n}))},this.onChangeQueryOptions=(n,r)=>{const{queries:o,onQueriesChange:i}=this.props;i(o.map((c,l)=>l!==r?c:{...c,model:{...c.model,maxDataPoints:n.maxDataPoints,intervalMs:n.minInterval?Ae.intervalToMs(n.minInterval):void 0}}))},this.onChangeDataSource=(n,r)=>{const{queries:o,onQueriesChange:i}=this.props,c=o.map((l,u)=>{if(u!==r)return l;const g=this.getDataSourceSettings(l);return n.type===g?.type?la(l,n):ia(l,n)});i(c)},this.onChangeQuery=(n,r)=>{const{queries:o,onQueriesChange:i}=this.props;i(o.map((c,l)=>l!==r?c:{...c,refId:n.refId,queryType:c.model.queryType??"",model:{...c.model,...n,datasource:n.datasource}}))},this.onDragEnd=n=>{const{queries:r,onQueriesChange:o}=this.props;if(!n||!n.destination)return;const i=n.source.index,c=n.destination.index;if(i===c)return;const l=Array.from(r),[u]=l.splice(i,1);l.splice(c,0,u),o(l)},this.getDataSourceSettings=n=>(0,z.F)().getInstanceSettings(n.datasourceUid)}render(){const{queries:a,expressions:n}=this.props,r=(0,Q.Fu)([...a,...n]);return e.createElement(Je.Z5,{onDragEnd:this.onDragEnd},e.createElement(Je.bK,{droppableId:"alerting-queries",direction:"vertical"},o=>e.createElement("div",{ref:o.innerRef,...o.droppableProps},e.createElement(F.K,{direction:"column"},a.map((i,c)=>{const l=this.props.data?.[i.refId]??{series:[],state:G.Gu.NotStarted},u=this.getDataSourceSettings(i),m=this.props.condition===i.refId?(0,Q.Vp)(l.series):void 0;return u?e.createElement(na,{index:c,key:i.refId,dsSettings:u,data:l,error:m,query:i,onChangeQuery:this.onChangeQuery,onRemoveQuery:this.onRemoveQuery,queries:[...a,...n],onChangeDataSource:this.onChangeDataSource,onDuplicateQuery:this.props.onDuplicateQuery,onChangeTimeRange:this.onChangeTimeRange,onChangeQueryOptions:this.onChangeQueryOptions,thresholds:r[i.refId]?.config,thresholdsType:r[i.refId]?.mode,onRunQueries:this.props.onRunQueries,condition:this.props.condition,onSetCondition:this.props.onSetCondition}):e.createElement(ca,{key:`${i.refId}-${c}`,index:c,model:i.model,onUpdateDatasource:()=>{const E=(0,Zn.ak)().getInstanceSettings(null);E&&this.onChangeDataSource(E,c)},onRemoveQuery:()=>{this.onRemoveQuery(i)}})}),o.placeholder))))}}function la(t,a){return{...t,model:{...(0,V.omit)(t.model,"datasource"),datasource:{type:a.type,uid:a.uid}},datasourceUid:a.uid}}function ia(t,a){return{refId:t.refId,relativeTimeRange:t.relativeTimeRange,queryType:"",datasourceUid:a.uid,model:{refId:t.refId,hide:!1,datasource:{type:a.type,uid:a.uid}}}}const ca=({index:t,onUpdateDatasource:a,onRemoveQuery:n,model:r})=>{const o=r.refId,[i,c]=(0,e.useState)(!1),l=()=>{c(g=>!g)},u=()=>{a()};return e.createElement(aa,null,e.createElement(jn.t,{title:o,draggable:!0,index:t,id:o,isOpen:!0,collapsable:!1},e.createElement(H.Z,null,e.createElement(H.Z.Heading,null,"This datasource has been removed"),e.createElement(H.Z.Description,null,"The datasource for this query was not found, it was either removed or is not installed correctly."),e.createElement(H.Z.Figure,null,e.createElement(q.J,{name:"question-circle"})),e.createElement(H.Z.Actions,null,e.createElement(D.zx,{key:"update",variant:"secondary",onClick:u},"Update datasource"),e.createElement(D.zx,{key:"remove",variant:"destructive",onClick:n},"Remove query")),e.createElement(H.Z.SecondaryActions,null,e.createElement(D.zx,{key:"details",onClick:l,icon:i?"angle-up":"angle-down",fill:"text",size:"sm"},"Show details"))),i&&e.createElement("div",null,e.createElement("pre",null,e.createElement("code",null,JSON.stringify(r,null,2))))))},ua=({queries:t,expressions:a,panelData:n,onRunQueries:r,onChangeQueries:o,onDuplicateQuery:i,condition:c,onSetCondition:l})=>{const u=(0,S.wW)(da);return e.createElement("div",{className:u.container},e.createElement(sa,{data:n,queries:t,expressions:a,onRunQueries:r,onQueriesChange:o,onDuplicateQuery:i,condition:c,onSetCondition:l}))},da=t=>({container:(0,d.css)` background-color: ${t.colors.background.primary}; height: 100%; `});var ma=s(66805),pa=s(26858);const fa=({queries:t,onChangeQuery:a,runQueries:n,panelData:r,dataSourceName:o})=>{const[i,c]=(0,e.useState)({series:[],state:ma.Gu.NotStarted,timeRange:(0,pa.$t)().timeRange()}),l=(0,S.wW)(ga);(0,e.useEffect)(()=>{c(r?.[t[0]?.refId])},[r,t]);const{error:u,loading:g,value:m}=(0,Y.Z)(()=>(0,z.F)().get(o),[o]),E=f=>{const C=t[0],I=(0,z.F)().getInstanceSettings(o)?.uid;if(!(0,$.tO)(f)||!I)return;const w=f.expr,W={...C,...f,datasourceUid:I,expr:w,model:{expr:w,datasource:f.datasource,refId:f.refId,editorMode:f.editorMode,instant:!!f.instant,range:!!f.range,legendFormat:f.legendFormat}};a([W])};if(g||m?.name!==o)return null;const y=(0,z.F)().getInstanceSettings(o);if(u||!m||!m?.components?.QueryEditor||!y){const f=u?.message||"Data source plugin does not export any Query Editor component";return e.createElement("div",null,"Could not load query editor due to: ",f)}const h=m.components.QueryEditor;return e.createElement(e.Fragment,null,t.length&&e.createElement(h,{query:t[0],queries:t,app:ye.zj.UnifiedAlerting,onChange:E,onRunQuery:n,datasource:m}),i&&e.createElement("div",{className:l.vizWrapper},e.createElement(ke.l,{data:i})))},ga=t=>({vizWrapper:(0,d.css)` margin: ${t.spacing(1,0)}; `});var va=s(53229),qe=s(84749);function Ea({value:t,disabled:a,...n}){const r=Ye(),{loading:o=!0}=(0,Y.Z)(()=>(0,qe.WI)((0,X.dV)()),[qe.WI]),i=(0,e.useCallback)(c=>!!r.find(({id:l})=>l===c.id),[r]);return e.createElement(va.q,{disabled:o||a,noDefault:!0,alerting:!0,filter:i,current:t,...n})}const ha=({disabled:t,onChangeCloudDatasource:a})=>{const{control:n,formState:{errors:r},setValue:o,watch:i}=(0,M.Gc)(),c=(0,S.wW)(ya),l=i("type");return e.createElement(e.Fragment,null,e.createElement("div",{className:c.flexRow},(l===p.$.cloudAlerting||l===p.$.cloudRecording)&&e.createElement(J.g,{className:c.formInput,label:t?"Data source":"Select data source",error:r.dataSourceName?.message,invalid:!!r.dataSourceName?.message,"data-testid":"datasource-picker"},e.createElement(ie.g,{render:({field:{onChange:u,ref:g,...m}})=>e.createElement(Ea,{...m,disabled:t,onChange:E=>{o("location",void 0),o("expression",""),u(E?.name??null),a(E?.uid??null)}}),name:"dataSourceName",control:n,rules:{required:{value:!0,message:"Please select a data source"}}}))))},ya=t=>({formInput:(0,d.css)` width: 330px; & + & { margin-left: ${t.spacing(3)}; } `,flexRow:(0,d.css)` display: flex; flex-direction: row; justify-content: flex-start; align-items: flex-end; `});function xa(){const t=re.Vt.hasAccess(O.AccessControlAction.AlertingRuleCreate,re.Vt.hasEditPermissionInFolders),a=re.Vt.hasAccess(O.AccessControlAction.AlertingRuleExternalWrite,re.Vt.isEditor),n=t?p.$.grafana:p.$.cloudAlerting,r=[];return t&&r.push(p.$.grafana),a&&r.push(p.$.cloudAlerting,p.$.cloudRecording),{enabledRuleTypes:r,defaultRuleType:n}}const Sa=t=>t.filter(a=>a.datasourceUid!==_.Yq).length===1,Ra=({queries:t,ruleFormType:a,editingExistingRule:n,rulesSourcesWithRuler:r})=>{const o=xa(),i=Sa(t),c=t[0]?.datasourceUid??"",l=a===p.$.cloudRecording,u=!n&&!l&&i&&r.some(f=>f.uid===c),g=!n&&!l,m=o.enabledRuleTypes.includes(p.$.grafana),E=o.enabledRuleTypes.includes(p.$.cloudAlerting),y=a===p.$.cloudAlerting&&m&&g,h=a===p.$.grafana&&u&&E&&u;return y||h},Ca=(t,a,n,r)=>a?t===p.$.grafana?{contentText:"Grafana-managed alert rules allow you to create alerts that can act on data from any of our supported data sources, including having multiple data sources in the same rule. You can also add expressions to transform your data and set alert conditions. Using images in alert notifications is also supported. ",title:"This alert rule is managed by Grafana."}:{contentText:"Data source-managed alert rules can be used for Grafana Mimir or Grafana Loki data sources which have been configured to support rule creation. The use of expressions or multiple queries is not supported.",title:`This alert rule is managed by the data source ${n}.`}:r?t===p.$.cloudAlerting?{contentText:"Data source-managed alert rules can be used for Grafana Mimir or Grafana Loki data sources which have been configured to support rule creation. The use of expressions or multiple queries is not supported.",title:`This alert rule is managed by the data source ${n}. If you want to use expressions or have multiple queries, switch to a Grafana-managed alert rule.`}:{contentText:"Grafana-managed alert rules allow you to create alerts that can act on data from any of our supported data sources, including having multiple data sources in the same rule. You can also add expressions to transform your data and set alert conditions. Using images in alert notifications is also supported.",title:"This alert rule will be managed by Grafana. The selected data source is configured to support rule creation."}:{contentText:"Grafana-managed alert rules allow you to create alerts that can act on data from any of our supported data sources, including having multiple data sources in the same rule. You can also add expressions to transform your data and set alert conditions. Using images in alert notifications is also supported.",title:"Based on the data sources selected, this alert rule is managed by Grafana."};function _e({editingExistingRule:t,rulesSourcesWithRuler:a,queries:n,onClickSwitch:r}){const{getValues:o}=(0,M.Gc)(),[i,c]=o(["type","dataSourceName"]),l=(0,S.wW)(Ia),u=Ra({queries:n,ruleFormType:i,editingExistingRule:t,rulesSourcesWithRuler:a}),g=i===p.$.cloudAlerting?"Data source-managed alert rule":"Grafana-managed alert rule",m=i!==p.$.cloudAlerting?"data source-managed":"Grafana-managed",E=i?Ca(i,t,c??"",u):void 0;return e.createElement("div",{className:l.alert},e.createElement(b.b,{severity:"info",title:g,onRemove:u?r:void 0,buttonContent:`Switch to ${m} alert rule`},e.createElement(F.K,{gap:.5,direction:"row",alignItems:"baseline"},e.createElement("div",{className:l.alertText},E?.title),e.createElement("div",{className:l.needInfo},e.createElement(Te.h,{contentText:E?.contentText??"",externalLink:"https://grafana.com/docs/grafana/latest/alerting/fundamentals/alert-rules/alert-rule-types/",linkText:"Read about alert rule types",title:" Alert rule types"})))))}const Ia=t=>({alertText:(0,d.css)` max-width: fit-content; flex: 1; `,alert:(0,d.css)` margin-top: ${t.spacing(2)}; `,needInfo:(0,d.css)` flex: 1; max-width: fit-content; `});var N=s(34099),wa=s(76897);const Da=t=>{try{return JSON.stringify(t),!1}catch{return!0}},et=(t,a)=>{if(Da(t))return null;if(a.datasourceUid!==_.Yq)return a;{const n=t.find(r=>r.refId===a.model.expression);return n?et(t,n):null}};var tt=s(11122),nt=s(22283);const at=(t,a)=>{const n=t.find(o=>o.refId===a);return n&&et(t,n)},Ta={queries:[]},rt=(0,N.PH)("duplicateQuery"),ot=(0,N.PH)("addNewDataQuery"),xe=(0,N.PH)("setDataQueries"),st=(0,N.PH)("addNewExpression"),lt=(0,N.PH)("removeExpression"),it=(0,N.PH)("removeExpressions"),ct=(0,N.PH)("addExpressions"),ut=(0,N.PH)("updateExpression"),dt=(0,N.PH)("updateExpressionRefId"),mt=(0,N.PH)("rewireExpressions"),pt=(0,N.PH)("updateExpressionType"),ft=(0,N.PH)("updateExpressionTimeRange"),Aa=(0,N.PH)("updateMaxDataPoints"),Pa=(0,N.PH)("updateMinInterval"),$e=(0,N.PH)("setRecordingRulesQueries"),$a=(0,N.Lq)(Ta,t=>{t.addCase(rt,(a,{payload:n})=>{a.queries=Ne(a.queries,n)}).addCase(ot,a=>{const n=(0,k.P)();n&&(a.queries=Ne(a.queries,{datasourceUid:n.uid,model:{refId:"",datasource:{type:n.type,uid:n.uid}}}))}).addCase(xe,(a,{payload:n})=>{const r=a.queries.filter(o=>(0,se.j)(o.model));a.queries=[...n,...r]}).addCase($e,(a,{payload:n})=>{const r=n.recordingRuleQueries[0],o={...r,expr:n.expression,model:r?.model};a.queries=[o]}).addCase(Aa,(a,n)=>{a.queries=a.queries.map(r=>r.refId===n.payload.refId?{...r,model:{...r.model,maxDataPoints:n.payload.maxDataPoints}}:r)}).addCase(Pa,(a,n)=>{a.queries=a.queries.map(r=>r.refId===n.payload.refId?{...r,model:{...r.model,intervalMs:n.payload.minInterval?Ae.intervalToMs(n.payload.minInterval):void 0}}:r)}),t.addCase(st,(a,{payload:n})=>{a.queries=Ne(a.queries,{datasourceUid:_.Yq,model:tt.mV.newQuery({type:n,conditions:[{...nt.R,query:{params:[]}}],expression:""})})}).addCase(lt,(a,{payload:n})=>{a.queries=a.queries.filter(r=>r.refId!==n)}).addCase(it,a=>{a.queries=a.queries.filter(n=>!(0,se.j)(n.model))}).addCase(ct,(a,{payload:n})=>{a.queries=[...a.queries,...n]}).addCase(ut,(a,{payload:n})=>{a.queries=a.queries.map(r=>{const o=at(a.queries,n.expression),i=o?o.relativeTimeRange:(0,oe.Rr)();return r.refId===n.refId&&(r.model=n,n.type===_.Us.resample&&(r.relativeTimeRange=i)),r})}).addCase(ft,a=>{const n=a.queries.map(r=>{if(r.datasourceUid===_.Yq){const o=at(a.queries,r.model.expression),i=o?o.relativeTimeRange:(0,oe.Rr)();r.relativeTimeRange=i}return r});a.queries=n}).addCase(dt,(a,{payload:n})=>{const{newRefId:r,oldRefId:o}=n;if((0,Q.Dr)(a.queries,r))return;const c=(0,Q.Ry)(a.queries,o,r);a.queries=c.map(l=>l.refId===o?{...l,refId:r,model:{...l.model,refId:r}}:l)}).addCase(mt,(a,{payload:n})=>{a.queries=(0,Q.Ry)(a.queries,n.oldRefId,n.newRefId)}).addCase(pt,(a,n)=>{a.queries=a.queries.map(r=>r.refId===n.payload.refId?{...r,model:{...tt.mV.newQuery({type:n.payload.type,conditions:[{...nt.R,query:{params:[]}}],expression:""}),refId:n.payload.refId}}:r)})}),Ne=(t,a)=>{const n=(0,wa.Hs)(t),r={...a,refId:n,queryType:"",model:{...a.model,hide:!1,refId:n},relativeTimeRange:a.relativeTimeRange??Na(a.model)};return[...t,r]},Na=t=>{if(!(0,se.j)(t))return(0,oe.Rr)()};var ba=s(73475);function Qa(){const[t,a]=(0,e.useState)({}),n=(0,e.useRef)(new ba.v);(0,e.useEffect)(()=>{const l=n.current;return l.get().subscribe(u=>{a(u)}),()=>{l.destroy()}},[]);const r=(0,e.useCallback)(()=>{a({})},[]),o=(0,e.useCallback)(()=>{n.current.cancel()},[]),i=(0,e.useCallback)(l=>{n.current.run(l)},[]),c=(0,e.useMemo)(()=>Object.values(t).some(l=>l.state===G.Gu.Loading),[t]);return{queryPreviewData:t,runQueries:i,cancelQueries:o,isPreviewLoading:c,clearPreviewData:r}}const Ma=({editingExistingRule:t,onDataChange:a})=>{const{setValue:n,getValues:r,watch:o,formState:{errors:i},control:c}=(0,M.Gc)(),{queryPreviewData:l,runQueries:u,cancelQueries:g,isPreviewLoading:m,clearPreviewData:E}=Qa(),y={queries:r("queries")},[{queries:h},f]=(0,e.useReducer)($a,y),[C,I,w]=o(["type","condition","dataSourceName"]),W=C===p.$.grafana,L=C===p.$.cloudRecording,T=C===p.$.cloudAlerting,ue=(0,O.useDispatch)();(0,e.useEffect)(()=>{ue((0,X.dV)())},[ue]);const ee=Ye(),P=(0,e.useCallback)(()=>{u(r("queries"))},[u,r]);(0,e.useEffect)(()=>{n("queries",h,{shouldValidate:!1})},[h,u,n]);const te=(0,k.P)()===void 0,de=(0,e.useMemo)(()=>h.filter(v=>!(0,se.j)(v.model)),[h]),A=(0,e.useMemo)(()=>h.filter(v=>(0,se.j)(v.model)),[h]),ne=h.length===0;(0,e.useEffect)(()=>{const v=r("condition");if(!v||p.$.cloudRecording)return;const x=(0,Q.Vp)(l[v]?.series||[]);a(x?.message||"")},[l,r,a]);const B=(0,e.useCallback)(v=>{v&&(P(),n("condition",v))},[P,n]),ae=(0,e.useCallback)((v,x)=>{(0,Q.Dr)(h,x)||(f(dt({oldRefId:v,newRefId:x})),I===v&&B(x))},[I,h,B]),j=Ga(),Se=(0,e.useCallback)(v=>{n("queries",v,{shouldValidate:!1}),j(v),f(xe(v)),f(ft());const[x,U]=(0,Q.eW)(h,v);x&&U&&f(mt({oldRefId:x,newRefId:U}))},[h,n,j]),Me=(0,e.useCallback)(v=>{const x=v[0],U=(0,z.F)().getInstanceSettings(x.datasourceUid);if(!U)throw new Error("The Data source has not been defined.");if(!(0,$.tO)(x.model))return;const Rt=x.model.expr;n("queries",v,{shouldValidate:!1}),n("dataSourceName",U.name),n("expression",Rt),f($e({recordingRuleQueries:v,expression:Rt})),P()},[P,n]),R=ee[0];(0,e.useEffect)(()=>{if(E(),C===p.$.cloudRecording){const v=r("expression");if(!R)return;const U={refId:"A",datasourceUid:t&&(0,z.F)().getInstanceSettings(w)?.uid||R.uid,queryType:"",relativeTimeRange:(0,oe.Rr)(),expr:v,model:{refId:"A",hide:!1,expr:v}};f($e({recordingRuleQueries:[U],expression:v}))}},[C,R,t,r,w,E]);const Fe=(0,e.useCallback)(v=>{f(rt(v))},[]);(0,e.useEffect)(()=>{if(!(0,Q.Dr)(h,I)){const v=h.at(-1)?.refId??null;B(v)}},[I,h,B]);const Z=(0,e.useCallback)(v=>{f(st(v))},[f]),K=(0,S.wW)(La),ar=(0,e.useCallback)(v=>{const x=(0,V.cloneDeep)(h);x[0].datasourceUid=v,n("queries",x,{shouldValidate:!1}),j(x),f(xe(x))},[h,n,j,f]),rr=v=>{const x=(0,V.cloneDeep)(h);if(x[0].model)if((0,$.tO)(x[0].model))x[0].model.expr=v;else{const U={...(0,V.cloneDeep)(x[0].model),expr:v};x[0].model=U}n("queries",x,{shouldValidate:!1}),j(x),f(xe(x)),P()},Et=(0,e.useCallback)(()=>f(it()),[f]),ht=(0,e.useCallback)(v=>f(ct(v)),[f]),[Re,yt]=(0,e.useState)([]),[Le,or]=(0,e.useState)(null),xt=(0,e.useCallback)(()=>{ht(Re)},[Re,ht]),St=(0,e.useCallback)(()=>{if(r("type")===p.$.cloudAlerting)n("type",p.$.grafana),Re.length>0&&xt(),Le&&n("condition",Le);else{n("type",p.$.cloudAlerting);const x=h.filter(U=>U.datasourceUid===_.Yq);yt(x),Et(),or(I)}},[r,n,h,Et,xt,yt,Re,Le,I]);return e.createElement(ce.z,{stepNo:2,title:C!==p.$.cloudRecording?"Define query and alert condition":"Define query"},(C===p.$.cloudRecording||C===p.$.cloudAlerting)&&e.createElement(ha,{onChangeCloudDatasource:ar,disabled:t}),L&&w&&e.createElement(J.g,{error:i.expression?.message,invalid:!!i.expression?.message},e.createElement(fa,{dataSourceName:w,queries:h,runQueries:P,onChangeQuery:Me,panelData:l})),T&&w&&e.createElement(F.K,{direction:"column"},e.createElement(J.g,{error:i.expression?.message,invalid:!!i.expression?.message},e.createElement(ie.g,{name:"expression",render:({field:{ref:v,...x}})=>e.createElement(Un,{...x,dataSourceName:w,showPreviewAlertsButton:!L,onChange:rr}),control:c,rules:{required:{value:!0,message:"A valid expression is required"}}})),e.createElement(_e,{editingExistingRule:t,queries:h,rulesSourcesWithRuler:ee,onClickSwitch:St})),W&&e.createElement(F.K,{direction:"column"},e.createElement(F.K,{direction:"row",gap:1,alignItems:"baseline"},e.createElement("div",{className:K.mutedText},"Define queries and/or expressions and then choose one of them as the alert rule condition. This is the threshold that an alert rule must meet or exceed in order to fire."),e.createElement(Te.h,{contentText:`An alert rule consists of one or more queries and expressions that select the data you want to measure. Define queries and/or expressions and then choose one of them as the alert rule condition. This is the threshold that an alert rule must meet or exceed in order to fire. For more information on queries and expressions, see Query and transform data.`,externalLink:"https://grafana.com/docs/grafana/latest/panels-visualizations/query-transform-data/",linkText:"Read about query and condition",title:"Define query and alert condition"})),e.createElement(ua,{queries:de,expressions:A,onRunQueries:P,onChangeQueries:Se,onDuplicateQuery:Fe,panelData:l,condition:I,onSetCondition:B}),e.createElement(he.u,{content:"You appear to have no compatible data sources",show:te},e.createElement(D.zx,{type:"button",onClick:()=>{f(ot())},variant:"secondary","aria-label":Tn.wl.components.QueryTab.addQuery,disabled:te,className:K.addQueryButton},"Add query")),e.createElement(_e,{editingExistingRule:t,rulesSourcesWithRuler:ee,queries:h,onClickSwitch:St}),e.createElement(Ze.x,{element:"h5"},"Expressions"),e.createElement("div",{className:K.mutedText},"Manipulate data returned from queries with math and other operations."),e.createElement(Bn,{queries:h,panelData:l,condition:I,onSetCondition:B,onRemoveExpression:v=>{f(lt(v))},onUpdateRefId:ae,onUpdateExpressionType:(v,x)=>{f(pt({refId:v,type:x}))},onUpdateQueryExpression:v=>{f(ut(v))}}),e.createElement(F.K,{direction:"row"},Ge.config.expressionsEnabled&&e.createElement(Fa,{onClickType:Z}),m&&e.createElement(D.zx,{icon:"fa fa-spinner",type:"button",variant:"destructive",onClick:g},"Cancel"),!m&&e.createElement(D.zx,{icon:"sync",type:"button",onClick:P,disabled:ne},"Preview")),ne&&e.createElement(b.b,{title:"No queries or expressions have been configured",severity:"warning"},"Create at least one query or expression to be alerted on")))};function Fa({onClickType:t}){const a=e.createElement(An.v,null,_.EJ.map(n=>e.createElement(he.u,{key:n.value,content:n.description??"",placement:"right"},e.createElement(Pn.s,{key:n.value,onClick:()=>t(n.value??_.Us.math),label:n.label??""}))));return e.createElement($n.L,{overlay:a},e.createElement(D.zx,{variant:"secondary"},"Add expression",e.createElement(q.J,{name:"angle-down"})))}const La=t=>({mutedText:(0,d.css)` color: ${t.colors.text.secondary}; font-size: ${t.typography.size.sm}; margin-top: ${t.spacing(-1)}; `,addQueryButton:(0,d.css)` width: fit-content; `,helpInfo:(0,d.css)` display: flex; flex-direction: row; align-items: center; width: fit-content; font-weight: ${t.typography.fontWeightMedium}; margin-left: ${t.spacing(1)}; font-size: ${t.typography.size.sm}; cursor: pointer; `,helpInfoText:(0,d.css)` margin-left: ${t.spacing(.5)}; text-decoration: underline; `,infoLink:(0,d.css)` color: ${t.colors.text.link}; `}),Ga=()=>{const{setValue:t}=(0,M.Gc)();return a=>{const n=a[0];if(!n)return;const r=(0,z.F)().getInstanceSettings(n.datasourceUid);if(!r)throw new Error("The Data source has not been defined.");if(t("dataSourceName",r.name),(0,$.tO)(n.model)){const o=n.model.expr;t("expression",o)}}},Wa={message:"Recording rule name must be valid metric name. It may only contain letters, numbers, and colons. It may not contain whitespace.",value:/^[a-zA-Z_:][a-zA-Z0-9_:]*$/},Ua=()=>{const t=(0,S.wW)(gt),{register:a,watch:n,formState:{errors:r}}=(0,M.Gc)(),o=n("type");return e.createElement(ce.z,{stepNo:1,title:"Set alert rule name."},e.createElement(J.g,{className:t.formInput,label:"Rule name",description:"Name for the alert rule.",error:r?.name?.message,invalid:!!r.name?.message},e.createElement(fe.I,{id:"name",...a("name",{required:{value:!0,message:"Must enter an alert name"},pattern:o===p.$.cloudRecording?Wa:void 0}),placeholder:"Give your alert rule a name."})))},be=({existing:t,prefill:a})=>{const n=(0,S.wW)(gt),r=(0,O.useDispatch)(),o=(0,bt.iG)(),[i]=(0,Qt.K)(),[c,l]=(0,e.useState)(!1),[u,g]=(0,e.useState)(t?.group.interval??$.EB),m=(0,Dt.UO)(),E=(0,Q.KP)(m.type),y=m.id,h=i.returnTo??"/alerting/list",[f,C]=(0,e.useState)(!1),I=(0,e.useMemo)(()=>t?Ba(t):a?Va(a):typeof i.defaults=="string"?Oa(i.defaults,E):{...(0,$.uZ)(),condition:"C",queries:(0,$.s0)(),type:E||p.$.grafana,evaluateEvery:u},[t,a,i,u,E]),w=(0,M.cI)({mode:"onSubmit",defaultValues:I,shouldFocusError:!0}),{handleSubmit:W,watch:L}=w,T=L("type"),ue=L("dataSourceName"),ee=!!(T&&(T===p.$.grafana||ue)),P=(0,ge._)(R=>R.ruleForm.saveRule)||ve.oq;(0,ze.x)(R=>R.unifiedAlerting.ruleForm.saveRule=ve.oq);const[te,de]=(0,e.useState)(""),A=(R="")=>{de(R)},ne=(R,Fe)=>{if(te!==""){o.error(te);return}r((0,X.wy)({values:{...I,...R,annotations:R.annotations?.map(({key:Z,value:K})=>({key:Z.trim(),value:K.trim()})).filter(({key:Z,value:K})=>!!Z&&!!K)??[],labels:R.labels?.map(({key:Z,value:K})=>({key:Z.trim(),value:K.trim()})).filter(({key:Z})=>!!Z)??[]},existing:t,redirectOnSave:Fe?h:void 0,initialAlertRuleName:I.name,evaluateEvery:u}))},B=()=>{if(t){const R=Ee.Zk(t.ruleSourceName,t.namespace,t.group.name,t.rule);r((0,X.hS)(R,{navigateTo:"/alerting/list"}))}},ae=R=>{t||(0,Oe.Z0)({grafana_version:Ge.config.buildInfo.version,org_id:re.Vt.user.orgId,user_id:re.Vt.user.id,error:Object.keys(R).toString()}),o.error("There are errors in the form. Please correct them and try again!")},j=()=>{(0,At.PN)(Oe.z7.cancelSavingAlertRule)},Se=L("evaluateEvery");(0,e.useEffect)(()=>g(Se),[Se]);const Me=e.createElement(We.Lh,{height:"auto",justify:"flex-end"},e.createElement(D.zx,{variant:"primary",type:"button",size:"sm",onClick:W(R=>ne(R,!1),ae),disabled:P.loading},P.loading&&e.createElement(Ue.$,{className:n.buttonSpinner,inline:!0}),"Save rule"),e.createElement(D.zx,{variant:"primary",type:"button",size:"sm",onClick:W(R=>ne(R,!0),ae),disabled:P.loading},P.loading&&e.createElement(Ue.$,{className:n.buttonSpinner,inline:!0}),"Save rule and exit"),e.createElement(Tt.Link,{to:h},e.createElement(D.zx,{variant:"secondary",disabled:P.loading,type:"button",onClick:j,size:"sm"},"Cancel")),t?e.createElement(D.zx,{fill:"outline",variant:"destructive",type:"button",onClick:()=>C(!0),size:"sm"},"Delete"):null,t?e.createElement(D.zx,{variant:"secondary",type:"button",onClick:()=>l(!0),disabled:P.loading,size:"sm"},za(L)?"Edit YAML":"View YAML"):null);return e.createElement(M.RV,{...w},e.createElement(Nt.A,{actions:Me}),e.createElement("form",{onSubmit:R=>R.preventDefault(),className:n.form},e.createElement("div",{className:n.contentOuter},e.createElement(Pt.$,{autoHeightMin:"100%",hideHorizontalTrack:!0},e.createElement("div",{className:n.contentInner},e.createElement(Ua,null),e.createElement(Ma,{editingExistingRule:!!t,onDataChange:A}),ee&&e.createElement(e.Fragment,null,T===p.$.grafana&&e.createElement(dn.w,{evaluateEvery:u,setEvaluateEvery:g,existing:!!t}),T===p.$.cloudAlerting&&e.createElement(cn,null),T===p.$.cloudRecording&&e.createElement(wn,null),T!==p.$.cloudRecording&&e.createElement(Mt.Z,null),e.createElement(Rn,{alertUid:y})))))),f?e.createElement($t.s,{isOpen:!0,title:"Delete rule",body:"Deleting this rule will permanently remove it. Are you sure you want to delete this rule?",confirmText:"Yes, delete",icon:"exclamation-triangle",onConfirm:B,onDismiss:()=>C(!1)}):null,c?T===p.$.grafana?e.createElement(mn.i,{alertUid:y,onClose:()=>l(!1)}):e.createElement(Dn.CU,{onClose:()=>l(!1)}):null)},za=t=>{const[a,n]=t(["type","dataSourceName"]);return(a===p.$.cloudAlerting||a===p.$.cloudRecording)&&n!==""},Qe=t=>({...t,queries:t.queries?.map(a=>(0,V.omit)(a,"model.hide"))});function Oa(t,a){let n;try{n=JSON.parse(t)}catch{return{...(0,$.uZ)(),queries:(0,$.s0)()}}return Qe({...(0,$.uZ)(),...n,annotations:(0,$.TN)(n.annotations??[]),queries:n.queries??(0,$.s0)(),type:a||p.$.grafana,evaluateEvery:$.EB})}function Va(t){return Qe({...(0,$.uZ)(),...t})}function Ba(t){return Qe((0,$.DQ)(t))}const gt=t=>({buttonSpinner:(0,d.css)` margin-right: ${t.spacing(1)}; `,form:(0,d.css)` width: 100%; height: 100%; display: flex; flex-direction: column; `,contentInner:(0,d.css)` flex: 1; padding: ${t.spacing(2)}; `,contentOuter:(0,d.css)` background: ${t.colors.background.primary}; border: 1px solid ${t.colors.border.weak}; border-radius: ${t.shape.borderRadius()}; overflow: hidden; flex: 1; margin-top: ${t.spacing(1)}; `,flexRow:(0,d.css)` display: flex; flex-direction: row; justify-content: flex-start; `,formInput:(0,d.css)` width: 275px; & + & { margin-left: ${t.spacing(3)}; } `});var Ha=s(42481),le=s(22446),ja=s(59597);function Za({sourceRuleId:t}){const a=(0,O.useDispatch)(),{loading:n,value:r,error:o}=(0,Y.Z)(()=>a((0,X.on)(t)).unwrap(),[t]);if(n)return e.createElement(Ie.u,{text:"Loading the rule"});if(r){const i=Ya(r),c=(0,$.DQ)(i);return e.createElement(be,{prefill:c})}return o?e.createElement(b.b,{title:"Error",severity:"error"},o.message):e.createElement(b.b,{title:"Cannot copy the rule. The rule does not exist",buttonContent:"Go back to alert list",onRemove:()=>wt.E1.replace((0,ja.u)("/alerting/list"))})}function Ka(t,a){(0,le.Pc)(t)&&(t.grafana_alert.title=a),(0,le.cG)(t)&&(t.alert=a),(0,le.yF)(t)&&(t.record=a)}function Ya(t){const a=(0,V.cloneDeep)(t);return Ka(a.rule,(0,Ha.G)((0,le.PW)(a.rule),a.group.rules.map(le.PW))),(0,le.Pc)(a.rule)&&(a.rule.grafana_alert.uid="",a.rule.grafana_alert.provenance&&(a.group={name:"",rules:a.group.rules})),a}var Ja=s(99322);function Xa({identifier:t,id:a}){(0,ze.x)(m=>m.unifiedAlerting.ruleForm.existingRule=ve.oq);const{loading:n,result:r,error:o,dispatched:i}=(0,ge._)(m=>m.ruleForm.existingRule),c=(0,O.useDispatch)(),{isEditable:l,loading:u}=(0,Ja.M)(Ee.s0(t),r?.rule),g=n||u;return(0,e.useEffect)(()=>{i||c((0,X.on)(t))},[i,c,t]),g||l===void 0?e.createElement(Ie.u,{text:"Loading rule..."}):o?e.createElement(b.b,{severity:"error",title:"Failed to load rule"},o.message):r?l===!1?e.createElement(pe,{title:"Cannot edit rule"},"Sorry! You do not have permission to edit this rule."):e.createElement(be,{existing:r}):e.createElement(pe,{title:"Rule not found"},"Sorry! This rule does not exist.")}var ka=s(81324),qa=s(79003),_a=s(13963);const vt={icon:"bell",id:"alert-rule-view"},er=t=>{if(t==="edit")return{...vt,id:"alert-rule-edit",text:"Edit rule"};if(t==="add")return{...vt,id:"alert-rule-add",text:"Add rule"}},tr=({match:t})=>{const a=(0,O.useDispatch)(),[n]=(0,qa.j)(),{id:r}=t.params,o=Ee.OA(r,!0),i=n.get("copyFrom")??void 0,c=Ee.OA(i),{loading:l=!0}=(0,Y.Z)(async()=>{o&&await a((0,X.nw)({rulesSourceName:o.ruleSourceName}))},[a]),{canCreateGrafanaRules:u,canCreateCloudRules:g,canEditRules:m}=(0,_a.B)(),E=(0,e.useCallback)(()=>{if(!l)return!o&&!u&&!g?e.createElement(pe,{title:"Cannot create rules"},"Sorry! You are not allowed to create rules."):o&&!m(o.ruleSourceName)?e.createElement(pe,{title:"Cannot edit rules"},"Sorry! You are not allowed to edit rules."):o?e.createElement(Xa,{key:r,identifier:o,id:r}):c?e.createElement(Za,{sourceRuleId:c}):e.createElement(be,null)},[g,u,m,c,r,o,l]);return e.createElement(ka.J,{isLoading:l,pageId:"alert-list",pageNav:er(o?"edit":"add")},E())},nr=(0,Ce.Pf)(tr,{style:"page"})},86954:(Ct,me,s)=>{s.d(me,{K:()=>O});var e=s(42844),Y=s(27702),Ce=s(66310);function O(b){const S=(0,Ce.wW)((0,Y.useCallback)(D=>d(D,b),[b]));return Y.createElement("div",{className:S.root},b.children)}const d=(b,S)=>({root:(0,e.css)({display:"flex",flexDirection:S.direction??"row",flexWrap:S.wrap??!0?"wrap":void 0,alignItems:S.alignItems,gap:b.spacing(S.gap??2),flexGrow:S.flexGrow})})}}]); //# sourceMappingURL=AlertingRuleForm.0885ba71cda43804812f.js.map