"use strict";(self.webpackChunkgrafana=self.webpackChunkgrafana||[]).push([[5644],{90950:(te,$,o)=>{o.d($,{n:()=>C});var y=o(9892),h=o(66111),R=o(73446),r=o(72648),N=o(11543),S=o(81764),P=o(8944),v=o(62911);function C({options:T,onOptionsChange:E}){const I=(0,r.wW)(m);return h.createElement("div",{className:I.container},h.createElement("h3",{className:"page-heading"},"Node graph"),h.createElement("div",{className:I.infoText},"Show or hide the node graph visualization",h.createElement(v.j,{hrefSuffix:`${T.type}/#node-graph`})),h.createElement(N.Z,{className:I.row},h.createElement(S._,{tooltip:"Displays the node graph above the trace view. Default: disabled",label:"Enable node graph",labelWidth:26},h.createElement(P.x,{id:"enableNodeGraph",value:T.jsonData.nodeGraph?.enabled,onChange:g=>(0,R.tp)({onOptionsChange:E,options:T},"nodeGraph",{...T.jsonData.nodeGraph,enabled:g.currentTarget.checked})}))))}const m=T=>({infoText:y.css`
    label: infoText;
    padding-bottom: ${T.spacing(2)};
    color: ${T.colors.text.secondary};
  `,container:y.css`
    label: container;
    width: 100%;
  `,row:y.css`
    label: row;
    align-items: baseline;
  `})},48288:(te,$,o)=>{o.d($,{F:()=>E});var y=o(9892),h=o(66111),R=o(73446),r=o(53117),N=o(72648),S=o(11543),P=o(81764),v=o(31403),C=o(46967),m=o(62911),T=o(33045);function E({options:g,onOptionsChange:x}){const k=(0,N.wW)(I);return h.createElement("div",{className:(0,y.css)({width:"100%"})},h.createElement("h3",{className:"page-heading"},"Trace to metrics"),h.createElement("div",{className:k.infoText},"Navigate from a trace span to the selected data source's metrics",h.createElement(m.j,{hrefSuffix:`${g.type}/#trace-to-metrics`})),h.createElement(S.Z,{className:k.row},h.createElement(P._,{tooltip:"The Prometheus data source the trace is going to navigate to",label:"Data source",labelWidth:26},h.createElement(r.q,{inputId:"trace-to-metrics-data-source-picker",pluginId:"prometheus",current:g.jsonData.tracesToMetrics?.datasourceUid,noDefault:!0,width:40,onChange:O=>(0,R.tp)({onOptionsChange:x,options:g},"tracesToMetrics",{...g.jsonData.tracesToMetrics,datasourceUid:O.uid})})),g.jsonData.tracesToMetrics?.datasourceUid?h.createElement(v.zx,{type:"button",variant:"secondary",size:"sm",fill:"text",onClick:()=>{(0,R.tp)({onOptionsChange:x,options:g},"tracesToMetrics",{...g.jsonData.tracesToMetrics,datasourceUid:void 0})}},"Clear"):null),h.createElement(S.Z,null,h.createElement(P._,{label:"Span start time shift",labelWidth:26,grow:!0,tooltip:"Shifts the start time of the span. Default: 0 (Time units can be used here, for example: 5s, -1m, 3h)"},h.createElement(C.I,{type:"text",placeholder:"0",width:40,onChange:O=>(0,R.tp)({onOptionsChange:x,options:g},"tracesToMetrics",{...g.jsonData.tracesToMetrics,spanStartTimeShift:O.currentTarget.value}),value:g.jsonData.tracesToMetrics?.spanStartTimeShift||""}))),h.createElement(S.Z,null,h.createElement(P._,{label:"Span end time shift",labelWidth:26,grow:!0,tooltip:"Shifts the end time of the span. Default: 0 (Time units can be used here, for example: 5s, -1m, 3h)"},h.createElement(C.I,{type:"text",placeholder:"0",width:40,onChange:O=>(0,R.tp)({onOptionsChange:x,options:g},"tracesToMetrics",{...g.jsonData.tracesToMetrics,spanEndTimeShift:O.currentTarget.value}),value:g.jsonData.tracesToMetrics?.spanEndTimeShift||""}))),h.createElement(S.Z,null,h.createElement(P._,{tooltip:"Tags that will be used in the metrics query",label:"Tags",labelWidth:26},h.createElement(T.a,{values:g.jsonData.tracesToMetrics?.tags??[],onChange:O=>(0,R.tp)({onOptionsChange:x,options:g},"tracesToMetrics",{...g.jsonData.tracesToMetrics,tags:O})}))),g.jsonData.tracesToMetrics?.queries?.map((O,z)=>h.createElement("div",{key:z,className:k.queryRow},h.createElement(P._,{label:"Link Label",labelWidth:26,tooltip:"Descriptive label for the linked query"},h.createElement(C.I,{label:"Link Label",type:"text",allowFullScreen:!0,value:O.name,width:40,onChange:W=>{let U=g.jsonData.tracesToMetrics?.queries.slice()??[];U[z].name=W.currentTarget.value,(0,R.tp)({onOptionsChange:x,options:g},"tracesToMetrics",{...g.jsonData.tracesToMetrics,queries:U})}})),h.createElement(P._,{label:"Query",labelWidth:10,tooltip:"The Prometheus query that will run when navigating from a trace to metrics. Interpolate tags using the `$__tags` keyword",grow:!0},h.createElement(C.I,{label:"Query",type:"text",allowFullScreen:!0,value:O.query,onChange:W=>{let U=g.jsonData.tracesToMetrics?.queries.slice()??[];U[z].query=W.currentTarget.value,(0,R.tp)({onOptionsChange:x,options:g},"tracesToMetrics",{...g.jsonData.tracesToMetrics,queries:U})}})),h.createElement(v.zx,{variant:"destructive",title:"Remove query",icon:"times",type:"button",onClick:()=>{let W=g.jsonData.tracesToMetrics?.queries.slice();W?.splice(z,1),(0,R.tp)({onOptionsChange:x,options:g},"tracesToMetrics",{...g.jsonData.tracesToMetrics,queries:W})}}))),h.createElement(v.zx,{variant:"secondary",title:"Add query",icon:"plus",type:"button",onClick:()=>{(0,R.tp)({onOptionsChange:x,options:g},"tracesToMetrics",{...g.jsonData.tracesToMetrics,queries:[...g.jsonData.tracesToMetrics?.queries??[],{query:""}]})}},"Add query"))}const I=g=>({infoText:y.css`
    padding-bottom: ${g.spacing(2)};
    color: ${g.colors.text.secondary};
  `,row:y.css`
    label: row;
    align-items: baseline;
  `,queryRow:y.css`
    display: flex;
  `})},91159:(te,$,o)=>{o.d($,{n:()=>S});var y=o(66111),h=o(31439);const R=y.lazy(()=>Promise.all([o.e(4254),o.e(4666),o.e(7142)]).then(o.bind(o,47864))),r=P=>y.createElement(y.Suspense,{fallback:null},y.createElement(R,{...P})),N=P=>{const v=(0,y.useRef)(null),{onRunQuery:C,onChange:m,...T}=P,E=g=>{v.current=g,m(g),C()},I=g=>{m(g)};return y.createElement(r,{onRunQuery:E,onBlur:I,...T})};class S extends y.PureComponent{constructor(v){super(v),this._isMounted=!1,this.onChangeQuery=(C,m)=>{const{query:T,onChange:E,onRunQuery:I}=this.props;if(E){const g={...T,expr:C};E(g),m&&I&&I()}},this.state={labelsLoaded:!1}}async componentDidMount(){this._isMounted=!0,await this.props.datasource.languageProvider.start(),this._isMounted&&this.setState({labelsLoaded:!0})}componentWillUnmount(){this._isMounted=!1}componentDidUpdate(v){const{range:C,datasource:{languageProvider:m}}=this.props;(0,h.rf)(C,v.range)&&m.fetchLabels()}render(){const{ExtraFieldElement:v,query:C,datasource:m,history:T,onRunQuery:E,onQueryType:I}=this.props,g=this.props.placeholder??"Enter a Loki query (run with Shift+Enter)";return y.createElement(y.Fragment,null,y.createElement("div",{className:"gf-form-inline gf-form-inline--xs-view-flex-column flex-grow-1","data-testid":this.props["data-testid"]},y.createElement("div",{className:"gf-form gf-form--grow flex-shrink-1 min-width-15"},y.createElement(N,{datasource:m,history:T??[],onChange:this.onChangeQuery,onRunQuery:E,initialValue:C.expr??"",placeholder:g,onQueryType:I}))),v)}}},31439:(te,$,o)=>{o.d($,{Hk:()=>C,U9:()=>S,_z:()=>m,aC:()=>T,iS:()=>P,rf:()=>R,tU:()=>v});function y(E){return h(E/1e3)}function h(E){return Math.floor(E/60)}function R(E,I){if(E&&I){const g=y(E.from.valueOf())===y(I.from.valueOf()),x=y(E.to.valueOf())===y(I.to.valueOf());return!(g&&x)}return!1}const r=/[*+?()|\\.\[\]{}^$]/g;function N(E){return E.replace(r,"\\$&")}function S(E){return E.replace(/\\/g,"\\\\").replace(/\n/g,"\\n").replace(/"/g,'\\"')}function P(E){return E.replace(/\\n/g,`
`).replace(/\\"/g,'"').replace(/\\\\/g,"\\")}function v(E){return S(N(E))}function C(E,I){return m(I)?v(E):S(E)}function m(E){return!!(E&&(E.includes("=~")||E.includes("!~")))}function T(E){const I=["b","kib","Kib","kb","KB","mib","Mib","mb","MB","gib","Gib","gb","GB","tib","Tib","tb","TB","pib","Pib","pb","PB","eib","Eib","eb","EB"],g=new RegExp(`^(?:-?\\d+(?:\\.\\d+)?)(?:${I.join("|")})$`);return!!E.match(g)}},38435:(te,$,o)=>{o.d($,{d:()=>v});var y=o(9892),h=o(66111),R=o(95831),r=o(2703),N=o(26418),S=o(72648),P=o(39904);function v({title:m,children:T,collapsedInfo:E,queryStats:I}){const[g,x]=(0,R.Z)(!1),k=(0,S.wW)(C),O=()=>{const{text:z,suffix:W}=(0,r.Cf)("bytes")(I.bytes,1);return z+W};return h.createElement("div",{className:k.wrapper},h.createElement(N.Stack,{gap:0,direction:"column"},h.createElement("div",{className:k.header,onClick:x,title:"Click to edit options"},h.createElement("div",{className:k.toggle},h.createElement(P.J,{name:g?"angle-down":"angle-right"})),h.createElement("h6",{className:k.title},m),!g&&h.createElement("div",{className:k.description},E.map((z,W)=>h.createElement("span",{key:W},z)))),g&&h.createElement("div",{className:k.body},T)),I&&h.createElement("p",{className:k.stats},"This query will process approximately ",O(),"."))}const C=m=>({wrapper:(0,y.css)({width:"100%",display:"flex",justifyContent:"space-between",alignItems:"baseline"}),switchLabel:(0,y.css)({color:m.colors.text.secondary,cursor:"pointer",fontSize:m.typography.bodySmall.fontSize,"&:hover":{color:m.colors.text.primary}}),header:(0,y.css)({display:"flex",cursor:"pointer",alignItems:"baseline",color:m.colors.text.primary,"&:hover":{background:m.colors.emphasize(m.colors.background.primary,.03)}}),title:(0,y.css)({flexGrow:1,overflow:"hidden",fontSize:m.typography.bodySmall.fontSize,fontWeight:m.typography.fontWeightMedium,margin:0}),description:(0,y.css)({color:m.colors.text.secondary,fontSize:m.typography.bodySmall.fontSize,paddingLeft:m.spacing(2),gap:m.spacing(2),display:"flex"}),body:(0,y.css)({display:"flex",paddingTop:m.spacing(2),gap:m.spacing(2),flexWrap:"wrap"}),toggle:(0,y.css)({color:m.colors.text.secondary,marginRight:`${m.spacing(1)}`}),stats:(0,y.css)({margin:"0px",color:m.colors.text.secondary,fontSize:m.typography.bodySmall.fontSize})})},45204:(te,$,o)=>{o.d($,{U:()=>S});var y=o(9892),h=o(57706),R=o.n(h),r=o(66111),N=o(72648);function S({query:v,lang:C,className:m}){const T=(0,N.l4)(),E=P(T),I=R().highlight(v,C.grammar,C.name);return r.createElement("div",{className:(0,y.cx)(E.editorField,"prism-syntax-highlight",m),"aria-label":"selector",dangerouslySetInnerHTML:{__html:I}})}const P=v=>({editorField:(0,y.css)({fontFamily:v.typography.fontFamilyMonospace,fontSize:v.typography.bodySmall.fontSize})})},25644:(te,$,o)=>{o.r($),o.d($,{plugin:()=>_a});var y=o(89424),h=o(23588),R=o(82378),r=o(66111),N=o(41818),S=o(35645);function P(){return(0,N.ff)("grafana_traces_cheatsheet_clicked",{datasourceType:"tempo",grafana_version:S.v.buildInfo.version}),r.createElement("div",null,r.createElement("h2",{id:"tempo-cheat-sheet"},"Tempo Cheat Sheet"),r.createElement("p",null,"Tempo is a trace id lookup store. Enter a trace id in the above field and hit \u201CRun Query\u201D to retrieve your trace. Tempo is generally paired with other datasources such as Loki or Prometheus to find traces."),r.createElement("p",null,"Here are some"," ",r.createElement("a",{href:"https://grafana.com/docs/tempo/latest/guides/instrumentation/",target:"blank"},"instrumentation examples")," ","to get you started with trace discovery through logs and metrics (exemplars)."))}var v=o(9892),C=o(42638),m=o(11543),T=o(81764),E=o(2594),I=o(30784),g=o(77117),x=o(72648),k=o(91159),O=o(26418),z=o(52081),W=o(45253),U=o(60499),ie=o(98864),q=o(3153),ut=o(45204),dt=o(68668),mt=o(38435),J=o(82897),K=o(59980),_e=o(49372),gt=o(85850),ht=o(12877),pt=o(7523),We=o(65583),Ue=o(39859),X=o(9471),De=o(59724),Fe=o(86870),xe=o(76997),ae=o(52666),Ve=o(47891),Ee=o(67483),Te=o(76282),ft=o(206),vt=o(99098),yt=o(22069),me=o(20308),oe=o(54899),ge=o(40538),Et=o(8878),Se=o(91162);const Wa={filters:[]};var G=(t=>(t.Resource="resource",t.Span="span",t.Unscoped="unscoped",t))(G||{});const Tt={wordPattern:/(-?\d*\.\d\w*)|([^`~!#%^&*()\-=+\[{\]}\\|;:'",.<>\/?\s]+)/g,brackets:[["{","}"],["(",")"]],autoClosingPairs:[{open:"{",close:"}"},{open:"(",close:")"},{open:'"',close:'"'},{open:"'",close:"'"}],surroundingPairs:[{open:"{",close:"}"},{open:"(",close:")"},{open:'"',close:'"'},{open:"'",close:"'"}],folding:{}},ke=["=","!=",">","<",">=","<=","=~"],St=["=","!=","=~"],bt=["=","!=",">","<",">=","<="],he=["duration","kind","name","status"],Ce=["resource","span"],Dt={ignoreCase:!1,defaultToken:"",tokenPostfix:".traceql",keywords:he.concat(Ce),operators:ke,statusValues:["ok","unset","error","false","true"],symbols:/[=><!~?:&|+\-*\/^%]+/,escapes:/\\(?:[abfnrtv\\"']|x[0-9A-Fa-f]{1,4}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})/,digits:/\d+(_+\d+)*/,octaldigits:/[0-7]+(_+[0-7]+)*/,binarydigits:/[0-1]+(_+[0-1]+)*/,tokenizer:{root:[[/[a-z_.][\w./_-]*(?=\s*(=|!=|>|<|>=|<=|=~|!~))/,"tag"],[/[a-z_.][\w./_-]*/,"tag"],[/[0-9.]+(s|ms|ns|m)/,"number"],[/^\s*[0-9A-Fa-f]+\s*$/,"tag"],[/[a-zA-Z_.]\w*/,{cases:{"@keywords":"type","@statusValues":"type.identifier","@default":"identifier"}}],[/"([^"\\]|\\.)*$/,"string.invalid"],[/'([^'\\]|\\.)*$/,"string.invalid"],[/"/,"string","@string_double"],[/'/,"string","@string_single"],{include:"@whitespace"},[/[{}()\[\]]/,"@brackets"],[/[<>](?!@symbols)/,"@brackets"],[/@symbols/,{cases:{"@operators":"delimiter","@default":""}}],[/(@digits)[eE]([\-+]?(@digits))?[fFdD]?/,"number.float"],[/(@digits)\.(@digits)([eE][\-+]?(@digits))?[fFdD]?/,"number.float"],[/0(@octaldigits)[Ll]?/,"number.octal"],[/0[bB](@binarydigits)[Ll]?/,"number.binary"],[/(@digits)[fFdD]/,"number.float"],[/(@digits)[lL]?/,"number"]],string_double:[[/[^\\"]+/,"string"],[/@escapes/,"string.escape"],[/\\./,"string.escape.invalid"],[/"/,"string","@pop"]],string_single:[[/[^\\']+/,"string"],[/@escapes/,"string.escape"],[/\\./,"string.escape.invalid"],[/'/,"string","@pop"]],clauses:[[/[^(,)]/,"tag"],[/\)/,"identifier","@pop"]],whitespace:[[/[ \t\r\n]+/,"white"]]}},xt={id:"traceql",extensions:[".traceql"],aliases:["tempo","traceql"],mimetypes:[],def:{language:Dt,languageConfiguration:Tt}},Ct={comment:{pattern:/#.*/},"span-set":{pattern:/\{[^}]*}/,inside:{filter:{pattern:/([\w.\/-]+)?(\s*)(([!=+\-<>~]+)\s*("([^"\n&]+)?"?|([^"\n\s&|}]+))?)/g,inside:{comment:{pattern:/#.*/},"label-key":{pattern:/[a-z_.][\w./_-]*(?=\s*(=|!=|>|<|>=|<=|=~|!~))/,alias:"attr-name"},"label-value":{pattern:/("(?:\\.|[^\\"])*")|(\w+)/,alias:"attr-value"}}},punctuation:/[}{&|]/}},number:/\b-?\d+((\.\d*)?([eE][+-]?\d+)?)?\b/,operator:new RegExp("/[-+*/=%^~]|&&?|\\|?\\||!=?|<(?:=>?|<|>)?|>[>=]?|","i"),punctuation:/[{};()`,.]/},je=t=>`{${t.filter(e=>e.tag&&e.operator&&e.value?.length).map(e=>`${Be(e)}${e.tag}${e.operator}${It(e)}`).join(" && ")}}`,It=t=>Array.isArray(t.value)&&t.value.length>1?`"${t.value.join("|")}"`:t.valueType==="string"?`"${t.value}"`:t.value,Be=t=>he.find(e=>e===t.tag)?"":(t.scope===G.Resource||t.scope===G.Span?t.scope?.toLowerCase():"")+".",Ie=t=>Be(t)+t.tag,Nt=t=>t.tag==="name"?"Span Name":(0,J.startCase)(Ie(t));function ze(t,e,a){const n=t.slice(0);return n[e]=a,n}const Ke=t=>{const e={label:t,value:t};switch(t){case"=":e.description="Equals";break;case"!=":e.description="Not equals";break;case">":e.description="Greater";break;case">=":e.description="Greater or Equal";break;case"<":e.description="Less";break;case"<=":e.description="Less or Equal";break;case"=~":e.description="Matches regex";break;case"!~":e.description="Does not match regex";break}return e};var F=o(69407);class Ne extends y.iL{constructor(e,a){super(),this.request=async(n,s={})=>(await this.datasource.metadataRequest(n,s))?.data,this.start=async()=>(this.startTask||(this.startTask=this.fetchTags().then(()=>[])),this.startTask),this.getTags=()=>this.tags,this.provideCompletionItems=async({text:n,value:s})=>{const i={suggestions:[]};if(!s)return i;const l=s.endText.getText();return l[l.indexOf(n)-1]==="="||n==="="?this.getTagValueCompletionItems(s):this.getTagsCompletionItems()},this.getTagsCompletionItems=()=>{const{tags:n}=this,s=[];return n?.length&&s.push({label:"Tag",items:n.map(i=>({label:i}))}),{suggestions:s}},this.datasource=e,Object.assign(this,a)}async fetchTags(){const e=await this.request("/api/search/tags",[]);this.tags=e.tagNames}async getTagValueCompletionItems(e){const a=e.endText.getText().split(" ");let n=a[a.length-1]??"";n=n.split("=")[0];const s=await this.request(`/api/v2/search/tag/${n}/values`,[]),i=[];return s&&s.tagValues&&i.push({label:"Tag Values",items:s.tagValues.map(l=>({label:l,insertText:`"${l}"`}))}),{suggestions:i}}async getOptionsV1(e){const a=await this.request(`/api/search/tag/${e}/values`);let n=[];return a&&a.tagValues&&(n=a.tagValues.map(s=>({value:s,label:s}))),n}async getOptionsV2(e){const a=await this.request(`/api/v2/search/tag/${e}/values`);let n=[];return a&&a.tagValues&&(n=a.tagValues.map(s=>({type:s.type,value:s.value,label:s.value}))),n}}var le=o(86146);const re=20;class Mt extends yt.CK{constructor(e,a=(0,me.J)()){super(e),this.instanceSettings=e,this.templateSrv=a,this.uploadedJson=null,this.getLokiSearchDS=()=>{const n=this.tracesToLogs?.lokiSearch!==!1&&this.lokiSearch===void 0?this.tracesToLogs?.datasourceUid:void 0;return this.lokiSearch?.datasourceUid??n},this.tracesToLogs=e.jsonData.tracesToLogs,this.serviceMap=e.jsonData.serviceMap,this.search=e.jsonData.search,this.nodeGraph=e.jsonData.nodeGraph,this.lokiSearch=e.jsonData.lokiSearch,this.traceQuery=e.jsonData.traceQuery,this.languageProvider=new Ne(this),this.search?.filters||(this.search={...this.search,filters:[{id:"service-name",tag:"service.name",operator:"=",scope:G.Resource},{id:"span-name",tag:"name",operator:"=",scope:G.Span}]})}query(e){const a=[],n=e.targets.filter(l=>!l.hide),s=(0,J.groupBy)(n,l=>l.queryType||"traceql");if(s.clear)return(0,K.of)({data:[],state:ae.Gu.Done});const i=this.getLokiSearchDS();if(i&&s.search?.length>0){(0,N.ff)("grafana_traces_loki_search_queried",{datasourceType:"tempo",app:e.app??"",grafana_version:S.v.buildInfo.version,hasLinkedQueryExpr:!!(s.search[0].linkedQuery?.expr&&s.search[0].linkedQuery?.expr!=="")});const l=(0,Se.ak)();a.push((0,_e.D)(l.get(i)).pipe((0,Ue.z)(c=>{const d={...e,targets:s.search.map(p=>p.linkedQuery)},f=c.instanceSettings.jsonData.derivedFields?.filter(p=>p.datasourceUid===this.uid&&p.matcherRegex).map(p=>p.matcherRegex)||[];return!f||f.length===0?(0,gt._)(()=>new Error("No Loki datasource configured for search. Set up Derived Fields for traces in a Loki datasource settings and link it to this Tempo datasource.")):c.query(d).pipe((0,X.U)(p=>p.error?p:(0,le.RY)(p,this.uid,this.name,f)))})))}if(s.nativeSearch?.length)try{(0,N.ff)("grafana_traces_search_queried",{datasourceType:"tempo",app:e.app??"",grafana_version:S.v.buildInfo.version,hasServiceName:!!s.nativeSearch[0].serviceName,hasSpanName:!!s.nativeSearch[0].spanName,resultLimit:s.nativeSearch[0].limit??"",hasSearch:!!s.nativeSearch[0].search,minDuration:s.nativeSearch[0].minDuration??"",maxDuration:s.nativeSearch[0].maxDuration??""});const l={startTime:e.range.from.unix(),endTime:e.range.to.unix()},c=this.applyVariables(s.nativeSearch[0],e.scopedVars),d=this.buildSearchQuery(c,l);a.push(this._request("/api/search",d).pipe((0,X.U)(u=>({data:[(0,le.n4)(u.data.traces,this.instanceSettings)]})),(0,De.K)(u=>(0,K.of)({error:{message:u.data.message},data:[]}))))}catch(l){return(0,K.of)({error:{message:l instanceof Error?l.message:"Unknown error occurred"},data:[]})}if(s.traceql?.length)try{const c=this.applyVariables(s.traceql[0],e.scopedVars)?.query||"",d=/^[0-9A-Fa-f]*$/;c.trim().match(d)?((0,N.ff)("grafana_traces_traceID_queried",{datasourceType:"tempo",app:e.app??"",grafana_version:S.v.buildInfo.version,hasQuery:c!==""}),a.push(this.handleTraceIdQuery(e,s.traceql))):((0,N.ff)("grafana_traces_traceql_queried",{datasourceType:"tempo",app:e.app??"",grafana_version:S.v.buildInfo.version,query:c??""}),a.push(this._request("/api/search",{q:c,limit:e.targets[0].limit??re,start:e.range.from.unix(),end:e.range.to.unix()}).pipe((0,X.U)(u=>({data:(0,le.xA)(u.data.traces,this.instanceSettings)})),(0,De.K)(u=>(0,K.of)({error:{message:u.data.message},data:[]})))))}catch(l){return(0,K.of)({error:{message:l instanceof Error?l.message:"Unknown error occurred"},data:[]})}if(s.traceqlSearch?.length)try{const l=je(s.traceqlSearch[0].filters);(0,N.ff)("grafana_traces_traceql_search_queried",{datasourceType:"tempo",app:e.app??"",grafana_version:S.v.buildInfo.version,query:l??""}),a.push(this._request("/api/search",{q:l,limit:e.targets[0].limit??re,start:e.range.from.unix(),end:e.range.to.unix()}).pipe((0,X.U)(c=>({data:(0,le.xA)(c.data.traces,this.instanceSettings)})),(0,De.K)(c=>(0,K.of)({error:{message:c.data.message},data:[]}))))}catch(l){return(0,K.of)({error:{message:l instanceof Error?l.message:"Unknown error occurred"},data:[]})}if(s.upload?.length)if(this.uploadedJson){(0,N.ff)("grafana_traces_json_file_uploaded",{datasourceType:"tempo",app:e.app??"",grafana_version:S.v.buildInfo.version});const l=JSON.parse(this.uploadedJson),c=l.batches,d=Array.isArray(l)&&l.some(u=>u?.meta?.preferredVisualisationType==="nodeGraph");c?a.push((0,K.of)((0,le.IM)(l.batches,this.nodeGraph?.enabled))):d?a.push((0,K.of)({data:l,state:ae.Gu.Done})):a.push((0,K.of)({error:{message:"Unable to parse uploaded data."},data:[]}))}else a.push((0,K.of)({data:[],state:ae.Gu.Done}));if(this.serviceMap?.datasourceUid&&s.serviceMap?.length>0){(0,N.ff)("grafana_traces_service_graph_queried",{datasourceType:"tempo",app:e.app??"",grafana_version:S.v.buildInfo.version,hasServiceMapQuery:!!s.serviceMap[0].serviceMapQuery});const l=this.serviceMap.datasourceUid,c=this.uid;a.push(wt(e,l,c).pipe((0,Fe.b)(d=>Pt(e,d,l).pipe((0,Fe.b)(u=>Lt(e,u,l,c))))))}return(0,ht.T)(...a)}applyTemplateVariables(e,a){return this.applyVariables(e,a)}interpolateVariablesInQueries(e,a){return!e||e.length===0?[]:e.map(n=>({...n,datasource:this.getRef(),...this.applyVariables(n,a)}))}applyVariables(e,a){const n={...e};return e.linkedQuery&&(n.linkedQuery={...e.linkedQuery,expr:this.templateSrv.replace(e.linkedQuery?.expr??"",a)}),{...n,query:this.templateSrv.replace(e.query??"",a,ge.b8.Pipe),serviceName:this.templateSrv.replace(e.serviceName??"",a),spanName:this.templateSrv.replace(e.spanName??"",a),search:this.templateSrv.replace(e.search??"",a),minDuration:this.templateSrv.replace(e.minDuration??"",a),maxDuration:this.templateSrv.replace(e.maxDuration??"",a)}}handleTraceIdQuery(e,a){const n=a.filter(i=>i.query).map(i=>({...i,query:i.query.trim()}));if(!n.length)return pt.E;const s=this.traceIdQueryRequest(e,n);return super.query(s).pipe((0,X.U)(i=>i.error?i:(0,le.Jk)(i,this.nodeGraph?.enabled)))}traceIdQueryRequest(e,a){const n={...e,targets:a};return this.traceQuery?.timeShiftEnabled?n.range=e.range&&{...e.range,from:e.range.from.subtract(Ve.intervalToMs(this.traceQuery?.spanStartTimeShift||"30m"),"milliseconds"),to:e.range.to.add(Ve.intervalToMs(this.traceQuery?.spanEndTimeShift||"30m"),"milliseconds")}:n.range={from:(0,Ee.CQ)(0),to:(0,Ee.CQ)(0),raw:{from:(0,Ee.CQ)(0),to:(0,Ee.CQ)(0)}},n}async metadataRequest(e,a={}){return await(0,We.n)(this._request(e,a,{method:"GET",hideFromInspector:!0}))}_request(e,a,n){const s=a?(0,Et.tW)(a):"",i=`${this.instanceSettings.url}${e}${s.length?`?${s}`:""}`,l={...n,url:i};return(0,oe.i)().fetch(l)}async testDatasource(){const e={headers:{},method:"GET",url:`${this.instanceSettings.url}/api/echo`};if((await(0,We.n)((0,oe.i)().fetch(e)))?.ok)return{status:"success",message:"Data source is working"}}getQueryDisplayText(e){if(e.queryType==="nativeSearch"){let a=[];for(const n of["serviceName","spanName","search","minDuration","maxDuration","limit"])e.hasOwnProperty(n)&&e[n]&&a.push(`${(0,J.startCase)(n)}: ${e[n]}`);return a.join(", ")}return e.query}buildSearchQuery(e,a){let n=e.search??"",s=(0,J.pick)(e,["minDuration","maxDuration","limit"]);if(s=(0,J.pickBy)(s,J.identity),e.serviceName&&(n+=` service.name="${e.serviceName}"`),e.spanName&&(n+=` name="${e.spanName}"`),s.limit||(s.limit=re),s.minDuration){if(s.minDuration=this.templateSrv.replace(s.minDuration??""),!(0,Te.IA)(s.minDuration))throw new Error("Please enter a valid min duration.");s.minDuration=s.minDuration.replace(/\s/g,"")}if(s.maxDuration){if(s.maxDuration=this.templateSrv.replace(s.maxDuration??""),!(0,Te.IA)(s.maxDuration))throw new Error("Please enter a valid max duration.");s.maxDuration=s.maxDuration.replace(/\s/g,"")}if(!Number.isInteger(s.limit)||s.limit<=0)throw new Error("Please enter a valid limit.");let i={tags:n,...s};return a&&(i.start=a.startTime,i.end=a.endTime),i}}function Me(t,e){return(0,_e.D)((0,Se.ak)().get(e)).pipe((0,Ue.z)(a=>a.query(t)))}function wt(t,e,a){const n=we(t);return Me(n,e).pipe((0,xe.q)(),(0,X.U)(s=>{const i=s.find(d=>!!d.error);if(i)throw new Error(i.error.message);const{nodes:l,edges:c}=(0,F.BC)(s,t.range);if(l.fields.length>0&&c.fields.length>0){const d=l.fields[0].values.length,u=c.fields[0].values.length;(0,N.ff)("grafana_traces_service_graph_size",{datasourceType:"tempo",grafana_version:S.v.buildInfo.version,nodeLength:d,edgeLength:u})}return l.refId=t.targets[0].refId,c.refId=t.targets[0].refId,l.fields[0].config=Ge(e,a,"__data.fields.id","__data.fields[0]"),c.fields[0].config=Ge(e,a,"__data.fields.target","__data.fields.target","__data.fields.source"),{data:[l,c],state:ae.Gu.Done}}))}function Pt(t,e,a){const n=we(t);return n.targets=Ye([se(F.rB,F.T1,t)]),Me(n,a).pipe((0,xe.q)(),(0,X.U)(s=>{const i=s.find(l=>!!l.error);if(i)throw new Error(i.error.message);return{data:[s[0]?.data??[],e.data[0],e.data[1]],state:ae.Gu.Done}}))}function Lt(t,e,a,n){let s=[],i="",l=[],c=[];t.app===ft.zj.Explore?e.data[0][0]?.fields[1]?.values&&(c=e.data[0][0]?.fields[1]?.values):e.data[0]&&e.data[0].map(f=>{f.fields[1]?.labels&&f.fields[1]?.labels.span_name&&c.push(f.fields[1]?.labels.span_name)});const d=Rt(c);d.length>0&&(i=se(F.$C,'span_name=~"'+d.join("|")+'"',t),s.push(i),d.map(f=>{const p=se(F.vO,'span_name=~"'+f+'"',t);l.push(p),s.push(p)}));const u=we(t);return u.targets=Ye(s),Me(u,a).pipe((0,xe.q)(),(0,X.U)(f=>{const p=f.find(A=>!!A.error);if(p)throw new Error(p.error.message);const M=At(t,e,f[0],i,l,a,n);return M.fields.length===0?{data:[e.data[1],e.data[2]],state:ae.Gu.Done}:{data:[M,e.data[1],e.data[2]],state:ae.Gu.Done}}))}function ce(t,e,a,n){return{url:"",title:t,internal:{query:{expr:e,range:!n,exemplar:!n,instant:n},datasourceUid:a,datasourceName:(0,Se.ak)().getDataSourceSettingsByUid(a)?.name??""}}}function Rt(t){return t.map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\\\$&"))}function Ge(t,e,a,n,s){return s=s?`client="\${${s}}",`:"",{links:[ce("Request rate",`sum by (client, server)(rate(${F.Yt}{${s}server="\${${a}}"}[$__rate_interval]))`,t,!1),ce("Request histogram",`histogram_quantile(0.9, sum(rate(${F.NZ}{${s}server="\${${a}}"}[$__rate_interval])) by (le, client, server))`,t,!1),ce("Failed request rate",`sum by (client, server)(rate(${F.yf}{${s}server="\${${a}}"}[$__rate_interval]))`,t,!1),Ze("View traces",`\${${n}}`,"",e)]}}function Ze(t,e,a,n){let s={queryType:"nativeSearch"};return e!==""&&(s.serviceName=e),a!==""&&(s.spanName=a),{url:"",title:t,internal:{query:s,datasourceUid:n,datasourceName:(0,Se.ak)().getDataSourceSettingsByUid(n)?.name??""}}}function we(t){return{...t,targets:F.t3.map(e=>({format:"table",refId:e,expr:`sum by (client, server) (rate(${e}${t.targets[0].serviceMapQuery||""}[$__range]))`,instant:!0}))}}function At(t,e,a,n,s,i,l){let c={fields:[]};const d=e.data[0]?.filter(p=>p.refId===se(F.rB,F.T1,t)),u=a.data.filter(p=>p.refId===n),f=a.data.filter(p=>s.includes(p.refId));if(d.length>0&&d[0].fields?.length>2&&(c.fields.push({...d[0].fields[1],name:"Name",config:{filterable:!1}}),c.fields.push({...d[0].fields[2],name:"Rate",config:{links:[ce("Rate",Pe(se(F.rB,'span_name="${__data.fields[0]}"',t)),i,!1)],decimals:2}}),c.fields.push({...d[0].fields[2],name:"  ",labels:null,config:{color:{mode:"continuous-BlPu"},custom:{cellOptions:{mode:ge.QH.Lcd,type:ge.h2.Gauge}},decimals:3}})),u.length>0&&u[0].fields?.length>2){const p=u[0].fields[1]?.values??[],M=u[0].fields[2]?.values??[];let A={};p.map((Z,H)=>{A[Z]={value:M[H]}});const Q=He({...d},A);c.fields.push({...u[0].fields[2],name:"Error Rate",values:Q,config:{links:[ce("Error Rate",Pe(se(F.$C,'span_name="${__data.fields[0]}"',t)),i,!1)],decimals:2}}),c.fields.push({...u[0].fields[2],name:"   ",values:Q,labels:null,config:{color:{mode:"continuous-RdYlGr"},custom:{cellOptions:{mode:ge.QH.Lcd,type:ge.h2.Gauge}},decimals:3}})}if(f.length>0&&f[0].fields?.length>1){let p={};f.map(M=>{const A=M.refId?.includes('span_name=~"')?'span_name=~"':'span_name="',Q=M.refId?.split(A)[1].split('"}')[0];p[Q]={value:M.fields[1].values[0]}}),c.fields.push({...f[0].fields[1],name:"Duration (p90)",values:He({...d},p),config:{links:[ce("Duration",Pe(se(F.vO,'span_name="${__data.fields[0]}"',t)),i,!1)],unit:"s"}})}return c.fields.length>0&&c.fields[0].values&&c.fields.push({name:"Links",type:vt.fS.string,values:c.fields[0].values.map(()=>"Tempo"),config:{links:[Ze("Tempo","","${__data.fields[0]}",l)]}}),c}function se(t,e,a){let n=a.targets[0]?.serviceMapQuery??"";const s=n.match(/^{(.*)}$/);s?.length&&(n=s[1]),n=n.replace("client","service").replace("server","service");const i=n.includes("span_name")?t.params.concat(n):t.params.concat(n).concat(e).filter(l=>l);return t.expr.replace("{}","{"+i.join(",")+"}")}function Pe(t){return t=t.replace("topk(5, ","").replace(" by (span_name))",""),t.replace("__range","__rate_interval")}function He(t,e){const a=t[0]?.fields[1]?.values??[];let n=[];for(let s=0;s<a.length;s++)Object.keys(e).includes(a[s])?n.push(e[a[s]].value):n.push("0");return n}function Ye(t){return t.map(e=>({refId:e,expr:e,instant:!0}))}const Le=r.memo(({onChange:t,query:e})=>{e.hasOwnProperty("limit")||(e.limit=re);const a=n=>{t({...e,limit:parseInt(n.currentTarget.value,10)})};return r.createElement(r.Fragment,null,r.createElement(O.EditorRow,null,r.createElement(mt.d,{title:"Options",collapsedInfo:[`Limit: ${e.limit||re}`]},r.createElement(O.EditorField,{label:"Limit",tooltip:"Maximum number of traces to return."},r.createElement(dt.H,{className:"width-4",placeholder:"auto",type:"number",min:1,defaultValue:e.limit||re,onCommitChange:a,value:e.limit})))))});Le.displayName="TempoQueryBuilderOptions";var ne=o(8581),ue=o(46967);const Qt=/^\d+(?:\.\d)?\d*(?:us|µs|ns|ms|s|m|h)$/,Ot=()=>({noBoxShadow:v.css`
    box-shadow: none;
    *:focus {
      box-shadow: none;
    }
  `}),qe=({filter:t,operators:e,updateFilter:a})=>{const n=(0,x.wW)(Ot);let s=!1;return typeof t.value=="string"&&(s=t.value?!Qt.test(t.value.concat("")):!1),r.createElement(z.Lh,{spacing:"none"},r.createElement(ne.Ph,{className:n.noBoxShadow,inputId:`${t.id}-operator`,options:e.map(Ke),value:t.operator,onChange:i=>{a({...t,operator:i?.value})},isClearable:!1,"aria-label":`select ${t.id} operator`,allowCustomValue:!0,width:8}),r.createElement(ue.I,{className:n.noBoxShadow,value:t.value,onChange:i=>{a({...t,value:i.currentTarget.value})},placeholder:"e.g. 100ms, 1.2s","aria-label":`select ${t.id} value`,invalid:s,width:18}))},Re=({label:t,tooltip:e,children:a})=>r.createElement(m.Z,null,r.createElement(T._,{label:t,labelWidth:28,grow:!0,tooltip:e},a)),$t=()=>({dropdown:v.css`
    box-shadow: none;
  `}),Je=({filter:t,datasource:e,updateFilter:a,deleteFilter:n,isTagsLoading:s,tags:i,setError:l,hideScope:c,hideTag:d,hideValue:u,allowDelete:f})=>{const p=(0,x.wW)($t),M=(0,r.useMemo)(()=>new Ne(e),[e]),A=(0,r.useMemo)(()=>Ie(t),[t]),[Q,Z]=(0,r.useState)(t.operator),[H,Y]=(0,r.useState)(t.value),D=async()=>{try{return await M.getOptionsV2(A)}catch(w){(0,oe.kW)(w)&&w?.status===404?l(w):w instanceof Error&&(0,q.WI)((0,ie.$l)((0,U.t_)("Error",w)))}return[]},{loading:L,value:B}=(0,C.Z)(D,[A,M,l]);(0,r.useEffect)(()=>{Array.isArray(t.value)&&t.value.length>1&&t.operator!=="=~"&&(Z(t.operator),a({...t,operator:"=~"})),Array.isArray(t.value)&&t.value.length<=1&&(H?.length||0)>1&&a({...t,operator:Q,value:t.value[0]})},[H,Q,a,t]),(0,r.useEffect)(()=>{Y(t.value)},[t.value]);const b=Object.values(G).map(w=>({label:w,value:w})),_=B?.filter(w=>w.type===B[0]?.type),de=B?.length===_?.length?B?.[0]?.type:void 0;let V=ke;switch(de){case"string":V=St;break;case"int":case"float":V=bt}return r.createElement(z.Lh,{spacing:"none",width:"auto"},!c&&r.createElement(ne.Ph,{className:p.dropdown,inputId:`${t.id}-scope`,options:b,value:t.scope,onChange:w=>{a({...t,scope:w?.value})},placeholder:"Select scope","aria-label":`select ${t.id} scope`}),!d&&r.createElement(ne.Ph,{className:p.dropdown,inputId:`${t.id}-tag`,isLoading:s,options:(t.tag!==void 0?(0,J.uniq)([t.tag,...i]):i).map(w=>({label:w,value:w})),value:t.tag,onChange:w=>{a({...t,tag:w?.value})},placeholder:"Select tag",isClearable:!0,"aria-label":`select ${t.id} tag`,allowCustomValue:!0}),r.createElement(ne.Ph,{className:p.dropdown,inputId:`${t.id}-operator`,options:V.map(Ke),value:t.operator,onChange:w=>{a({...t,operator:w?.value})},isClearable:!1,"aria-label":`select ${t.id} operator`,allowCustomValue:!0,width:8}),!u&&r.createElement(ne.Ph,{className:p.dropdown,inputId:`${t.id}-value`,isLoading:L,options:B,value:t.value,onChange:w=>{Array.isArray(w)?a({...t,value:w.map(be=>be.value),valueType:w[0]?.type}):a({...t,value:w?.value,valueType:w?.type})},placeholder:"Select value",isClearable:!1,"aria-label":`select ${t.id} value`,allowCustomValue:!0,isMulti:!0,allowCreateWhileLoading:!0}),f&&r.createElement(O.AccessoryButton,{variant:"secondary",icon:"times",onClick:()=>n?.(t),tooltip:"Remove tag","aria-label":`remove tag with ID ${t.id}`}))};var _t=o(44288);const Wt=()=>({vertical:v.css`
    display: flex;
    flex-direction: column;
    gap: 0.25rem;
  `,horizontal:v.css`
    display: flex;
    flex-direction: row;
    gap: 1rem;
  `}),Xe=({updateFilter:t,deleteFilter:e,filters:a,datasource:n,setError:s,tags:i,isTagsLoading:l,hideValues:c})=>{const d=(0,x.wW)(Wt),u=()=>(0,_t.Z)().slice(0,8),f=(0,r.useCallback)(()=>t({id:u(),operator:"=",scope:G.Span}),[t]);return(0,r.useEffect)(()=>{a?.length||f()},[a,f]),r.createElement("div",{className:d.vertical},a?.map((p,M)=>r.createElement("div",{className:d.horizontal,key:p.id},r.createElement(Je,{filter:p,datasource:n,setError:s,updateFilter:t,tags:i,isTagsLoading:l,deleteFilter:e,allowDelete:!0,hideValue:c}),M===a.length-1&&r.createElement(O.AccessoryButton,{variant:"secondary",icon:"plus",onClick:f,title:"Add tag"}))))},Ut=({datasource:t,query:e,onChange:a})=>{const n=(0,x.wW)(Ft),[s,i]=(0,r.useState)(null),[l,c]=(0,r.useState)([]),[d,u]=(0,r.useState)(!0),[f,p]=(0,r.useState)(""),M=(0,r.useCallback)(D=>{const L={...e};L.filters||=[];const B=L.filters.findIndex(b=>b.id===D.id);B>=0?L.filters=ze(L.filters,B,D):L.filters.push(D),a(L)},[a,e]),A=D=>{a({...e,filters:e.filters.filter(L=>L.id!==D.id)})};(0,r.useEffect)(()=>{p(je(e.filters||[]))},[e]);const Q=(0,r.useCallback)(D=>e.filters?.find(L=>L.id===D),[e.filters]);(0,r.useEffect)(()=>{(async()=>{try{await t.languageProvider.start();const L=t.languageProvider.getTags();L&&(L.find(B=>B==="status")||L.push("status"),c(L),u(!1))}catch(L){L instanceof Error&&(0,q.WI)((0,ie.$l)((0,U.t_)("Error",L)))}})()},[t]),(0,r.useEffect)(()=>{t.search?.filters?.filter(D=>D.value).forEach(D=>{Q(D.id)||M(D)})},[t.search?.filters,Q,M]);const Z=t.search?.filters?.map(D=>D.tag)||[];Z.push("duration");const H=[...he,...l].filter(D=>!Z.includes(D)),Y=(e.filters||[]).filter(D=>D.tag!=="duration"&&(t.search?.filters?.findIndex(L=>L.id===D.id)||0)===-1);return r.createElement(r.Fragment,null,r.createElement("div",{className:n.container},r.createElement("div",null,t.search?.filters?.map(D=>r.createElement(Re,{key:D.id,label:Nt(D),tooltip:`Filter your search by ${Ie(D)}. To modify the default filters shown for search visit the Tempo datasource configuration page.`},r.createElement(Je,{filter:Q(D.id)||D,datasource:t,setError:i,updateFilter:M,tags:[],hideScope:!0,hideTag:!0}))),r.createElement(Re,{label:"Duration",tooltip:"The span duration, i.e.	end - start time of the span. Accepted units are ns, ms, s, m, h"},r.createElement(z.Lh,{spacing:"sm"},r.createElement(qe,{filter:Q("min-duration")||{id:"min-duration",tag:"duration",operator:">",valueType:"duration"},operators:[">",">="],updateFilter:M}),r.createElement(qe,{filter:Q("max-duration")||{id:"max-duration",tag:"duration",operator:"<",valueType:"duration"},operators:["<","<="],updateFilter:M}))),r.createElement(Re,{label:"Tags"},r.createElement(Xe,{filters:Y,datasource:t,setError:i,updateFilter:M,deleteFilter:A,tags:H,isTagsLoading:d}))),r.createElement(O.EditorRow,null,r.createElement(ut.U,{query:f,lang:{grammar:Ct,name:"traceql"}})),r.createElement(Le,{onChange:a,query:e})),s?r.createElement(W.b,{title:"Unable to connect to Tempo search",severity:"info",className:n.alert},"Please ensure that Tempo is configured with search enabled. If you would like to hide this tab, you can configure it in the ",r.createElement("a",{href:`/datasources/edit/${t.uid}`},"datasource settings"),"."):null)},Ft=t=>({alert:v.css`
    max-width: 75ch;
    margin-top: ${t.spacing(2)};
  `,container:v.css`
    display: flex;
    gap: 4px;
    flex-wrap: wrap;
    flex-direction: column;
  `}),Vt={};var kt=(t=>(t[t.UNSPECIFIED=0]="UNSPECIFIED",t[t.INTERNAL=1]="INTERNAL",t[t.SERVER=2]="SERVER",t[t.CLIENT=3]="CLIENT",t[t.PRODUCER=4]="PRODUCER",t[t.CONSUMER=5]="CONSUMER",t))(kt||{}),et=o(9405);const Ae=class{constructor(t){this.triggerCharacters=["{",".","[","(","=","~"," ",'"'],this.tags={},this.cachedValues={},this.languageProvider=t.languageProvider,this.registerInteractionCommandId=null}provideCompletionItems(t,e){if(!(this.monaco&&this.editor))throw new Error("provideCompletionItems called before CompletionProvider was initialized");if(this.editor.getModel()?.id!==t.id)return{suggestions:[]};const{range:a,offset:n}=Bt(this.monaco,t,e),s=this.getSituation(t.getValue(),n);return this.getCompletions(s).then(l=>{const c=l.length.toString().length;return{suggestions:l.map((u,f)=>{const p={kind:jt(u.type,this.monaco),label:u.label,insertText:u.insertText,sortText:f.toString().padStart(c,"0"),range:a,command:{id:this.registerInteractionCommandId||"noOp",title:"Report Interaction",arguments:[u.label,u.type]}};return zt(p,u.type,t,n),p})}})}setTags(t){t.forEach(e=>this.tags[e]=new Set)}setRegisterInteractionCommandId(t){this.registerInteractionCommandId=t}async getTagValues(t){let e;return this.cachedValues.hasOwnProperty(t)?e=this.cachedValues[t]:(e=await this.languageProvider.getOptionsV2(t),this.cachedValues[t]=e),e}async getCompletions(t){if(!Object.keys(this.tags).length)return[];switch(t.type){case"UNKNOWN":return[];case"EMPTY":return this.getScopesCompletions("{ ").concat(this.getIntrinsicsCompletions("{ ")).concat(this.getTagsCompletions("{ ."));case"SPANSET_EMPTY":return this.getScopesCompletions().concat(this.getIntrinsicsCompletions()).concat(this.getTagsCompletions("."));case"SPANSET_ONLY_DOT":return this.getTagsCompletions();case"SPANSET_IN_NAME":return this.getScopesCompletions().concat(this.getIntrinsicsCompletions()).concat(this.getTagsCompletions());case"SPANSET_IN_NAME_SCOPE":return this.getTagsCompletions();case"SPANSET_AFTER_NAME":return Ae.operators.map(s=>({label:s,insertText:s,type:"OPERATOR"}));case"SPANSET_IN_VALUE":let e;try{e=await this.getTagValues(t.tagName)}catch(s){(0,oe.kW)(s)?(0,q.WI)((0,ie.$l)((0,U.t_)(s.data.error,new Error(s.data.message)))):s instanceof Error&&(0,q.WI)((0,ie.$l)((0,U.t_)("Error",s)))}const a=[],n=s=>t.betweenQuotes?s.label:s.type==="string"?`"${s.label}"`:s.label;return e?.forEach(s=>{s?.label&&a.push({label:s.label,insertText:n(s),type:"TAG_VALUE"})}),a;case"SPANSET_AFTER_VALUE":return Ae.logicalOps.concat("}").map(s=>({label:s,insertText:s,type:"OPERATOR"}));default:throw new Error(`Unexpected situation ${t}`)}}getTagsCompletions(t){return Object.keys(this.tags).sort((e,a)=>e.localeCompare(a,void 0,{sensitivity:"accent"})).map(e=>({label:e,insertText:(t||"")+e,type:"TAG_NAME"}))}getIntrinsicsCompletions(t){return he.map(e=>({label:e,insertText:(t||"")+e,type:"KEYWORD"}))}getScopesCompletions(t){return Ce.map(e=>({label:e,insertText:(t||"")+e,type:"SCOPE"}))}getSituationInSpanSet(t){const e=/(?<name>[\w./-]+)?/,a=/(?<op>[!=+\-<>]+)/,n=/(?<value>(?<open_quote>")([^"\n&|]+)?(?<close_quote>")?|([^"\n\s&|]+))?/,s=new RegExp("([\\s{])("+e.source+"(?<space1>\\s*)("+a.source+"(?<space2>\\s*)"+n.source+")?)(?<space3>\\s*)$"),i=t.match(s);if(i){const l=i.groups?.name,c=i.groups?.op;if(!l)return{type:"SPANSET_EMPTY"};if(l===".")return{type:"SPANSET_ONLY_DOT"};const d=l.match(/^(?<pre_dot>\.)?(?<word>\w[\w./-]*\w)(?<post_dot>\.)?$/);return c?i.groups?.space3&&i.groups.open_quote===i.groups.close_quote?{type:"SPANSET_AFTER_VALUE"}:{type:"SPANSET_IN_VALUE",tagName:l,betweenQuotes:!!i.groups?.open_quote}:Ce.filter(u=>u===d?.groups?.word)&&d?.groups?.post_dot?{type:"SPANSET_IN_NAME_SCOPE"}:{type:i.groups?.space1?"SPANSET_AFTER_NAME":"SPANSET_IN_NAME"}}return{type:"EMPTY"}}getSituation(t,e){if(t===""||e===0)return{type:"EMPTY"};const a=t.substring(0,e);return a.lastIndexOf("{")>a.lastIndexOf("}")?this.getSituationInSpanSet(a):{type:"UNKNOWN"}}};let Qe=Ae;Qe.operators=["=","-","+","<",">",">=","<=","=~"],Qe.logicalOps=["&&","||"];function jt(t,e){switch(t){case"TAG_NAME":return e.languages.CompletionItemKind.Enum;case"KEYWORD":return e.languages.CompletionItemKind.Keyword;case"OPERATOR":return e.languages.CompletionItemKind.Operator;case"TAG_VALUE":return e.languages.CompletionItemKind.EnumMember;case"SCOPE":return e.languages.CompletionItemKind.Class;default:throw new Error(`Unexpected CompletionType: ${t}`)}}function Bt(t,e,a){const n=e.getWordAtPosition(a),s=n!=null?t.Range.lift({startLineNumber:a.lineNumber,endLineNumber:a.lineNumber,startColumn:n.startColumn,endColumn:n.endColumn}):t.Range.fromPositions(a),i={column:a.column,lineNumber:a.lineNumber};return{offset:e.getOffsetAt(i),range:s}}function zt(t,e,a,n){if(e==="TAG_NAME"){const s=a.getValue().substring(0,n).match(/(span\.|resource\.|\.)?([\w./-]*)$/);if(s){const i=s[1],l=s[2];l&&(!i&&t.insertText[0]!=="."&&(t.insertText="."+t.insertText),t.range={...t.range,startColumn:n-l.length+1})}}}function Kt(t){const{onChange:e,onRunQuery:a,placeholder:n}=t,s=qt(t.datasource),i=(0,x.l4)(),l=Xt(i,n);return r.createElement(et.p,{value:t.value,language:pe,onBlur:e,onChange:e,containerStyles:l.queryField,readOnly:t.readOnly,monacoOptions:{folding:!1,fontSize:14,lineNumbers:"off",overviewRulerLanes:0,renderLineHighlight:"none",scrollbar:{vertical:"hidden",verticalScrollbarSize:8,horizontal:"hidden",horizontalScrollbarSize:0},scrollBeyondLastLine:!1,wordWrap:"on"},onBeforeEditorMount:Jt,onEditorDidMount:(c,d)=>{t.readOnly||(s(c,d,Ht(c)),Zt(c,d,a),Gt(c,d,l)),Yt(c)}})}function Gt(t,e,a){const n=[{range:new e.Range(1,1,1,1),options:{className:a.placeholder,isWholeLine:!0}}];let s=[];const i=()=>{const l=t.getModel();if(!l)return;const c=l.getValueLength()===0?n:[];s=l.deltaDecorations(s,c)};i(),t.onDidChangeModelContent(i)}function Zt(t,e,a){t.addAction({id:"run-query",label:"Run Query",keybindings:[e.KeyMod.Shift|e.KeyCode.Enter],contextMenuGroupId:"navigation",contextMenuOrder:1.5,run:function(){a()}})}function Ht(t){return t.addCommand(0,function(e,a,n){const s={datasourceType:"tempo",type:n};n!=="TAG_VALUE"&&(s.label=a),(0,N.ff)("grafana_traces_traceql_completion",s)})}function Yt(t){const e=t.getDomNode(),a=()=>{if(e){const n=Math.min(1e3,t.getContentHeight()),s=parseInt(e.style.width,10);e.style.width=`${s}px`,e.style.height=`${n}px`,t.layout({width:s,height:n})}};t.onDidContentSizeChange(a),a()}function qt(t){const e=(0,r.useRef)(new Qe({languageProvider:t.languageProvider}));(0,r.useEffect)(()=>{(async()=>{try{await t.languageProvider.start();const s=t.languageProvider.getTags();s&&(s.find(i=>i==="status")||s.push("status"),e.current.setTags(s))}catch(s){s instanceof Error&&(0,q.WI)((0,ie.$l)((0,U.t_)("Error",s)))}})()},[t]);const a=(0,r.useRef)(null);return(0,r.useEffect)(()=>()=>{a.current?.()},[]),(n,s,i)=>{e.current.editor=n,e.current.monaco=s,e.current.setRegisterInteractionCommandId(i);const{dispose:l}=s.languages.registerCompletionItemProvider(pe,e.current);a.current=l}}let tt=!1;const pe="traceql";function Jt(t){if(!tt){tt=!0;const{aliases:e,extensions:a,mimetypes:n,def:s}=xt;t.languages.register({id:pe,aliases:e,extensions:a,mimetypes:n}),t.languages.setMonarchTokensProvider(pe,s.language),t.languages.setLanguageConfiguration(pe,s.languageConfiguration)}}const Xt=(t,e)=>({queryField:v.css`
      border-radius: ${t.shape.borderRadius()};
      border: 1px solid ${t.components.input.borderColor};
      flex: 1;
    `,placeholder:v.css`
      ::after {
        content: '${e}';
        font-family: ${t.typography.fontFamilyMonospace};
        opacity: 0.3;
      }
    `});function ea(t){const e=(0,x.wW)(ta),a=(0,J.defaults)(t.query,Vt),n=s=>{t.onChange({...a,query:s})};return r.createElement(r.Fragment,null,r.createElement(g.W,null,"Build complex queries using TraceQL to select a list of traces."," ",r.createElement("a",{rel:"noreferrer",target:"_blank",href:"https://grafana.com/docs/tempo/latest/traceql/"},"Documentation")),r.createElement(Kt,{placeholder:"Enter a TraceQL query or trace ID (run with Shift+Enter)",value:a.query,onChange:n,datasource:t.datasource,onRunQuery:t.onRunQuery}),r.createElement("div",{className:e.optionsContainer},r.createElement(Le,{query:a,onChange:t.onChange})))}const ta=()=>({optionsContainer:v.css`
    margin-top: 10px;
  `});var at=o(13572),aa=o(27303),rt=o(659);class ra{constructor(e){this.triggerCharacters=["="," "],this.tags={},this.cachedValues={},this.languageProvider=e.languageProvider}provideCompletionItems(e,a){if(!(this.monaco&&this.editor))throw new Error("provideCompletionItems called before CompletionProvider was initialized");if(this.editor.getModel()?.id!==e.id)return{suggestions:[]};const{range:n,offset:s}=na(this.monaco,e,a),i=this.getSituation(e.getValue(),s);return this.getCompletions(i).then(c=>{const d=c.length.toString().length;return{suggestions:c.map((f,p)=>({kind:sa(f.type,this.monaco),label:f.label,insertText:f.insertText,sortText:p.toString().padStart(d,"0"),range:n}))}})}setTags(e){e.forEach(a=>this.tags[a]=new Set)}async getTagValues(e){let a;return this.cachedValues.hasOwnProperty(e)?a=this.cachedValues[e]:(a=await this.languageProvider.getOptionsV1(e),this.cachedValues[e]=a),a}async getCompletions(e){if(!Object.keys(this.tags).length)return[];switch(e.type){case"UNKNOWN":return[];case"EMPTY":return this.getTagsCompletions();case"IN_NAME":return this.getTagsCompletions();case"IN_VALUE":const a=await this.getTagValues(e.tagName),n=[],s=i=>`"${i.label}"`;return a.forEach(i=>{i?.label&&n.push({label:i.label,insertText:s(i),type:"TAG_VALUE"})}),n;default:throw new Error(`Unexpected situation ${e}`)}}getTagsCompletions(){return Object.keys(this.tags).sort((e,a)=>e.localeCompare(a,void 0,{sensitivity:"accent"})).map(e=>({label:e,insertText:e,type:"TAG_NAME"}))}getSituation(e,a){if(e===""||a===0||e[e.length-1]===" ")return{type:"EMPTY"};const n=e.substring(0,a),s=/(?<key>[^= ]+)(?<equals>=)?(?<value>([^ "]+)|"([^"]*)")?/,i=n.match(new RegExp(s,"g"));if(i?.length){const c=i[i.length-1].match(s);if(c){const d=c.groups?.key,u=c.groups?.equals;return d?u?{type:"IN_VALUE",tagName:d}:{type:"IN_NAME"}:{type:"EMPTY"}}}return{type:"EMPTY"}}}function sa(t,e){switch(t){case"TAG_NAME":return e.languages.CompletionItemKind.Enum;case"KEYWORD":return e.languages.CompletionItemKind.Keyword;case"OPERATOR":return e.languages.CompletionItemKind.Operator;case"TAG_VALUE":return e.languages.CompletionItemKind.EnumMember;case"SCOPE":return e.languages.CompletionItemKind.Class;default:throw new Error(`Unexpected CompletionType: ${t}`)}}function na(t,e,a){const n=e.getWordAtPosition(a),s=n!=null?t.Range.lift({startLineNumber:a.lineNumber,endLineNumber:a.lineNumber,startColumn:n.startColumn,endColumn:n.endColumn}):t.Range.fromPositions(a),i={column:a.column,lineNumber:a.lineNumber};return{offset:e.getOffsetAt(i),range:s}}const ia={id:"tagsfield",extensions:[".tagsfield"],aliases:["tagsfield"],mimetypes:[],def:{language:{ignoreCase:!1,defaultToken:"",tokenPostfix:".tagsfield",operators:["="],symbols:/[=><!~?:&|+\-*\/^%]+/,escapes:/\\(?:[abfnrtv\\"']|x[0-9A-Fa-f]{1,4}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})/,digits:/\d+(_+\d+)*/,octaldigits:/[0-7]+(_+[0-7]+)*/,binarydigits:/[0-1]+(_+[0-1]+)*/,hexdigits:/[[0-9a-fA-F]+(_+[0-9a-fA-F]+)*/,integersuffix:/(ll|LL|u|U|l|L)?(ll|LL|u|U|l|L)?/,floatsuffix:/[fFlL]?/,tokenizer:{root:[[/[a-z_.][\w./_-]*(?=\s*(=|!=|>|<|>=|<=|=~|!~))/,"tag"],[/[a-zA-Z_.]\w*/,{cases:{"@default":"identifier"}}],[/"([^"\\]|\\.)*$/,"string.invalid"],[/'([^'\\]|\\.)*$/,"string.invalid"],[/"/,"string","@string_double"],[/'/,"string","@string_single"],{include:"@whitespace"},[/[{}()\[\]]/,"@brackets"],[/[<>](?!@symbols)/,"@brackets"],[/@symbols/,{cases:{"@operators":"delimiter","@default":""}}],[/\d+/,"number"],[/\d*\d+[eE]([\-+]?\d+)?(@floatsuffix)/,"number.float"],[/\d*\.\d+([eE][\-+]?\d+)?(@floatsuffix)/,"number.float"],[/0[xX][0-9a-fA-F']*[0-9a-fA-F](@integersuffix)/,"number.hex"],[/0[0-7']*[0-7](@integersuffix)/,"number.octal"],[/0[bB][0-1']*[0-1](@integersuffix)/,"number.binary"],[/\d[\d']*\d(@integersuffix)/,"number"],[/\d(@integersuffix)/,"number"]],string_double:[[/[^\\"]+/,"string"],[/@escapes/,"string.escape"],[/\\./,"string.escape.invalid"],[/"/,"string","@pop"]],string_single:[[/[^\\']+/,"string"],[/@escapes/,"string.escape"],[/\\./,"string.escape.invalid"],[/'/,"string","@pop"]],clauses:[[/[^(,)]/,"tag"],[/\)/,"identifier","@pop"]],whitespace:[[/[ \t\r\n]+/,"white"]]}},languageConfiguration:{wordPattern:/(-?\d*\.\d\w*)|([^`~!#%^&*()\-=+\[{\]}\\|;:'",.<>\/?\s]+)/g,brackets:[["{","}"],["(",")"]],autoClosingPairs:[{open:"{",close:"}"},{open:"(",close:")"},{open:'"',close:'"'},{open:"'",close:"'"}],surroundingPairs:[{open:"{",close:"}"},{open:"(",close:")"},{open:'"',close:'"'},{open:"'",close:"'"}],folding:{}}}};function oa(t){const{onChange:e,onBlur:a,placeholder:n}=t,s=ua(t.datasource),i=(0,x.l4)(),l=ma(i,n);return r.createElement(et.p,{value:t.value,language:fe,onBlur:a,onChange:e,containerStyles:l.queryField,monacoOptions:{folding:!1,fontSize:14,lineNumbers:"off",overviewRulerLanes:0,renderLineHighlight:"none",scrollbar:{vertical:"hidden",verticalScrollbarSize:8,horizontal:"hidden",horizontalScrollbarSize:0},scrollBeyondLastLine:!1,wordWrap:"on"},onBeforeEditorMount:da,onEditorDidMount:(c,d)=>{s(c,d),la(c,d,l),ca(c)}})}function la(t,e,a){const n=[{range:new e.Range(1,1,1,1),options:{className:a.placeholder,isWholeLine:!0}}];let s=[];const i=()=>{const l=t.getModel();if(!l)return;const c=l.getValueLength()===0?n:[];s=l.deltaDecorations(s,c)};i(),t.onDidChangeModelContent(i)}function ca(t){const e=t.getDomNode(),a=()=>{if(e){const n=Math.min(1e3,t.getContentHeight()),s=parseInt(e.style.width,10);e.style.width=`${s}px`,e.style.height=`${n}px`,t.layout({width:s,height:n})}};t.onDidContentSizeChange(a),a()}function ua(t){const e=(0,r.useRef)(new ra({languageProvider:t.languageProvider}));(0,r.useEffect)(()=>{(async()=>{try{await t.languageProvider.start();const s=t.languageProvider.getTags();s&&(s.find(i=>i==="status.code")||s.push("status.code"),e.current.setTags(s))}catch(s){s instanceof Error&&(0,q.WI)((0,ie.$l)((0,U.t_)("Error",s)))}})()},[t]);const a=(0,r.useRef)(null);return(0,r.useEffect)(()=>()=>{a.current?.()},[]),(n,s)=>{e.current.editor=n,e.current.monaco=s;const{dispose:i}=s.languages.registerCompletionItemProvider(fe,e.current);a.current=i}}let st=!1;const fe="tagsfield";function da(t){if(!st){st=!0;const{aliases:e,extensions:a,mimetypes:n,def:s}=ia;t.languages.register({id:fe,aliases:e,extensions:a,mimetypes:n}),t.languages.setMonarchTokensProvider(fe,s.language),t.languages.setLanguageConfiguration(fe,s.languageConfiguration)}}const ma=(t,e)=>({queryField:v.css`
      border-radius: ${t.shape.borderRadius()};
      border: 1px solid ${t.components.input.borderColor};
      flex: 1;
    `,placeholder:v.css`
      ::after {
        content: '${e}';
        font-family: ${t.typography.fontFamilyMonospace};
        opacity: 0.3;
      }
    `}),nt="e.g. 1.2s, 100ms",ga=({datasource:t,query:e,onChange:a,onBlur:n,onRunQuery:s})=>{const i=(0,x.wW)(ha),l=(0,r.useMemo)(()=>new Ne(t),[t]),[c,d]=(0,r.useState)(),[u,f]=(0,r.useState)(),[p,M]=(0,r.useState)(null),[A,Q]=(0,r.useState)({}),[Z,H]=(0,r.useState)({serviceName:!1,spanName:!1}),Y=(0,r.useCallback)(async(b,_="")=>{const de=b==="serviceName"?"service.name":"name";H(V=>({...V,[b]:!0}));try{return(await l.getOptionsV1(de)).filter(be=>be.value?(0,aa.C)(be.value,_).found:!1)}catch(V){return(0,oe.kW)(V)&&V?.status===404?M(V):V instanceof Error&&(0,q.WI)((0,rt.$l)((0,U.t_)("Error",V))),[]}finally{H(V=>({...V,[b]:!1}))}},[l]);(0,r.useEffect)(()=>{(async()=>{try{const[_,de]=await Promise.all([Y("serviceName"),Y("spanName")]);e.serviceName&&(0,me.J)().containsTemplate(e.serviceName)&&_.push((0,at.E)(e.serviceName)),d(_),e.spanName&&(0,me.J)().containsTemplate(e.spanName)&&de.push((0,at.E)(e.spanName)),f(de)}catch(_){(0,oe.kW)(_)&&_?.status===404?M(_):_ instanceof Error&&(0,q.WI)((0,rt.$l)((0,U.t_)("Error",_)))}})()},[l,Y,e.serviceName,e.spanName]);const D=b=>{b.key==="Enter"&&(b.shiftKey||b.ctrlKey)&&s()},L=(0,r.useCallback)(b=>{a({...e,search:b})},[a,e]),B=(0,me.J)();return r.createElement(r.Fragment,null,r.createElement("div",{className:i.container},r.createElement(m.Z,null,r.createElement(T._,{label:"Service Name",labelWidth:14,grow:!0},r.createElement(ne.Ph,{inputId:"service",options:c,onOpenMenu:()=>{Y("serviceName")},isLoading:Z.serviceName,value:c?.find(b=>b?.value===e.serviceName)||e.serviceName,onChange:b=>{a({...e,serviceName:b?.value})},placeholder:"Select a service",isClearable:!0,onKeyDown:D,"aria-label":"select-service-name",allowCustomValue:!0}))),r.createElement(m.Z,null,r.createElement(T._,{label:"Span Name",labelWidth:14,grow:!0},r.createElement(ne.Ph,{inputId:"spanName",options:u,onOpenMenu:()=>{Y("spanName")},isLoading:Z.spanName,value:u?.find(b=>b?.value===e.spanName)||e.spanName,onChange:b=>{a({...e,spanName:b?.value})},placeholder:"Select a span",isClearable:!0,onKeyDown:D,"aria-label":"select-span-name",allowCustomValue:!0}))),r.createElement(m.Z,null,r.createElement(T._,{label:"Tags",labelWidth:14,grow:!0,tooltip:"Values should be in logfmt."},r.createElement(oa,{placeholder:"http.status_code=200 error=true",value:e.search||"",onChange:L,onBlur:n,datasource:t}))),r.createElement(m.Z,null,r.createElement(T._,{label:"Min Duration",invalid:!!A.minDuration,labelWidth:14,grow:!0},r.createElement(ue.I,{id:"minDuration",value:e.minDuration||"",placeholder:nt,onBlur:()=>{const b=B.replace(e.minDuration??"");e.minDuration&&!(0,Te.IA)(b)?Q({...A,minDuration:!0}):Q({...A,minDuration:!1})},onChange:b=>a({...e,minDuration:b.currentTarget.value}),onKeyDown:D}))),r.createElement(m.Z,null,r.createElement(T._,{label:"Max Duration",invalid:!!A.maxDuration,labelWidth:14,grow:!0},r.createElement(ue.I,{id:"maxDuration",value:e.maxDuration||"",placeholder:nt,onBlur:()=>{const b=B.replace(e.maxDuration??"");e.maxDuration&&!(0,Te.IA)(b)?Q({...A,maxDuration:!0}):Q({...A,maxDuration:!1})},onChange:b=>a({...e,maxDuration:b.currentTarget.value}),onKeyDown:D}))),r.createElement(m.Z,null,r.createElement(T._,{label:"Limit",invalid:!!A.limit,labelWidth:14,grow:!0,tooltip:"Maximum number of returned results"},r.createElement(ue.I,{id:"limit",value:e.limit||"",placeholder:`Default: ${re}`,type:"number",onChange:b=>{let _=b.currentTarget.value?parseInt(b.currentTarget.value,10):void 0;_&&(!Number.isInteger(_)||_<=0)?Q({...A,limit:!0}):Q({...A,limit:!1}),a({...e,limit:b.currentTarget.value?parseInt(b.currentTarget.value,10):void 0})},onKeyDown:D})))),p?r.createElement(W.b,{title:"Unable to connect to Tempo search",severity:"info",className:i.alert},"Please ensure that Tempo is configured with search enabled. If you would like to hide this tab, you can configure it in the ",r.createElement("a",{href:`/datasources/edit/${t.uid}`},"datasource settings"),"."):null)},ha=t=>({container:v.css`
    max-width: 500px;
  `,alert:v.css`
    max-width: 75ch;
    margin-top: ${t.spacing(2)};
  `});var pa=o(44847),it=o(86647);async function ot(t){if(!t)return;const e=(0,it.F)();try{return await e.get(t)}catch(a){console.error("Failed to load data source",a);return}}function fa({graphDatasourceUid:t,query:e,onChange:a}){const n=(0,x.wW)(ya),s=(0,C.Z)(()=>ot(t),[t]),[i,l]=(0,r.useState)(void 0);if((0,r.useEffect)(()=>{async function u(f){const p=await f.getTagKeys({series:["traces_service_graph_request_server_seconds_sum","traces_service_graph_request_total","traces_service_graph_request_failed_total"]});l(Boolean(p.length))}!s.loading&&s.value&&u(s.value)},[s]),s.loading)return null;const c=s.value;if(!t)return r.createElement("div",{className:"text-warning"},"Please set up a service graph datasource in the datasource settings.");if(t&&!c)return r.createElement("div",{className:"text-warning"},"Service graph datasource is configured but the data source no longer exists. Please configure existing data source to use the service graph functionality.");const d=va(e.serviceMapQuery||"");return r.createElement("div",null,r.createElement(m.Z,null,r.createElement(T._,{label:"Filter",labelWidth:14,grow:!0},r.createElement(pa.F,{datasource:{uid:t},filters:d,getTagKeysOptions:{series:["traces_service_graph_request_total","traces_spanmetrics_calls_total"]},addFilter:u=>{a({...e,serviceMapQuery:Oe([...d,u])})},removeFilter:u=>{const f=[...d];f.splice(u,1),a({...e,serviceMapQuery:Oe(f)})},changeFilter:(u,f)=>{const p=[...d];p.splice(u,1,f),a({...e,serviceMapQuery:Oe(p)})}}))),i===!1?r.createElement(W.b,{title:"No service graph data found",severity:"info",className:n.alert},"Please ensure that service graph metrics are set up correctly according to the"," ",r.createElement("a",{target:"_blank",rel:"noreferrer noopener",href:"https://grafana.com/docs/tempo/next/grafana-agent/service-graphs/"},"Tempo documentation"),"."):null)}function va(t){let e,a=[];const n=/([\w_]+)(=|!=|<|>|=~|!~)"(.*?)"/g;for(;(e=n.exec(t))!==null;)a.push({key:e[1],operator:e[2],value:e[3],condition:""});return a}function Oe(t){return`{${t.map(e=>`${e.key}${e.operator}"${e.value}"`).join(",")}}`}const ya=t=>({alert:v.css`
    max-width: 75ch;
    margin-top: ${t.spacing(2)};
  `}),Ea=S.v.featureToggles.traceqlSearch?"traceqlSearch":"traceql";class Ta extends r.PureComponent{constructor(e){super(e),this.onChangeLinkedQuery=a=>{const{query:n,onChange:s}=this.props;s({...n,linkedQuery:{...a,refId:"linked"}})},this.onRunLinkedQuery=()=>{this.props.onRunQuery()},this.onClearResults=()=>{const{onChange:a,query:n,onRunQuery:s}=this.props;a({...n,queryType:"clear"}),s()}}async componentDidMount(){(!this.props.query.queryType||this.props.query.queryType==="clear")&&this.props.onChange({...this.props.query,queryType:Ea})}render(){const{query:e,onChange:a,datasource:n,app:s}=this.props,i=n.getLokiSearchDS(),l=n.serviceMap?.datasourceUid;let c=[{value:"traceql",label:"TraceQL"},{value:"upload",label:"JSON File"},{value:"serviceMap",label:"Service Graph"}];return S.v.featureToggles.traceqlSearch&&c.unshift({value:"traceqlSearch",label:"Search"}),!S.v.featureToggles.traceqlSearch&&!n?.search?.hide&&c.unshift({value:"nativeSearch",label:"Search"}),i&&(n?.search?.hide?c.unshift({value:"search",label:"Search"}):c.push({value:"search",label:"Loki Search"})),r.createElement(r.Fragment,null,r.createElement(m.Z,null,r.createElement(T._,{label:"Query type"},r.createElement(E.S,{options:c,value:e.queryType,onChange:d=>{(0,N.ff)("grafana_traces_query_type_changed",{datasourceType:"tempo",app:s??"",grafana_version:S.v.buildInfo.version,newQueryType:d,previousQueryType:e.queryType??""}),this.onClearResults(),a({...e,queryType:d})},size:"md"}))),e.queryType==="search"&&r.createElement(Sa,{logsDatasourceUid:i,query:e,onRunQuery:this.onRunLinkedQuery,onChange:this.onChangeLinkedQuery}),e.queryType==="nativeSearch"&&r.createElement(ga,{datasource:this.props.datasource,query:e,onChange:a,onBlur:this.props.onBlur,onRunQuery:this.props.onRunQuery}),e.queryType==="traceqlSearch"&&r.createElement(Ut,{datasource:this.props.datasource,query:e,onChange:a,onBlur:this.props.onBlur}),e.queryType==="upload"&&r.createElement("div",{className:(0,v.css)({padding:this.props.theme.spacing(2)})},r.createElement(I.Yo,{options:{multiple:!1},onLoad:d=>{this.props.datasource.uploadedJson=d,this.props.onRunQuery()}})),e.queryType==="serviceMap"&&r.createElement(fa,{graphDatasourceUid:l,query:e,onChange:a}),e.queryType==="traceql"&&r.createElement(ea,{datasource:this.props.datasource,query:e,onRunQuery:this.props.onRunQuery,onChange:a}))}}function Sa({logsDatasourceUid:t,onChange:e,onRunQuery:a,query:n}){const s=(0,C.Z)(()=>ot(t),[t]);if(s.loading)return null;const i=s.value;return i?r.createElement(r.Fragment,null,r.createElement(g.W,null,"Tempo uses ",i.name," to find traces."),r.createElement(k.n,{datasource:i,onChange:e,onRunQuery:a,query:n.linkedQuery??{refId:"linked"},history:[]})):t?t&&!i?r.createElement("div",{className:"text-warning"},"Loki search datasource is configured but the data source no longer exists. Please configure existing data source to use the search."):null:r.createElement("div",{className:"text-warning"},"Please set up a Loki search datasource in the datasource settings.")}const ba=(0,x.HE)(Ta);var Da=o(12006),xa=o(90950),Ca=o(83437),Ia=o(48288),Na=o(95638),j=o(73446),lt=o(53117),ct=o(31403),ve=o(62911),$e=o(8944);function Ma({options:t,onOptionsChange:e}){const a=(0,x.wW)(ye);return r.createElement("div",{className:a.container},r.createElement("h3",{className:"page-heading"},"TraceID query"),r.createElement("div",{className:a.infoText},"Modify how TraceID queries are run",r.createElement(ve.j,{hrefSuffix:"tempo/#traceid-query"})),r.createElement(T._,{label:"Use time range in query",tooltip:"The time range can be used when there are performance issues or timeouts since it will narrow down the search to the defined range. Default: disabled",labelWidth:26},r.createElement($e.x,{id:"enable-time-shift",value:t.jsonData.traceQuery?.timeShiftEnabled||!1,onChange:n=>{(0,j.tp)({onOptionsChange:e,options:t},"traceQuery",{...t.jsonData.traceQuery,timeShiftEnabled:n.currentTarget.checked})}})),r.createElement(m.Z,null,r.createElement(T._,{label:"Time shift for start of search",labelWidth:26,disabled:!t.jsonData.traceQuery?.timeShiftEnabled,grow:!0,tooltip:"Shifts the start of the time range when searching by TraceID. Searching can return traces that do not fully fall into the search time range, so we recommend using higher time shifts for longer traces. Default: 30m (Time units can be used here, for example: 5s, 1m, 3h)"},r.createElement(ue.I,{type:"text",placeholder:"30m",width:40,onChange:n=>(0,j.tp)({onOptionsChange:e,options:t},"traceQuery",{...t.jsonData.traceQuery,spanStartTimeShift:n.currentTarget.value}),value:t.jsonData.traceQuery?.spanStartTimeShift||""}))),r.createElement(m.Z,null,r.createElement(T._,{label:"Time shift for end of search",labelWidth:26,disabled:!t.jsonData.traceQuery?.timeShiftEnabled,grow:!0,tooltip:"Shifts the end of the time range when searching by TraceID. Searching can return traces that do not fully fall into the search time range, so we recommend using higher time shifts for longer traces. Default: 30m (Time units can be used here, for example: 5s, 1m, 3h)"},r.createElement(ue.I,{type:"text",placeholder:"30m",width:40,onChange:n=>(0,j.tp)({onOptionsChange:e,options:t},"traceQuery",{...t.jsonData.traceQuery,spanEndTimeShift:n.currentTarget.value}),value:t.jsonData.traceQuery?.spanEndTimeShift||""}))))}const ye=t=>({infoText:v.css`
    padding-bottom: ${t.spacing(2)};
    color: ${t.colors.text.secondary};
  `,container:v.css`
    width: 100%;
  `,row:v.css`
    align-items: baseline;
  `});function wa({options:t,onOptionsChange:e}){const a=(0,x.wW)(ye),n=t.jsonData.tracesToLogs?.lokiSearch!==!1?t.jsonData.tracesToLogs?.datasourceUid:void 0;return n&&t.jsonData.lokiSearch===void 0&&(0,j.tp)({onOptionsChange:e,options:t},"lokiSearch",{datasourceUid:n}),r.createElement("div",{className:a.container},r.createElement("h3",{className:"page-heading"},"Loki search"),r.createElement("div",{className:a.infoText},"Select a Loki data source to search for traces. Derived fields must be configured in the Loki data source",r.createElement(ve.j,{hrefSuffix:"tempo/#loki-search"})),r.createElement(m.Z,{className:a.row},r.createElement(T._,{tooltip:"The Loki data source with the service graph data",label:"Data source",labelWidth:26},r.createElement(lt.q,{inputId:"loki-search-data-source-picker",pluginId:"loki",current:t.jsonData.lokiSearch?.datasourceUid,noDefault:!0,width:40,onChange:s=>(0,j.tp)({onOptionsChange:e,options:t},"lokiSearch",{datasourceUid:s.uid})})),t.jsonData.lokiSearch?.datasourceUid?r.createElement(ct.zx,{type:"button",variant:"secondary",size:"sm",fill:"text",onClick:()=>{(0,j.tp)({onOptionsChange:e,options:t},"lokiSearch",{datasourceUid:void 0})}},"Clear"):null))}function Pa({options:t,onOptionsChange:e}){const a=(0,x.wW)(ye);return r.createElement("div",{className:a.container},r.createElement("h3",{className:"page-heading"},"Tempo search"),r.createElement("div",{className:a.infoText},"Modify how traces are searched",r.createElement(ve.j,{hrefSuffix:"tempo/#tempo-search"})),r.createElement(m.Z,{className:a.row},r.createElement(T._,{tooltip:"Removes the search tab from the query editor",label:"Hide search",labelWidth:26},r.createElement($e.x,{id:"hideSearch",value:t.jsonData.search?.hide,onChange:n=>(0,j.tp)({onOptionsChange:e,options:t},"search",{...t.jsonData.search,hide:n.currentTarget.checked})}))))}function La({options:t,onOptionsChange:e}){const a=(0,x.wW)(ye);return r.createElement("div",{className:a.container},r.createElement("h3",{className:"page-heading"},"Service graph"),r.createElement("div",{className:a.infoText},"Select a Prometheus data source that contains the service graph data",r.createElement(ve.j,{hrefSuffix:"tempo/#service-graph"})),r.createElement(m.Z,{className:a.row},r.createElement(T._,{tooltip:"The Prometheus data source with the service graph data",label:"Data source",labelWidth:26},r.createElement(lt.q,{inputId:"service-graph-data-source-picker",pluginId:"prometheus",current:t.jsonData.serviceMap?.datasourceUid,noDefault:!0,width:40,onChange:n=>(0,j.tp)({onOptionsChange:e,options:t},"serviceMap",{datasourceUid:n.uid})})),t.jsonData.serviceMap?.datasourceUid?r.createElement(ct.zx,{type:"button",variant:"secondary",size:"sm",fill:"text",onClick:()=>{(0,j.tp)({onOptionsChange:e,options:t},"serviceMap",{datasourceUid:void 0})}},"Clear"):null))}function Ra({options:t,onOptionsChange:e,datasource:a}){const n=async()=>{if(!a)throw new Error("Unable to retrieve datasource");try{await a.languageProvider.start();const u=a.languageProvider.getTags();if(u)return u.find(f=>f==="status")||u.push("status"),u}catch(u){throw new Error(`${u.statusText}: ${u.data.error}`)}return[]},{error:s,loading:i,value:l}=(0,C.Z)(n,[a,t]),c=(0,r.useCallback)(u=>{let f=t.jsonData.search?.filters;f||=[];const p=f.findIndex(M=>M.id===u.id);p>=0?f=ze(f,p,u):f.push(u),(0,j.tp)({onOptionsChange:e,options:t},"search",{...t.jsonData.search,filters:f})},[e,t]),d=u=>{(0,j.tp)({onOptionsChange:e,options:t},"search",{...t.jsonData.search,filters:t.jsonData.search?.filters?.filter(f=>f.id!==u.id)})};return(0,r.useEffect)(()=>{t.jsonData.search?.filters||(0,j.tp)({onOptionsChange:e,options:t},"search",{...t.jsonData.search,filters:[{id:"service-name",tag:"service.name",operator:"=",scope:G.Resource},{id:"span-name",tag:"name",operator:"=",scope:G.Span}]})},[e,t]),r.createElement(r.Fragment,null,a?r.createElement(Xe,{updateFilter:c,deleteFilter:d,filters:t.jsonData.search?.filters||[],datasource:a,setError:()=>{},tags:[...he,...l||[]],isTagsLoading:i,hideValues:!0}):r.createElement("div",null,"Invalid data source, please create a valid data source and try again"),s&&r.createElement(W.b,{title:"Unable to fetch TraceQL tags",severity:"error",topSpacing:1},s.message))}function Aa({options:t,onOptionsChange:e}){const a=(0,x.wW)(ye),n=(0,it.F)(),s=async()=>await n.get({type:t.type,uid:t.uid}),{value:i}=(0,C.Z)(s,[n,t]);return r.createElement("div",{className:a.container},r.createElement("h3",{className:"page-heading"},"Tempo search"),r.createElement("div",{className:a.infoText},"Modify how traces are searched",r.createElement(ve.j,{hrefSuffix:"tempo/#tempo-search"})),r.createElement(m.Z,{className:a.row},r.createElement(T._,{tooltip:"Removes the search tab from the query editor",label:"Hide search",labelWidth:26},r.createElement($e.x,{id:"hideSearch",value:t.jsonData.search?.hide,onChange:l=>(0,j.tp)({onOptionsChange:e,options:t},"search",{...t.jsonData.search,hide:l.currentTarget.checked})}))),r.createElement(m.Z,{className:a.row},r.createElement(T._,{tooltip:"Configures which fields are available in the UI",label:"Static filters",labelWidth:26},r.createElement(Ra,{datasource:i,options:t,onOptionsChange:e}))))}const Qa=({options:t,onOptionsChange:e})=>r.createElement(r.Fragment,null,r.createElement(Da.E,{defaultUrl:"http://tempo",dataSourceConfig:t,showAccessOptions:!1,onChange:e,secureSocksDSProxyEnabled:S.v.secureSocksDSProxyEnabled}),r.createElement("div",{className:"gf-form-group"},r.createElement(Ca.Z,{options:t,onOptionsChange:e})),S.v.featureToggles.traceToMetrics?r.createElement("div",{className:"gf-form-group"},r.createElement(Ia.F,{options:t,onOptionsChange:e})):null,r.createElement("div",{className:"gf-form-group"},r.createElement(La,{options:t,onOptionsChange:e})),r.createElement("div",{className:"gf-form-group"},r.createElement(xa.n,{options:t,onOptionsChange:e})),r.createElement("div",{className:"gf-form-group"},S.v.featureToggles.traceqlSearch?r.createElement(Aa,{options:t,onOptionsChange:e}):r.createElement(Pa,{options:t,onOptionsChange:e})),r.createElement("div",{className:"gf-form-group"},r.createElement(wa,{options:t,onOptionsChange:e})),r.createElement("div",{className:"gf-form-group"},r.createElement(Ma,{options:t,onOptionsChange:e})),r.createElement("div",{className:"gf-form-group"},r.createElement(Na.SpanBarSettings,{options:t,onOptionsChange:e})));var Oa=o(35630);const $a=({payload:{dashboardId:t,orgId:e,grafanaVersion:a,queries:n}})=>{try{const s=n[Oa.id];if(!s?.length)return;let i={grafana_version:a,dashboard_id:t,org_id:e,native_search_query_count:0,search_query_count:0,service_map_query_count:0,traceql_query_count:0,upload_query_count:0,native_search_queries_with_template_variables_count:0,search_queries_with_template_variables_count:0,service_map_queries_with_template_variables_count:0,traceql_queries_with_template_variables_count:0};for(const l of s)l.hide||(l.queryType==="nativeSearch"?(i.native_search_query_count++,(l.serviceName&&ee(l.serviceName)||l.spanName&&ee(l.spanName)||l.search&&ee(l.search)||l.minDuration&&ee(l.minDuration)||l.maxDuration&&ee(l.maxDuration))&&i.native_search_queries_with_template_variables_count++):l.queryType==="search"?(i.search_query_count++,l.linkedQuery&&l.linkedQuery.expr&&ee(l.linkedQuery.expr)&&i.search_queries_with_template_variables_count++):l.queryType==="serviceMap"?(i.service_map_query_count++,l.serviceMapQuery&&ee(l.serviceMapQuery)&&i.service_map_queries_with_template_variables_count++):l.queryType==="traceql"?(i.traceql_query_count++,ee(l.query)&&i.traceql_queries_with_template_variables_count++):l.queryType==="upload"&&i.upload_query_count++);(0,N.ff)("grafana_tempo_dashboard_loaded",i)}catch(s){console.error("error in tempo tracking handler",s)}},ee=t=>(0,me.J)().containsTemplate(t),_a=new y.hf(Mt).setQueryEditor(ba).setConfigEditor(Qa).setQueryEditorHelp(P);(0,R.N$)().subscribe(h.Pl,$a)},42638:(te,$,o)=>{var y;y={value:!0};var h=o(9683),R=o(66111),r=h.__importDefault(o(55986));function N(S,P){P===void 0&&(P=[]);var v=r.default(S,P,{loading:!0}),C=v[0],m=v[1];return R.useEffect(function(){m()},[m]),C}$.Z=N}}]);

//# sourceMappingURL=5644.c57cb4174d996eeb147a.js.map