"use strict";(self.webpackChunkgrafana=self.webpackChunkgrafana||[]).push([[5252],{27871:(se,U,l)=>{l.d(U,{n:()=>R});var y=l(60234),v=l(65237),P=l(65820),s=l(54805),M=l(1163),D=l(57313);function R({options:x,onOptionsChange:g}){return v.createElement("div",{className:m.container},v.createElement("h3",{className:"page-heading"},"Node graph"),v.createElement(s.Z,{className:m.row},v.createElement(M._,{tooltip:"Displays the node graph above the trace view. Default: disabled",label:"Enable node graph",labelWidth:26},v.createElement(D.x,{id:"enableNodeGraph",value:x.jsonData.nodeGraph?.enabled,onChange:S=>(0,P.tp)({onOptionsChange:g,options:x},"nodeGraph",{...x.jsonData.nodeGraph,enabled:S.currentTarget.checked})}))))}const m={container:y.css`
    label: container;
    width: 100%;
  `,row:y.css`
    label: row;
    align-items: baseline;
  `}},87825:(se,U,l)=>{l.d(U,{F:()=>S});var y=l(60234),v=l(65237),P=l(65820),s=l(58526),M=l(93048),D=l(54805),R=l(1163),m=l(48389),x=l(96682),g=l(36659);function S({options:h,onOptionsChange:C}){const L=(0,M.wW)(E);return v.createElement("div",{className:(0,y.css)({width:"100%"})},v.createElement("h3",{className:"page-heading"},"Trace to metrics"),v.createElement("div",{className:L.infoText},"Navigate from a trace span to the selected data source's metrics."),v.createElement(D.Z,{className:L.row},v.createElement(R._,{tooltip:"The Prometheus data source the trace is going to navigate to",label:"Data source",labelWidth:26},v.createElement(s.q,{inputId:"trace-to-metrics-data-source-picker",pluginId:"prometheus",current:h.jsonData.tracesToMetrics?.datasourceUid,noDefault:!0,width:40,onChange:Q=>(0,P.tp)({onOptionsChange:C,options:h},"tracesToMetrics",{...h.jsonData.tracesToMetrics,datasourceUid:Q.uid})})),h.jsonData.tracesToMetrics?.datasourceUid?v.createElement(m.zx,{type:"button",variant:"secondary",size:"sm",fill:"text",onClick:()=>{(0,P.tp)({onOptionsChange:C,options:h},"tracesToMetrics",{...h.jsonData.tracesToMetrics,datasourceUid:void 0})}},"Clear"):null),v.createElement(D.Z,null,v.createElement(R._,{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)"},v.createElement(x.I,{type:"text",placeholder:"0",width:40,onChange:Q=>(0,P.tp)({onOptionsChange:C,options:h},"tracesToMetrics",{...h.jsonData.tracesToMetrics,spanStartTimeShift:Q.currentTarget.value}),value:h.jsonData.tracesToMetrics?.spanStartTimeShift||""}))),v.createElement(D.Z,null,v.createElement(R._,{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)"},v.createElement(x.I,{type:"text",placeholder:"0",width:40,onChange:Q=>(0,P.tp)({onOptionsChange:C,options:h},"tracesToMetrics",{...h.jsonData.tracesToMetrics,spanEndTimeShift:Q.currentTarget.value}),value:h.jsonData.tracesToMetrics?.spanEndTimeShift||""}))),v.createElement(D.Z,null,v.createElement(R._,{tooltip:"Tags that will be used in the metrics query",label:"Tags",labelWidth:26},v.createElement(g.a,{values:h.jsonData.tracesToMetrics?.tags??[],onChange:Q=>(0,P.tp)({onOptionsChange:C,options:h},"tracesToMetrics",{...h.jsonData.tracesToMetrics,tags:Q})}))),h.jsonData.tracesToMetrics?.queries?.map((Q,B)=>v.createElement("div",{key:B,className:L.queryRow},v.createElement(R._,{label:"Link Label",labelWidth:26,tooltip:"Descriptive label for the linked query"},v.createElement(x.I,{label:"Link Label",type:"text",allowFullScreen:!0,value:Q.name,width:40,onChange:F=>{let W=h.jsonData.tracesToMetrics?.queries.slice()??[];W[B].name=F.currentTarget.value,(0,P.tp)({onOptionsChange:C,options:h},"tracesToMetrics",{...h.jsonData.tracesToMetrics,queries:W})}})),v.createElement(R._,{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},v.createElement(x.I,{label:"Query",type:"text",allowFullScreen:!0,value:Q.query,onChange:F=>{let W=h.jsonData.tracesToMetrics?.queries.slice()??[];W[B].query=F.currentTarget.value,(0,P.tp)({onOptionsChange:C,options:h},"tracesToMetrics",{...h.jsonData.tracesToMetrics,queries:W})}})),v.createElement(m.zx,{variant:"destructive",title:"Remove query",icon:"times",type:"button",onClick:()=>{let F=h.jsonData.tracesToMetrics?.queries.slice();F?.splice(B,1),(0,P.tp)({onOptionsChange:C,options:h},"tracesToMetrics",{...h.jsonData.tracesToMetrics,queries:F})}}))),v.createElement(m.zx,{variant:"secondary",title:"Add query",icon:"plus",type:"button",onClick:()=>{(0,P.tp)({onOptionsChange:C,options:h},"tracesToMetrics",{...h.jsonData.tracesToMetrics,queries:[...h.jsonData.tracesToMetrics?.queries??[],{query:""}]})}},"Add query"))}const E=h=>({infoText:y.css`
    padding-bottom: ${h.spacing(2)};
    color: ${h.colors.text.secondary};
  `,row:y.css`
    label: row;
    align-items: baseline;
  `,queryRow:y.css`
    display: flex;
  `})},23794:(se,U,l)=>{l.d(U,{n:()=>D});var y=l(65237),v=l(25468);const P=y.lazy(()=>Promise.all([l.e(5560),l.e(2090),l.e(2309),l.e(7556),l.e(7142)]).then(l.bind(l,43676))),s=R=>y.createElement(y.Suspense,{fallback:null},y.createElement(P,{...R})),M=R=>{const m=(0,y.useRef)(null),{onRunQuery:x,onChange:g,...S}=R,E=C=>{m.current=C,g(C),x()},h=C=>{g(C)};return y.createElement(s,{onRunQuery:E,onBlur:h,...S})};class D extends y.PureComponent{constructor(m){super(m),this._isMounted=!1,this.onChangeQuery=(x,g)=>{const{query:S,onChange:E,onRunQuery:h}=this.props;if(E){const C={...S,expr:x};E(C),g&&h&&h()}},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(m){const{range:x,datasource:{languageProvider:g}}=this.props;(0,v.rf)(x,m.range)&&g.fetchLabels()}render(){const{ExtraFieldElement:m,query:x,datasource:g,history:S,onRunQuery:E,onQueryType:h}=this.props,C=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(M,{datasource:g,history:S??[],onChange:this.onChangeQuery,onRunQuery:E,initialValue:x.expr??"",placeholder:C,onQueryType:h}))),m)}}},25468:(se,U,l)=>{l.d(U,{Hk:()=>x,U9:()=>D,_z:()=>g,aC:()=>S,iS:()=>R,rf:()=>P,tU:()=>m});function y(E){return v(E/1e3)}function v(E){return Math.floor(E/60)}function P(E,h){if(E&&h){const C=y(E.from.valueOf())===y(h.from.valueOf()),L=y(E.to.valueOf())===y(h.to.valueOf());return!(C&&L)}return!1}const s=/[*+?()|\\.\[\]{}^$]/g;function M(E){return E.replace(s,"\\$&")}function D(E){return E.replace(/\\/g,"\\\\").replace(/\n/g,"\\n").replace(/"/g,'\\"')}function R(E){return E.replace(/\\n/g,`
`).replace(/\\"/g,'"').replace(/\\\\/g,"\\")}function m(E){return D(M(E))}function x(E,h){return g(h)?m(E):D(E)}function g(E){return!!(E&&(E.includes("=~")||E.includes("!~")))}function S(E){const h=["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"],C=new RegExp(`^(?:-?\\d+(?:\\.\\d+)?)(?:${h.join("|")})$`);return!!E.match(C)}},15839:(se,U,l)=>{l.d(U,{d:()=>m});var y=l(60234),v=l(65237),P=l(47153),s=l(9788),M=l(66917),D=l(93048),R=l(6335);function m({title:g,children:S,collapsedInfo:E,queryStats:h}){const[C,L]=(0,P.Z)(!1),Q=(0,D.wW)(x),B=()=>{const{text:F,suffix:W}=(0,s.Cf)("bytes")(h.bytes,1);return F+W};return v.createElement("div",{className:Q.wrapper},v.createElement(M.Stack,{gap:0,direction:"column"},v.createElement("div",{className:Q.header,onClick:L,title:"Click to edit options"},v.createElement("div",{className:Q.toggle},v.createElement(R.J,{name:C?"angle-down":"angle-right"})),v.createElement("h6",{className:Q.title},g),!C&&v.createElement("div",{className:Q.description},E.map((F,W)=>v.createElement("span",{key:W},F)))),C&&v.createElement("div",{className:Q.body},S)),h&&v.createElement("p",{className:Q.stats},"This query will process approximately ",B(),"."))}const x=g=>({wrapper:(0,y.css)({width:"100%",display:"flex",justifyContent:"space-between",alignItems:"baseline"}),switchLabel:(0,y.css)({color:g.colors.text.secondary,cursor:"pointer",fontSize:g.typography.bodySmall.fontSize,"&:hover":{color:g.colors.text.primary}}),header:(0,y.css)({display:"flex",cursor:"pointer",alignItems:"baseline",color:g.colors.text.primary,"&:hover":{background:g.colors.emphasize(g.colors.background.primary,.03)}}),title:(0,y.css)({flexGrow:1,overflow:"hidden",fontSize:g.typography.bodySmall.fontSize,fontWeight:g.typography.fontWeightMedium,margin:0}),description:(0,y.css)({color:g.colors.text.secondary,fontSize:g.typography.bodySmall.fontSize,paddingLeft:g.spacing(2),gap:g.spacing(2),display:"flex"}),body:(0,y.css)({display:"flex",paddingTop:g.spacing(2),gap:g.spacing(2),flexWrap:"wrap"}),toggle:(0,y.css)({color:g.colors.text.secondary,marginRight:`${g.spacing(1)}`}),stats:(0,y.css)({margin:"0px",color:g.colors.text.secondary,fontSize:g.typography.bodySmall.fontSize})})},7642:(se,U,l)=>{l.d(U,{U:()=>D});var y=l(60234),v=l(6570),P=l.n(v),s=l(65237),M=l(93048);function D({query:m,lang:x,className:g}){const S=(0,M.l4)(),E=R(S),h=P().highlight(m,x.grammar,x.name);return s.createElement("div",{className:(0,y.cx)(E.editorField,"prism-syntax-highlight",g),"aria-label":"selector",dangerouslySetInnerHTML:{__html:h}})}const R=m=>({editorField:(0,y.css)({fontFamily:m.typography.fontFamilyMonospace,fontSize:m.typography.bodySmall.fontSize})})},55252:(se,U,l)=>{l.r(U),l.d(U,{plugin:()=>Va});var y=l(9306),v=l(5777),P=l(25557),s=l(65237),M=l(28704),D=l(49784);function R(){return(0,M.ff)("grafana_traces_cheatsheet_clicked",{datasourceType:"tempo",grafana_version:D.v.buildInfo.version}),s.createElement("div",null,s.createElement("h2",{id:"tempo-cheat-sheet"},"Tempo Cheat Sheet"),s.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."),s.createElement("p",null,"Here are some"," ",s.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 m=l(60234),x=l(37843),g=l(54805),S=l(1163),E=l(12007),h=l(63469),C=l(58639),L=l(93048),Q=l(23794),B=l(66917),F=l(6741),W=l(88347),ne=l(93589),fe=l(19750),ie=l(18606),lt=l(7642),ct=l(43326),ut=l(15839),Y=l(89949),z=l(45383),Qe=l(91053),dt=l(91826),gt=l(6857),mt=l(42420),Oe=l(78209),$e=l(22479),q=l(39343),be=l(56469),Ue=l(9045),De=l(28037),ee=l(81859),Fe=l(65996),ve=l(79432),ye=l(43643),ht=l(71534),pt=l(12554),ft=l(88657),ge=l(10808),me=l(55041),Ee=l(91510),vt=l(25743),Te=l(12469);const ka=Object.freeze([0,0]),ja={filters:[]};var G=(t=>(t.Resource="resource",t.Span="span",t.Unscoped="unscoped",t))(G||{});const oe=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}=Et(this.monaco,t,e),r=this.getSituation(t.getValue(),n);return this.getCompletions(r).then(o=>{const c=o.length.toString().length;return{suggestions:o.map((u,f)=>{const p={kind:yt(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 Tt(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 oe.operators.map(r=>({label:r,insertText:r,type:"OPERATOR"}));case"SPANSET_IN_VALUE":const e=await this.getTagValues(t.tagName),a=[],n=r=>t.betweenQuotes?r.label:r.type==="string"?`"${r.label}"`:r.label;return e.forEach(r=>{r?.label&&a.push({label:r.label,insertText:n(r),type:"TAG_VALUE"})}),a;case"SPANSET_AFTER_VALUE":return oe.logicalOps.concat("}").map(r=>({label:r,insertText:r,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 oe.intrinsics.map(e=>({label:e,insertText:(t||"")+e,type:"KEYWORD"}))}getScopesCompletions(t){return oe.scopes.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&|]+))?/,r=new RegExp("([\\s{])("+e.source+"(?<space1>\\s*)("+a.source+"(?<space2>\\s*)"+n.source+")?)(?<space3>\\s*)$"),i=t.match(r);if(i){const o=i.groups?.name,c=i.groups?.op;if(!o)return{type:"SPANSET_EMPTY"};if(o===".")return{type:"SPANSET_ONLY_DOT"};const d=o.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:o,betweenQuotes:!!i.groups?.open_quote}:oe.scopes.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 J=oe;J.intrinsics=["duration","name","status"],J.scopes=["resource","span"],J.operators=["=","-","+","<",">",">=","<=","=~"],J.logicalOps=["&&","||"];function yt(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 Et(t,e,a){const n=e.getWordAtPosition(a),r=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:r}}function Tt(t,e,a,n){if(e==="TAG_NAME"){const r=a.getValue().substring(0,n).match(/(span\.|resource\.|\.)?([\w./-]*)$/);if(r){const i=r[1],o=r[2];o&&(!i&&t.insertText[0]!=="."&&(t.insertText="."+t.insertText),t.range={...t.range,startColumn:n-o.length+1})}}}const We=t=>`{${t.filter(e=>e.tag&&e.operator&&e.value?.length).map(e=>`${_e(e)}${e.tag}${e.operator}${St(e)}`).join(" && ")}}`,St=t=>Array.isArray(t.value)&&t.value.length>1?`"${t.value.join("|")}"`:t.valueType==="string"?`"${t.value}"`:t.value,_e=t=>J.intrinsics.find(e=>e===t.tag)?"":(t.scope===G.Resource||t.scope===G.Span?t.scope?.toLowerCase():"")+".",xe=t=>_e(t)+t.tag,bt=t=>t.tag==="name"?"Span Name":(0,Y.startCase)(xe(t));function Ve(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 _=l(92114);class Ce extends y.iL{constructor(e,a){super(),this.request=async(n,r={})=>(await this.datasource.metadataRequest(n,r))?.data,this.start=async()=>(this.startTask||(this.startTask=this.fetchTags().then(()=>[])),this.startTask),this.getTags=()=>this.tags,this.provideCompletionItems=async({text:n,value:r})=>{const i={suggestions:[]};if(!r)return i;const o=r.endText.getText();return o[o.indexOf(n)-1]==="="||n==="="?this.getTagValueCompletionItems(r):this.getTagsCompletionItems()},this.getTagsCompletionItems=()=>{const{tags:n}=this,r=[];return n?.length&&r.push({label:"Tag",items:n.map(i=>({label:i}))}),{suggestions:r}},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 r=await this.request(`/api/v2/search/tag/${n}/values`,[]),i=[];return r&&r.tagValues&&i.push({label:"Tag Values",items:r.tagValues.map(o=>({label:o,insertText:`"${o}"`}))}),{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(r=>({value:r,label:r}))),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(r=>({type:r.type,value:r.value,label:r.value}))),n}}var le=l(98483);const te=20;class Dt extends ft.CK{constructor(e,a=(0,ge.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 Ce(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(o=>!o.hide),r=(0,Y.groupBy)(n,o=>o.queryType||"traceql");if(r.clear)return(0,z.of)({data:[],state:ee.Gu.Done});const i=this.getLokiSearchDS();if(i&&r.search?.length>0){(0,M.ff)("grafana_traces_loki_search_queried",{datasourceType:"tempo",app:e.app??"",grafana_version:D.v.buildInfo.version,hasLinkedQueryExpr:!!(r.search[0].linkedQuery?.expr&&r.search[0].linkedQuery?.expr!=="")});const o=(0,Te.ak)();a.push((0,Qe.D)(o.get(i)).pipe((0,$e.z)(c=>{const d={...e,targets:r.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,dt._)(()=>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,q.U)(p=>p.error?p:(0,le.RY)(p,this.uid,this.name,f)))})))}if(r.nativeSearch?.length)try{(0,M.ff)("grafana_traces_search_queried",{datasourceType:"tempo",app:e.app??"",grafana_version:D.v.buildInfo.version,hasServiceName:!!r.nativeSearch[0].serviceName,hasSpanName:!!r.nativeSearch[0].spanName,resultLimit:r.nativeSearch[0].limit??"",hasSearch:!!r.nativeSearch[0].search,minDuration:r.nativeSearch[0].minDuration??"",maxDuration:r.nativeSearch[0].maxDuration??""});const o={startTime:e.range.from.unix(),endTime:e.range.to.unix()},c=this.applyVariables(r.nativeSearch[0],e.scopedVars),d=this.buildSearchQuery(c,o);a.push(this._request("/api/search",d).pipe((0,q.U)(u=>({data:[(0,le.n4)(u.data.traces,this.instanceSettings)]})),(0,be.K)(u=>(0,z.of)({error:{message:u.data.message},data:[]}))))}catch(o){return(0,z.of)({error:{message:o instanceof Error?o.message:"Unknown error occurred"},data:[]})}if(r.traceql?.length)try{const c=this.applyVariables(r.traceql[0],e.scopedVars)?.query||"",d=/^[0-9A-Fa-f]*$/;c.trim().match(d)?((0,M.ff)("grafana_traces_traceID_queried",{datasourceType:"tempo",app:e.app??"",grafana_version:D.v.buildInfo.version,hasQuery:c!==""}),a.push(this.handleTraceIdQuery(e,r.traceql))):((0,M.ff)("grafana_traces_traceql_queried",{datasourceType:"tempo",app:e.app??"",grafana_version:D.v.buildInfo.version,query:c??""}),a.push(this._request("/api/search",{q:c,limit:e.targets[0].limit??te,start:e.range.from.unix(),end:e.range.to.unix()}).pipe((0,q.U)(u=>({data:(0,le.xA)(u.data.traces,this.instanceSettings)})),(0,be.K)(u=>(0,z.of)({error:{message:u.data.message},data:[]})))))}catch(o){return(0,z.of)({error:{message:o instanceof Error?o.message:"Unknown error occurred"},data:[]})}if(r.traceqlSearch?.length)try{const o=We(r.traceqlSearch[0].filters);(0,M.ff)("grafana_traces_traceql_search_queried",{datasourceType:"tempo",app:e.app??"",grafana_version:D.v.buildInfo.version,query:o??""}),a.push(this._request("/api/search",{q:o,limit:e.targets[0].limit??te,start:e.range.from.unix(),end:e.range.to.unix()}).pipe((0,q.U)(c=>({data:(0,le.xA)(c.data.traces,this.instanceSettings)})),(0,be.K)(c=>(0,z.of)({error:{message:c.data.message},data:[]}))))}catch(o){return(0,z.of)({error:{message:o instanceof Error?o.message:"Unknown error occurred"},data:[]})}if(r.upload?.length)if(this.uploadedJson){(0,M.ff)("grafana_traces_json_file_uploaded",{datasourceType:"tempo",app:e.app??"",grafana_version:D.v.buildInfo.version});const o=JSON.parse(this.uploadedJson),c=o.batches,d=Array.isArray(o)&&o.some(u=>u?.meta?.preferredVisualisationType==="nodeGraph");c?a.push((0,z.of)((0,le.IM)(o.batches,this.nodeGraph?.enabled))):d?a.push((0,z.of)({data:o,state:ee.Gu.Done})):a.push((0,z.of)({error:{message:"Unable to parse uploaded data."},data:[]}))}else a.push((0,z.of)({data:[],state:ee.Gu.Done}));if(this.serviceMap?.datasourceUid&&r.serviceMap?.length>0){(0,M.ff)("grafana_traces_service_graph_queried",{datasourceType:"tempo",app:e.app??"",grafana_version:D.v.buildInfo.version,hasServiceMapQuery:!!r.serviceMap[0].serviceMapQuery});const o=this.serviceMap.datasourceUid,c=this.uid;a.push(xt(e,o,c).pipe((0,Ue.b)(d=>Ct(e,d,o).pipe((0,Ue.b)(u=>Nt(e,u,o,c))))))}return(0,gt.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),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 mt.E;const r=this.traceIdQueryRequest(e,n);return super.query(r).pipe((0,q.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(Fe.intervalToMs(this.traceQuery?.spanStartTimeShift||"30m"),"milliseconds"),to:e.range.to.add(Fe.intervalToMs(this.traceQuery?.spanEndTimeShift||"30m"),"milliseconds")}:n.range={from:(0,ve.CQ)(0),to:(0,ve.CQ)(0),raw:{from:(0,ve.CQ)(0),to:(0,ve.CQ)(0)}},n}async metadataRequest(e,a={}){return await(0,Oe.n)(this._request(e,a,{method:"GET",hideFromInspector:!0}))}_request(e,a,n){const r=a?(0,vt.tW)(a):"",i=`${this.instanceSettings.url}${e}${r.length?`?${r}`:""}`,o={...n,url:i};return(0,me.i)().fetch(o)}async testDatasource(){const e={headers:{},method:"GET",url:`${this.instanceSettings.url}/api/echo`};if((await(0,Oe.n)((0,me.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,Y.startCase)(n)}: ${e[n]}`);return a.join(", ")}return e.query}buildSearchQuery(e,a){let n=e.search??"",r=(0,Y.pick)(e,["minDuration","maxDuration","limit"]);if(r=(0,Y.pickBy)(r,Y.identity),e.serviceName&&(n+=` service.name="${e.serviceName}"`),e.spanName&&(n+=` name="${e.spanName}"`),r.limit||(r.limit=te),r.minDuration){if(r.minDuration=this.templateSrv.replace(r.minDuration??""),!(0,ye.IA)(r.minDuration))throw new Error("Please enter a valid min duration.");r.minDuration=r.minDuration.replace(/\s/g,"")}if(r.maxDuration){if(r.maxDuration=this.templateSrv.replace(r.maxDuration??""),!(0,ye.IA)(r.maxDuration))throw new Error("Please enter a valid max duration.");r.maxDuration=r.maxDuration.replace(/\s/g,"")}if(!Number.isInteger(r.limit)||r.limit<=0)throw new Error("Please enter a valid limit.");let i={tags:n,...r};return a&&(i.start=a.startTime,i.end=a.endTime),i}}function Ne(t,e){return(0,Qe.D)((0,Te.ak)().get(e)).pipe((0,$e.z)(a=>a.query(t)))}function xt(t,e,a){const n=Ie(t);return Ne(n,e).pipe((0,De.q)(),(0,q.U)(r=>{const i=r.find(d=>!!d.error);if(i)throw new Error(i.error.message);const{nodes:o,edges:c}=(0,_.BC)(r,t.range);if(o.fields.length>0&&c.fields.length>0){const d=o.fields[0].values.length,u=c.fields[0].values.length;(0,M.ff)("grafana_traces_service_graph_size",{datasourceType:"tempo",grafana_version:D.v.buildInfo.version,nodeLength:d,edgeLength:u})}return o.refId=t.targets[0].refId,c.refId=t.targets[0].refId,o.fields[0].config=je(e,a,"__data.fields.id","__data.fields[0]"),c.fields[0].config=je(e,a,"__data.fields.target","__data.fields.target","__data.fields.source"),{data:[o,c],state:ee.Gu.Done}}))}function Ct(t,e,a){const n=Ie(t);return n.targets=Ge([ae(_.rB,_.T1,t)]),Ne(n,a).pipe((0,De.q)(),(0,q.U)(r=>{const i=r.find(o=>!!o.error);if(i)throw new Error(i.error.message);return{data:[r[0]?.data??[],e.data[0],e.data[1]],state:ee.Gu.Done}}))}function Nt(t,e,a,n){let r=[],i="",o=[],c=[];t.app===ht.zj.Explore?e.data[0][0]?.fields[1]?.values&&(c=e.data[0][0]?.fields[1]?.values.toArray()):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=It(c);d.length>0&&(i=ae(_.$C,'span_name=~"'+d.join("|")+'"',t),r.push(i),d.map(f=>{const p=ae(_.vO,'span_name=~"'+f+'"',t);o.push(p),r.push(p)}));const u=Ie(t);return u.targets=Ge(r),Ne(u,a).pipe((0,De.q)(),(0,q.U)(f=>{const p=f.find(A=>!!A.error);if(p)throw new Error(p.error.message);const N=Mt(t,e,f[0],i,o,a,n);return N.fields.length===0?{data:[e.data[1],e.data[2]],state:ee.Gu.Done}:{data:[N,e.data[1],e.data[2]],state:ee.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,Te.ak)().getDataSourceSettingsByUid(a)?.name??""}}}function It(t){return t.map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\\\$&"))}function je(t,e,a,n,r){return r=r?`client="\${${r}}",`:"",{links:[ce("Request rate",`sum by (client, server)(rate(${_.Yt}{${r}server="\${${a}}"}[$__rate_interval]))`,t,!1),ce("Request histogram",`histogram_quantile(0.9, sum(rate(${_.NZ}{${r}server="\${${a}}"}[$__rate_interval])) by (le, client, server))`,t,!1),ce("Failed request rate",`sum by (client, server)(rate(${_.yf}{${r}server="\${${a}}"}[$__rate_interval]))`,t,!1),Be("View traces",`\${${n}}`,"",e)]}}function Be(t,e,a,n){let r={queryType:"nativeSearch"};return e!==""&&(r.serviceName=e),a!==""&&(r.spanName=a),{url:"",title:t,internal:{query:r,datasourceUid:n,datasourceName:(0,Te.ak)().getDataSourceSettingsByUid(n)?.name??""}}}function Ie(t){return{...t,targets:_.t3.map(e=>({format:"table",refId:e,expr:`sum by (client, server) (rate(${e}${t.targets[0].serviceMapQuery||""}[$__range]))`,instant:!0}))}}function Mt(t,e,a,n,r,i,o){let c={fields:[]};const d=e.data[0]?.filter(p=>p.refId===ae(_.rB,_.T1,t)),u=a.data.filter(p=>p.refId===n),f=a.data.filter(p=>r.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",Me(ae(_.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:Ee.QH.Lcd,type:Ee.h2.Gauge}},decimals:3}})),u.length>0&&u[0].fields?.length>2){const p=u[0].fields[1]?.values.toArray()??[],N=u[0].fields[2]?.values.toArray()??[];let A={};p.map((K,Z)=>{A[K]={value:N[Z]}});const O=ze({...d},A);c.fields.push({...u[0].fields[2],name:"Error Rate",values:O,config:{links:[ce("Error Rate",Me(ae(_.$C,'span_name="${__data.fields[0]}"',t)),i,!1)],decimals:2}}),c.fields.push({...u[0].fields[2],name:"   ",values:O,labels:null,config:{color:{mode:"continuous-RdYlGr"},custom:{cellOptions:{mode:Ee.QH.Lcd,type:Ee.h2.Gauge}},decimals:3}})}if(f.length>0&&f[0].fields?.length>1){let p={};f.map(N=>{const A=N.refId?.includes('span_name=~"')?'span_name=~"':'span_name="',O=N.refId?.split(A)[1].split('"}')[0];p[O]={value:N.fields[1].values.toArray()[0]}}),c.fields.push({...f[0].fields[1],name:"Duration (p90)",values:ze({...d},p),config:{links:[ce("Duration",Me(ae(_.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:pt.fS.string,values:c.fields[0].values.map(()=>"Tempo"),config:{links:[Be("Tempo","","${__data.fields[0]}",o)]}}),c}function ae(t,e,a){let n=a.targets[0]?.serviceMapQuery??"";const r=n.match(/^{(.*)}$/);r?.length&&(n=r[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(o=>o);return t.expr.replace("{}","{"+i.join(",")+"}")}function Me(t){return t=t.replace("topk(5, ","").replace(" by (span_name))",""),t.replace("__range","__rate_interval")}function ze(t,e){const a=t[0]?.fields[1]?.values.toArray()??[];let n=[];for(let r=0;r<a.length;r++)Object.keys(e).includes(a[r])?n.push(e[a[r]].value):n.push("0");return n}function Ge(t){return t.map(e=>({refId:e,expr:e,instant:!0}))}const we=s.memo(({onChange:t,query:e})=>{e.hasOwnProperty("limit")||(e.limit=te);const a=n=>{t({...e,limit:parseInt(n.currentTarget.value,10)})};return s.createElement(s.Fragment,null,s.createElement(B.EditorRow,null,s.createElement(ut.d,{title:"Options",collapsedInfo:[`Limit: ${e.limit||te}`]},s.createElement(B.EditorField,{label:"Limit",tooltip:"Maximum number of traces to return."},s.createElement(ct.H,{className:"width-4",placeholder:"auto",type:"number",min:1,defaultValue:e.limit||te,onCommitChange:a,value:e.limit})))))});we.displayName="TempoQueryBuilderOptions";const wt={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=["=","!=",">","<",">=","<=","=~"],Lt=["=","!=","=~"],Pt=["=","!=",">","<",">=","<="],Rt=["duration","name","status","parent"],At=["resource","span"],Qt={ignoreCase:!1,defaultToken:"",tokenPostfix:".traceql",keywords:Rt.concat(At),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"]]}},Ot={id:"traceql",extensions:[".traceql"],aliases:["tempo","traceql"],mimetypes:[],def:{language:Qt,languageConfiguration:wt}},$t={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:/[{};()`,.]/};var re=l(94795),ue=l(96682);const Ut=/^\d+(?:\.\d)?\d*(?:us|µs|ns|ms|s|m|h)$/,Ft=()=>({noBoxShadow:m.css`
    box-shadow: none;
    *:focus {
      box-shadow: none;
    }
  `}),Ze=({filter:t,operators:e,updateFilter:a})=>{const n=(0,L.wW)(Ft);let r=!1;return typeof t.value=="string"&&(r=t.value?!Ut.test(t.value.concat("")):!1),s.createElement(F.Lh,{spacing:"none"},s.createElement(re.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}),s.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:r,width:18}))},Le=({label:t,tooltip:e,children:a})=>s.createElement(g.Z,null,s.createElement(S._,{label:t,labelWidth:28,grow:!0,tooltip:e},a)),Wt=()=>({dropdown:m.css`
    box-shadow: none;
  `}),He=({filter:t,datasource:e,updateFilter:a,deleteFilter:n,isTagsLoading:r,tags:i,setError:o,hideScope:c,hideTag:d,hideValue:u,allowDelete:f})=>{const p=(0,L.wW)(Wt),N=(0,s.useMemo)(()=>new Ce(e),[e]),A=(0,s.useMemo)(()=>xe(t),[t]),[O,K]=(0,s.useState)(t.operator),[Z,H]=(0,s.useState)(t.value),b=async()=>{try{return await N.getOptionsV2(A)}catch(I){(0,me.kW)(I)&&I?.status===404?o(I):I instanceof Error&&(0,ie.WI)((0,fe.$l)((0,ne.t_)("Error",I)))}return[]},{loading:w,value:j}=(0,x.Z)(b,[A,N,o]);(0,s.useEffect)(()=>{Array.isArray(t.value)&&t.value.length>1&&t.operator!=="=~"&&(K(t.operator),a({...t,operator:"=~"})),Array.isArray(t.value)&&t.value.length<=1&&(Z?.length||0)>1&&a({...t,operator:O,value:t.value[0]})},[Z,O,a,t]),(0,s.useEffect)(()=>{H(t.value)},[t.value]);const T=Object.values(G).map(I=>({label:I,value:I})),$=j?.filter(I=>I.type===j[0]?.type),de=j?.length===$?.length?j?.[0]?.type:void 0;let V=Ke;switch(de){case"string":V=Lt;break;case"int":case"float":V=Pt}return s.createElement(F.Lh,{spacing:"none",width:"auto"},!c&&s.createElement(re.Ph,{className:p.dropdown,inputId:`${t.id}-scope`,options:T,value:t.scope,onChange:I=>{a({...t,scope:I?.value})},placeholder:"Select scope","aria-label":`select ${t.id} scope`}),!d&&s.createElement(re.Ph,{className:p.dropdown,inputId:`${t.id}-tag`,isLoading:r,options:(t.tag!==void 0?(0,Y.uniq)([t.tag,...i]):i).map(I=>({label:I,value:I})),value:t.tag,onChange:I=>{a({...t,tag:I?.value})},placeholder:"Select tag",isClearable:!0,"aria-label":`select ${t.id} tag`,allowCustomValue:!0}),s.createElement(re.Ph,{className:p.dropdown,inputId:`${t.id}-operator`,options:V.map(ke),value:t.operator,onChange:I=>{a({...t,operator:I?.value})},isClearable:!1,"aria-label":`select ${t.id} operator`,allowCustomValue:!0,width:8}),!u&&s.createElement(re.Ph,{className:p.dropdown,inputId:`${t.id}-value`,isLoading:w,options:j,value:t.value,onChange:I=>{Array.isArray(I)?a({...t,value:I.map(Se=>Se.value),valueType:I[0]?.type}):a({...t,value:I?.value,valueType:I?.type})},placeholder:"Select value",isClearable:!1,"aria-label":`select ${t.id} value`,allowCustomValue:!0,isMulti:!0,allowCreateWhileLoading:!0}),f&&s.createElement(B.AccessoryButton,{variant:"secondary",icon:"times",onClick:()=>n?.(t),tooltip:"Remove tag","aria-label":`remove tag with ID ${t.id}`}))};var _t=l(66117);const Vt=()=>({vertical:m.css`
    display: flex;
    flex-direction: column;
    gap: 0.25rem;
  `,horizontal:m.css`
    display: flex;
    flex-direction: row;
    gap: 1rem;
  `}),Ye=({updateFilter:t,deleteFilter:e,filters:a,datasource:n,setError:r,tags:i,isTagsLoading:o,hideValues:c})=>{const d=(0,L.wW)(Vt),u=()=>(0,_t.Z)().slice(0,8),f=(0,s.useCallback)(()=>t({id:u(),operator:"=",scope:G.Span}),[t]);return(0,s.useEffect)(()=>{a?.length||f()},[a,f]),s.createElement("div",{className:d.vertical},a?.map((p,N)=>s.createElement("div",{className:d.horizontal,key:p.id},s.createElement(He,{filter:p,datasource:n,setError:r,updateFilter:t,tags:i,isTagsLoading:o,deleteFilter:e,allowDelete:!0,hideValue:c}),N===a.length-1&&s.createElement(B.AccessoryButton,{variant:"secondary",icon:"plus",onClick:f,title:"Add tag"}))))},kt=({datasource:t,query:e,onChange:a})=>{const n=(0,L.wW)(jt),[r,i]=(0,s.useState)(null),[o,c]=(0,s.useState)([]),[d,u]=(0,s.useState)(!0),[f,p]=(0,s.useState)(""),N=(0,s.useCallback)(b=>{const w={...e};w.filters||=[];const j=w.filters.findIndex(T=>T.id===b.id);j>=0?w.filters=Ve(w.filters,j,b):w.filters.push(b),a(w)},[a,e]),A=b=>{a({...e,filters:e.filters.filter(w=>w.id!==b.id)})};(0,s.useEffect)(()=>{p(We(e.filters||[]))},[e]);const O=(0,s.useCallback)(b=>e.filters?.find(w=>w.id===b),[e.filters]);(0,s.useEffect)(()=>{(async()=>{try{await t.languageProvider.start();const w=t.languageProvider.getTags();w&&(w.find(j=>j==="status")||w.push("status"),c(w),u(!1))}catch(w){w instanceof Error&&(0,ie.WI)((0,fe.$l)((0,ne.t_)("Error",w)))}})()},[t]),(0,s.useEffect)(()=>{t.search?.filters?.filter(b=>b.value).forEach(b=>{O(b.id)||N(b)})},[t.search?.filters,O,N]);const K=t.search?.filters?.map(b=>b.tag)||[];K.push("duration");const Z=[...J.intrinsics,...o].filter(b=>!K.includes(b)),H=(e.filters||[]).filter(b=>b.tag!=="duration"&&(t.search?.filters?.findIndex(w=>w.id===b.id)||0)===-1);return s.createElement(s.Fragment,null,s.createElement("div",{className:n.container},s.createElement("div",null,t.search?.filters?.map(b=>s.createElement(Le,{key:b.id,label:bt(b),tooltip:`Filter your search by ${xe(b)}. To modify the default filters shown for search visit the Tempo datasource configuration page.`},s.createElement(He,{filter:O(b.id)||b,datasource:t,setError:i,updateFilter:N,tags:[],hideScope:!0,hideTag:!0}))),s.createElement(Le,{label:"Duration",tooltip:"The span duration, i.e.	end - start time of the span. Accepted units are ns, ms, s, m, h"},s.createElement(F.Lh,{spacing:"sm"},s.createElement(Ze,{filter:O("min-duration")||{id:"min-duration",tag:"duration",operator:">",valueType:"duration"},operators:[">",">="],updateFilter:N}),s.createElement(Ze,{filter:O("max-duration")||{id:"max-duration",tag:"duration",operator:"<",valueType:"duration"},operators:["<","<="],updateFilter:N}))),s.createElement(Le,{label:"Tags"},s.createElement(Ye,{filters:H,datasource:t,setError:i,updateFilter:N,deleteFilter:A,tags:Z,isTagsLoading:d}))),s.createElement(B.EditorRow,null,s.createElement(lt.U,{query:f,lang:{grammar:$t,name:"traceql"}})),s.createElement(we,{onChange:a,query:e})),r?s.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 ",s.createElement("a",{href:`/datasources/edit/${t.uid}`},"datasource settings"),"."):null)},jt=t=>({alert:m.css`
    max-width: 75ch;
    margin-top: ${t.spacing(2)};
  `,container:m.css`
    display: flex;
    gap: 4px;
    flex-wrap: wrap;
    flex-direction: column;
  `}),Bt={};var zt=(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))(zt||{}),qe=l(73383);function Gt(t){const{onChange:e,onRunQuery:a,placeholder:n}=t,r=qt(t.datasource),i=(0,L.l4)(),o=Xt(i,n);return s.createElement(qe.p,{value:t.value,language:he,onBlur:e,onChange:e,containerStyles:o.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||(r(c,d,Ht(c)),Zt(c,d,a),Kt(c,d,o)),Yt(c)}})}function Kt(t,e,a){const n=[{range:new e.Range(1,1,1,1),options:{className:a.placeholder,isWholeLine:!0}}];let r=[];const i=()=>{const o=t.getModel();if(!o)return;const c=o.getValueLength()===0?n:[];r=o.deltaDecorations(r,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 r={datasourceType:"tempo",type:n};n!=="TAG_VALUE"&&(r.label=a),(0,M.ff)("grafana_traces_traceql_completion",r)})}function Yt(t){const e=t.getDomNode(),a=()=>{if(e){const n=Math.min(1e3,t.getContentHeight()),r=parseInt(e.style.width,10);e.style.width=`${r}px`,e.style.height=`${n}px`,t.layout({width:r,height:n})}};t.onDidContentSizeChange(a),a()}function qt(t){const e=(0,s.useRef)(new J({languageProvider:t.languageProvider}));(0,s.useEffect)(()=>{(async()=>{try{await t.languageProvider.start();const r=t.languageProvider.getTags();r&&(r.find(i=>i==="status")||r.push("status"),e.current.setTags(r))}catch(r){r instanceof Error&&(0,ie.WI)((0,fe.$l)((0,ne.t_)("Error",r)))}})()},[t]);const a=(0,s.useRef)(null);return(0,s.useEffect)(()=>()=>{a.current?.()},[]),(n,r,i)=>{e.current.editor=n,e.current.monaco=r,e.current.setRegisterInteractionCommandId(i);const{dispose:o}=r.languages.registerCompletionItemProvider(he,e.current);a.current=o}}let Je=!1;const he="traceql";function Jt(t){if(!Je){Je=!0;const{aliases:e,extensions:a,mimetypes:n,def:r}=Ot;t.languages.register({id:he,aliases:e,extensions:a,mimetypes:n}),t.languages.setMonarchTokensProvider(he,r.language),t.languages.setLanguageConfiguration(he,r.languageConfiguration)}}const Xt=(t,e)=>({queryField:m.css`
      border-radius: ${t.shape.borderRadius()};
      border: 1px solid ${t.components.input.borderColor};
      flex: 1;
    `,placeholder:m.css`
      ::after {
        content: '${e}';
        font-family: ${t.typography.fontFamilyMonospace};
        opacity: 0.3;
      }
    `});function ea(t){const e=(0,L.wW)(ta),a=(0,Y.defaults)(t.query,Bt),n=r=>{t.onChange({...a,query:r})};return s.createElement(s.Fragment,null,s.createElement(C.W,null,"Build complex queries using TraceQL to select a list of traces."," ",s.createElement("a",{rel:"noreferrer",target:"_blank",href:"https://grafana.com/docs/tempo/latest/traceql/"},"Documentation")),s.createElement(Gt,{placeholder:"Enter a TraceQL query or trace ID (run with Shift+Enter)",value:a.query,onChange:n,datasource:t.datasource,onRunQuery:t.onRunQuery}),s.createElement("div",{className:e.optionsContainer},s.createElement(we,{query:a,onChange:t.onChange})))}const ta=()=>({optionsContainer:m.css`
    margin-top: 10px;
  `});var Xe=l(10933),aa=l(7012),et=l(69531);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:r}=na(this.monaco,e,a),i=this.getSituation(e.getValue(),r);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=[],r=i=>`"${i.label}"`;return a.forEach(i=>{i?.label&&n.push({label:i.label,insertText:r(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),r=/(?<key>[^= ]+)(?<equals>=)?(?<value>([^ "]+)|"([^"]*)")?/,i=n.match(new RegExp(r,"g"));if(i?.length){const c=i[i.length-1].match(r);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),r=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:r}}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,r=ua(t.datasource),i=(0,L.l4)(),o=ga(i,n);return s.createElement(qe.p,{value:t.value,language:pe,onBlur:a,onChange:e,containerStyles:o.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)=>{r(c,d),la(c,d,o),ca(c)}})}function la(t,e,a){const n=[{range:new e.Range(1,1,1,1),options:{className:a.placeholder,isWholeLine:!0}}];let r=[];const i=()=>{const o=t.getModel();if(!o)return;const c=o.getValueLength()===0?n:[];r=o.deltaDecorations(r,c)};i(),t.onDidChangeModelContent(i)}function ca(t){const e=t.getDomNode(),a=()=>{if(e){const n=Math.min(1e3,t.getContentHeight()),r=parseInt(e.style.width,10);e.style.width=`${r}px`,e.style.height=`${n}px`,t.layout({width:r,height:n})}};t.onDidContentSizeChange(a),a()}function ua(t){const e=(0,s.useRef)(new ra({languageProvider:t.languageProvider}));(0,s.useEffect)(()=>{(async()=>{try{await t.languageProvider.start();const r=t.languageProvider.getTags();r&&(r.find(i=>i==="status.code")||r.push("status.code"),e.current.setTags(r))}catch(r){r instanceof Error&&(0,ie.WI)((0,fe.$l)((0,ne.t_)("Error",r)))}})()},[t]);const a=(0,s.useRef)(null);return(0,s.useEffect)(()=>()=>{a.current?.()},[]),(n,r)=>{e.current.editor=n,e.current.monaco=r;const{dispose:i}=r.languages.registerCompletionItemProvider(pe,e.current);a.current=i}}let tt=!1;const pe="tagsfield";function da(t){if(!tt){tt=!0;const{aliases:e,extensions:a,mimetypes:n,def:r}=ia;t.languages.register({id:pe,aliases:e,extensions:a,mimetypes:n}),t.languages.setMonarchTokensProvider(pe,r.language),t.languages.setLanguageConfiguration(pe,r.languageConfiguration)}}const ga=(t,e)=>({queryField:m.css`
      border-radius: ${t.shape.borderRadius()};
      border: 1px solid ${t.components.input.borderColor};
      flex: 1;
    `,placeholder:m.css`
      ::after {
        content: '${e}';
        font-family: ${t.typography.fontFamilyMonospace};
        opacity: 0.3;
      }
    `}),at="e.g. 1.2s, 100ms",ma=({datasource:t,query:e,onChange:a,onBlur:n,onRunQuery:r})=>{const i=(0,L.wW)(ha),o=(0,s.useMemo)(()=>new Ce(t),[t]),[c,d]=(0,s.useState)(),[u,f]=(0,s.useState)(),[p,N]=(0,s.useState)(null),[A,O]=(0,s.useState)({}),[K,Z]=(0,s.useState)({serviceName:!1,spanName:!1}),H=(0,s.useCallback)(async(T,$="")=>{const de=T==="serviceName"?"service.name":"name";Z(V=>({...V,[T]:!0}));try{return(await o.getOptionsV1(de)).filter(Se=>Se.value?(0,aa.C)(Se.value,$).found:!1)}catch(V){return(0,me.kW)(V)&&V?.status===404?N(V):V instanceof Error&&(0,ie.WI)((0,et.$l)((0,ne.t_)("Error",V))),[]}finally{Z(V=>({...V,[T]:!1}))}},[o]);(0,s.useEffect)(()=>{(async()=>{try{const[$,de]=await Promise.all([H("serviceName"),H("spanName")]);e.serviceName&&(0,ge.J)().containsTemplate(e.serviceName)&&$.push((0,Xe.E)(e.serviceName)),d($),e.spanName&&(0,ge.J)().containsTemplate(e.spanName)&&de.push((0,Xe.E)(e.spanName)),f(de)}catch($){(0,me.kW)($)&&$?.status===404?N($):$ instanceof Error&&(0,ie.WI)((0,et.$l)((0,ne.t_)("Error",$)))}})()},[o,H,e.serviceName,e.spanName]);const b=T=>{T.key==="Enter"&&(T.shiftKey||T.ctrlKey)&&r()},w=(0,s.useCallback)(T=>{a({...e,search:T})},[a,e]),j=(0,ge.J)();return s.createElement(s.Fragment,null,s.createElement("div",{className:i.container},s.createElement(g.Z,null,s.createElement(S._,{label:"Service Name",labelWidth:14,grow:!0},s.createElement(re.Ph,{inputId:"service",options:c,onOpenMenu:()=>{H("serviceName")},isLoading:K.serviceName,value:c?.find(T=>T?.value===e.serviceName)||e.serviceName,onChange:T=>{a({...e,serviceName:T?.value})},placeholder:"Select a service",isClearable:!0,onKeyDown:b,"aria-label":"select-service-name",allowCustomValue:!0}))),s.createElement(g.Z,null,s.createElement(S._,{label:"Span Name",labelWidth:14,grow:!0},s.createElement(re.Ph,{inputId:"spanName",options:u,onOpenMenu:()=>{H("spanName")},isLoading:K.spanName,value:u?.find(T=>T?.value===e.spanName)||e.spanName,onChange:T=>{a({...e,spanName:T?.value})},placeholder:"Select a span",isClearable:!0,onKeyDown:b,"aria-label":"select-span-name",allowCustomValue:!0}))),s.createElement(g.Z,null,s.createElement(S._,{label:"Tags",labelWidth:14,grow:!0,tooltip:"Values should be in logfmt."},s.createElement(oa,{placeholder:"http.status_code=200 error=true",value:e.search||"",onChange:w,onBlur:n,datasource:t}))),s.createElement(g.Z,null,s.createElement(S._,{label:"Min Duration",invalid:!!A.minDuration,labelWidth:14,grow:!0},s.createElement(ue.I,{id:"minDuration",value:e.minDuration||"",placeholder:at,onBlur:()=>{const T=j.replace(e.minDuration??"");e.minDuration&&!(0,ye.IA)(T)?O({...A,minDuration:!0}):O({...A,minDuration:!1})},onChange:T=>a({...e,minDuration:T.currentTarget.value}),onKeyDown:b}))),s.createElement(g.Z,null,s.createElement(S._,{label:"Max Duration",invalid:!!A.maxDuration,labelWidth:14,grow:!0},s.createElement(ue.I,{id:"maxDuration",value:e.maxDuration||"",placeholder:at,onBlur:()=>{const T=j.replace(e.maxDuration??"");e.maxDuration&&!(0,ye.IA)(T)?O({...A,maxDuration:!0}):O({...A,maxDuration:!1})},onChange:T=>a({...e,maxDuration:T.currentTarget.value}),onKeyDown:b}))),s.createElement(g.Z,null,s.createElement(S._,{label:"Limit",invalid:!!A.limit,labelWidth:14,grow:!0,tooltip:"Maximum number of returned results"},s.createElement(ue.I,{id:"limit",value:e.limit||"",placeholder:`Default: ${te}`,type:"number",onChange:T=>{let $=T.currentTarget.value?parseInt(T.currentTarget.value,10):void 0;$&&(!Number.isInteger($)||$<=0)?O({...A,limit:!0}):O({...A,limit:!1}),a({...e,limit:T.currentTarget.value?parseInt(T.currentTarget.value,10):void 0})},onKeyDown:b})))),p?s.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 ",s.createElement("a",{href:`/datasources/edit/${t.uid}`},"datasource settings"),"."):null)},ha=t=>({container:m.css`
    max-width: 500px;
  `,alert:m.css`
    max-width: 75ch;
    margin-top: ${t.spacing(2)};
  `});var pa=l(49794),rt=l(51031);async function st(t){if(!t)return;const e=(0,rt.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,L.wW)(ya),r=(0,x.Z)(()=>st(t),[t]),[i,o]=(0,s.useState)(void 0);if((0,s.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"]});o(Boolean(p.length))}!r.loading&&r.value&&u(r.value)},[r]),r.loading)return null;const c=r.value;if(!t)return s.createElement("div",{className:"text-warning"},"Please set up a service graph datasource in the datasource settings.");if(t&&!c)return s.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 s.createElement("div",null,s.createElement(g.Z,null,s.createElement(S._,{label:"Filter",labelWidth:14,grow:!0},s.createElement(pa.F,{datasource:{uid:t},filters:d,getTagKeysOptions:{series:["traces_service_graph_request_total","traces_spanmetrics_calls_total"]},addFilter:u=>{a({...e,serviceMapQuery:Pe([...d,u])})},removeFilter:u=>{const f=[...d];f.splice(u,1),a({...e,serviceMapQuery:Pe(f)})},changeFilter:(u,f)=>{const p=[...d];p.splice(u,1,f),a({...e,serviceMapQuery:Pe(p)})}}))),i===!1?s.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"," ",s.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 Pe(t){return`{${t.map(e=>`${e.key}${e.operator}"${e.value}"`).join(",")}}`}const ya=t=>({alert:m.css`
    max-width: 75ch;
    margin-top: ${t.spacing(2)};
  `}),Ea=D.v.featureToggles.traceqlSearch?"traceqlSearch":"traceql";class Ta extends s.PureComponent{constructor(e){super(e),this.onChangeLinkedQuery=a=>{const{query:n,onChange:r}=this.props;r({...n,linkedQuery:{...a,refId:"linked"}})},this.onRunLinkedQuery=()=>{this.props.onRunQuery()},this.onClearResults=()=>{const{onChange:a,query:n,onRunQuery:r}=this.props;a({...n,queryType:"clear"}),r()}}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:r}=this.props,i=n.getLokiSearchDS(),o=n.serviceMap?.datasourceUid;let c=[{value:"traceql",label:"TraceQL"},{value:"upload",label:"JSON File"},{value:"serviceMap",label:"Service Graph"}];return D.v.featureToggles.traceqlSearch&&c.unshift({value:"traceqlSearch",label:"Search"}),!D.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"})),s.createElement(s.Fragment,null,s.createElement(g.Z,null,s.createElement(S._,{label:"Query type"},s.createElement(E.S,{options:c,value:e.queryType,onChange:d=>{(0,M.ff)("grafana_traces_query_type_changed",{datasourceType:"tempo",app:r??"",grafana_version:D.v.buildInfo.version,newQueryType:d,previousQueryType:e.queryType??""}),this.onClearResults(),a({...e,queryType:d})},size:"md"}))),e.queryType==="search"&&s.createElement(Sa,{logsDatasourceUid:i,query:e,onRunQuery:this.onRunLinkedQuery,onChange:this.onChangeLinkedQuery}),e.queryType==="nativeSearch"&&s.createElement(ma,{datasource:this.props.datasource,query:e,onChange:a,onBlur:this.props.onBlur,onRunQuery:this.props.onRunQuery}),e.queryType==="traceqlSearch"&&s.createElement(kt,{datasource:this.props.datasource,query:e,onChange:a,onBlur:this.props.onBlur}),e.queryType==="upload"&&s.createElement("div",{className:(0,m.css)({padding:this.props.theme.spacing(2)})},s.createElement(h.Yo,{options:{multiple:!1},onLoad:d=>{this.props.datasource.uploadedJson=d,this.props.onRunQuery()}})),e.queryType==="serviceMap"&&s.createElement(fa,{graphDatasourceUid:o,query:e,onChange:a}),e.queryType==="traceql"&&s.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 r=(0,x.Z)(()=>st(t),[t]);if(r.loading)return null;const i=r.value;return i?s.createElement(s.Fragment,null,s.createElement(C.W,null,"Tempo uses ",i.name," to find traces."),s.createElement(Q.n,{datasource:i,onChange:e,onRunQuery:a,query:n.linkedQuery??{refId:"linked"},history:[]})):t?t&&!i?s.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:s.createElement("div",{className:"text-warning"},"Please set up a Loki search datasource in the datasource settings.")}const ba=(0,L.HE)(Ta);var Da=l(38210),xa=l(70340),Ca=l(27871),Na=l(58309),Ia=l(87825),Ma=l(99919),k=l(65820),nt=l(58526),it=l(48389);function wa({options:t,onOptionsChange:e}){const a=(0,L.wW)(La),n=t.jsonData.tracesToLogs?.lokiSearch!==!1?t.jsonData.tracesToLogs?.datasourceUid:void 0;return n&&t.jsonData.lokiSearch===void 0&&(0,k.tp)({onOptionsChange:e,options:t},"lokiSearch",{datasourceUid:n}),s.createElement("div",{className:(0,m.css)({width:"100%"})},s.createElement("h3",{className:"page-heading"},"Loki search"),s.createElement("div",{className:a.infoText},"Select a Loki data source to search for traces. Derived fields must be configured in the Loki data source."),s.createElement(g.Z,{className:a.row},s.createElement(S._,{tooltip:"The Loki data source with the service graph data",label:"Data source",labelWidth:26},s.createElement(nt.q,{inputId:"loki-search-data-source-picker",pluginId:"loki",current:t.jsonData.lokiSearch?.datasourceUid,noDefault:!0,width:40,onChange:r=>(0,k.tp)({onOptionsChange:e,options:t},"lokiSearch",{datasourceUid:r.uid})})),t.jsonData.lokiSearch?.datasourceUid?s.createElement(it.zx,{type:"button",variant:"secondary",size:"sm",fill:"text",onClick:()=>{(0,k.tp)({onOptionsChange:e,options:t},"lokiSearch",{datasourceUid:void 0})}},"Clear"):null))}const La=t=>({infoText:m.css`
    label: infoText;
    padding-bottom: ${t.spacing(2)};
    color: ${t.colors.text.secondary};
  `,row:m.css`
    label: row;
    align-items: baseline;
  `});var Re=l(57313);function Pa({options:t,onOptionsChange:e}){const a=(0,L.wW)(Ra);return s.createElement("div",{className:a.container},s.createElement("h3",{className:"page-heading"},"TraceID query"),s.createElement("div",{className:a.infoText},"Modify how TraceID queries are run. These settings do not apply to TraceQL queries."),s.createElement(S._,{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},s.createElement(Re.x,{id:"enable-time-shift",value:t.jsonData.traceQuery?.timeShiftEnabled||!1,onChange:n=>{(0,k.tp)({onOptionsChange:e,options:t},"traceQuery",{...t.jsonData.traceQuery,timeShiftEnabled:n.currentTarget.checked})}})),s.createElement(g.Z,null,s.createElement(S._,{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)"},s.createElement(ue.I,{type:"text",placeholder:"30m",width:40,onChange:n=>(0,k.tp)({onOptionsChange:e,options:t},"traceQuery",{...t.jsonData.traceQuery,spanStartTimeShift:n.currentTarget.value}),value:t.jsonData.traceQuery?.spanStartTimeShift||""}))),s.createElement(g.Z,null,s.createElement(S._,{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)"},s.createElement(ue.I,{type:"text",placeholder:"30m",width:40,onChange:n=>(0,k.tp)({onOptionsChange:e,options:t},"traceQuery",{...t.jsonData.traceQuery,spanEndTimeShift:n.currentTarget.value}),value:t.jsonData.traceQuery?.spanEndTimeShift||""}))))}const Ra=t=>({infoText:m.css`
    label: infoText;
    padding-bottom: ${t.spacing(2)};
    color: ${t.colors.text.secondary};
  `,container:m.css`
    label: container;
    width: 100%;
  `,row:m.css`
    label: row;
    align-items: baseline;
  `});function Aa({options:t,onOptionsChange:e}){return s.createElement("div",{className:ot.container},s.createElement("h3",{className:"page-heading"},"Tempo search"),s.createElement(g.Z,{className:ot.row},s.createElement(S._,{tooltip:"Removes the search tab from the query editor",label:"Hide search",labelWidth:26},s.createElement(Re.x,{id:"hideSearch",value:t.jsonData.search?.hide,onChange:a=>(0,k.tp)({onOptionsChange:e,options:t},"search",{...t.jsonData.search,hide:a.currentTarget.checked})}))))}const ot={container:m.css`
    label: container;
    width: 100%;
  `,row:m.css`
    label: row;
    align-items: baseline;
  `};function Qa({options:t,onOptionsChange:e}){const a=(0,L.wW)(Oa);return s.createElement("div",{className:(0,m.css)({width:"100%"})},s.createElement("h3",{className:"page-heading"},"Service graph"),s.createElement("div",{className:a.infoText},"Select a Prometheus data source that contains the service graph data."),s.createElement(g.Z,{className:a.row},s.createElement(S._,{tooltip:"The Prometheus data source with the service graph data",label:"Data source",labelWidth:26},s.createElement(nt.q,{inputId:"service-graph-data-source-picker",pluginId:"prometheus",current:t.jsonData.serviceMap?.datasourceUid,noDefault:!0,width:40,onChange:n=>(0,k.tp)({onOptionsChange:e,options:t},"serviceMap",{datasourceUid:n.uid})})),t.jsonData.serviceMap?.datasourceUid?s.createElement(it.zx,{type:"button",variant:"secondary",size:"sm",fill:"text",onClick:()=>{(0,k.tp)({onOptionsChange:e,options:t},"serviceMap",{datasourceUid:void 0})}},"Clear"):null))}const Oa=t=>({infoText:m.css`
    label: infoText;
    padding-bottom: ${t.spacing(2)};
    color: ${t.colors.text.secondary};
  `,row:m.css`
    label: row;
    align-items: baseline;
  `});function $a({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:r,loading:i,value:o}=(0,x.Z)(n,[a,t]),c=(0,s.useCallback)(u=>{let f=t.jsonData.search?.filters;f||=[];const p=f.findIndex(N=>N.id===u.id);p>=0?f=Ve(f,p,u):f.push(u),(0,k.tp)({onOptionsChange:e,options:t},"search",{...t.jsonData.search,filters:f})},[e,t]),d=u=>{(0,k.tp)({onOptionsChange:e,options:t},"search",{...t.jsonData.search,filters:t.jsonData.search?.filters?.filter(f=>f.id!==u.id)})};return(0,s.useEffect)(()=>{t.jsonData.search?.filters||(0,k.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]),s.createElement(s.Fragment,null,a?s.createElement(Ye,{updateFilter:c,deleteFilter:d,filters:t.jsonData.search?.filters||[],datasource:a,setError:()=>{},tags:[...J.intrinsics,...o||[]],isTagsLoading:i,hideValues:!0}):s.createElement("div",null,"Invalid data source, please create a valid data source and try again"),r&&s.createElement(W.b,{title:"Unable to fetch TraceQL tags",severity:"error",topSpacing:1},r.message))}function Ua({options:t,onOptionsChange:e}){const a=(0,rt.F)(),n=async()=>await a.get({type:t.type,uid:t.uid}),{value:r}=(0,x.Z)(n,[a,t]);return s.createElement("div",{className:Ae.container},s.createElement("h3",{className:"page-heading"},"Tempo search"),s.createElement(g.Z,{className:Ae.row},s.createElement(S._,{tooltip:"Removes the search tab from the query editor",label:"Hide search",labelWidth:26},s.createElement(Re.x,{id:"hideSearch",value:t.jsonData.search?.hide,onChange:i=>(0,k.tp)({onOptionsChange:e,options:t},"search",{...t.jsonData.search,hide:i.currentTarget.checked})}))),s.createElement(g.Z,{className:Ae.row},s.createElement(S._,{tooltip:"Configures which fields are available in the UI",label:"Static filters",labelWidth:26},s.createElement($a,{datasource:r,options:t,onOptionsChange:e}))))}const Ae={container:m.css`
    label: container;
    width: 100%;
  `,row:m.css`
    label: row;
    align-items: baseline;
  `},Fa=({options:t,onOptionsChange:e})=>s.createElement(s.Fragment,null,s.createElement(Da.E,{defaultUrl:"http://tempo",dataSourceConfig:t,showAccessOptions:!1,onChange:e}),D.v.featureToggles.secureSocksDatasourceProxy&&s.createElement(xa.i,{options:t,onOptionsChange:e}),s.createElement("div",{className:"gf-form-group"},s.createElement(Na.Z,{options:t,onOptionsChange:e})),D.v.featureToggles.traceToMetrics?s.createElement("div",{className:"gf-form-group"},s.createElement(Ia.F,{options:t,onOptionsChange:e})):null,s.createElement("div",{className:"gf-form-group"},s.createElement(Qa,{options:t,onOptionsChange:e})),s.createElement("div",{className:"gf-form-group"},s.createElement(Ca.n,{options:t,onOptionsChange:e})),s.createElement("div",{className:"gf-form-group"},D.v.featureToggles.traceqlSearch?s.createElement(Ua,{options:t,onOptionsChange:e}):s.createElement(Aa,{options:t,onOptionsChange:e})),s.createElement("div",{className:"gf-form-group"},s.createElement(wa,{options:t,onOptionsChange:e})),s.createElement("div",{className:"gf-form-group"},s.createElement(Pa,{options:t,onOptionsChange:e})),s.createElement("div",{className:"gf-form-group"},s.createElement(Ma.SpanBarSettings,{options:t,onOptionsChange:e})));var Wa=l(35630);const _a=({payload:{dashboardId:t,orgId:e,grafanaVersion:a,queries:n}})=>{try{const r=n[Wa.id];if(!r?.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 o of r)o.hide||(o.queryType==="nativeSearch"?(i.native_search_query_count++,(o.serviceName&&X(o.serviceName)||o.spanName&&X(o.spanName)||o.search&&X(o.search)||o.minDuration&&X(o.minDuration)||o.maxDuration&&X(o.maxDuration))&&i.native_search_queries_with_template_variables_count++):o.queryType==="search"?(i.search_query_count++,o.linkedQuery&&o.linkedQuery.expr&&X(o.linkedQuery.expr)&&i.search_queries_with_template_variables_count++):o.queryType==="serviceMap"?(i.service_map_query_count++,o.serviceMapQuery&&X(o.serviceMapQuery)&&i.service_map_queries_with_template_variables_count++):o.queryType==="traceql"?(i.traceql_query_count++,X(o.query)&&i.traceql_queries_with_template_variables_count++):o.queryType==="upload"&&i.upload_query_count++);(0,M.ff)("grafana_tempo_dashboard_loaded",i)}catch(r){console.error("error in tempo tracking handler",r)}},X=t=>(0,ge.J)().containsTemplate(t),Va=new y.hf(Dt).setQueryEditor(ba).setConfigEditor(Fa).setQueryEditorHelp(R);(0,P.N$)().subscribe(v.Pl,_a)}}]);

//# sourceMappingURL=5252.3eab6c505c2b3a53e311.js.map