"use strict";(self.webpackChunkgrafana=self.webpackChunkgrafana||[]).push([[5644],{90950:(se,U,l)=>{l.d(U,{n:()=>R});var y=l(9892),f=l(68404),P=l(5916),s=l(11543),M=l(81764),D=l(8944);function R({options:x,onOptionsChange:g}){return f.createElement("div",{className:m.container},f.createElement("h3",{className:"page-heading"},"Node graph"),f.createElement(s.Z,{className:m.row},f.createElement(M._,{tooltip:"Displays the node graph above the trace view. Default: disabled",label:"Enable node graph",labelWidth:26},f.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;
  `}},48288:(se,U,l)=>{l.d(U,{F:()=>S});var y=l(9892),f=l(68404),P=l(5916),s=l(53117),M=l(72648),D=l(11543),R=l(81764),m=l(31403),x=l(46967),g=l(33045);function S({options:h,onOptionsChange:C}){const L=(0,M.wW)(E);return f.createElement("div",{className:(0,y.css)({width:"100%"})},f.createElement("h3",{className:"page-heading"},"Trace to metrics"),f.createElement("div",{className:L.infoText},"Navigate from a trace span to the selected data source's metrics."),f.createElement(D.Z,{className:L.row},f.createElement(R._,{tooltip:"The Prometheus data source the trace is going to navigate to",label:"Data source",labelWidth:26},f.createElement(s.q,{inputId:"trace-to-metrics-data-source-picker",pluginId:"prometheus",current:h.jsonData.tracesToMetrics?.datasourceUid,noDefault:!0,width:40,onChange:A=>(0,P.tp)({onOptionsChange:C,options:h},"tracesToMetrics",{...h.jsonData.tracesToMetrics,datasourceUid:A.uid})})),h.jsonData.tracesToMetrics?.datasourceUid?f.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),f.createElement(D.Z,null,f.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)"},f.createElement(x.I,{type:"text",placeholder:"0",width:40,onChange:A=>(0,P.tp)({onOptionsChange:C,options:h},"tracesToMetrics",{...h.jsonData.tracesToMetrics,spanStartTimeShift:A.currentTarget.value}),value:h.jsonData.tracesToMetrics?.spanStartTimeShift||""}))),f.createElement(D.Z,null,f.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)"},f.createElement(x.I,{type:"text",placeholder:"0",width:40,onChange:A=>(0,P.tp)({onOptionsChange:C,options:h},"tracesToMetrics",{...h.jsonData.tracesToMetrics,spanEndTimeShift:A.currentTarget.value}),value:h.jsonData.tracesToMetrics?.spanEndTimeShift||""}))),f.createElement(D.Z,null,f.createElement(R._,{tooltip:"Tags that will be used in the metrics query",label:"Tags",labelWidth:26},f.createElement(g.a,{values:h.jsonData.tracesToMetrics?.tags??[],onChange:A=>(0,P.tp)({onOptionsChange:C,options:h},"tracesToMetrics",{...h.jsonData.tracesToMetrics,tags:A})}))),h.jsonData.tracesToMetrics?.queries?.map((A,j)=>f.createElement("div",{key:j,className:L.queryRow},f.createElement(R._,{label:"Link Label",labelWidth:26,tooltip:"Descriptive label for the linked query"},f.createElement(x.I,{label:"Link Label",type:"text",allowFullScreen:!0,value:A.name,width:40,onChange:F=>{let W=h.jsonData.tracesToMetrics?.queries.slice()??[];W[j].name=F.currentTarget.value,(0,P.tp)({onOptionsChange:C,options:h},"tracesToMetrics",{...h.jsonData.tracesToMetrics,queries:W})}})),f.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},f.createElement(x.I,{label:"Query",type:"text",allowFullScreen:!0,value:A.query,onChange:F=>{let W=h.jsonData.tracesToMetrics?.queries.slice()??[];W[j].query=F.currentTarget.value,(0,P.tp)({onOptionsChange:C,options:h},"tracesToMetrics",{...h.jsonData.tracesToMetrics,queries:W})}})),f.createElement(m.zx,{variant:"destructive",title:"Remove query",icon:"times",type:"button",onClick:()=>{let F=h.jsonData.tracesToMetrics?.queries.slice();F?.splice(j,1),(0,P.tp)({onOptionsChange:C,options:h},"tracesToMetrics",{...h.jsonData.tracesToMetrics,queries:F})}}))),f.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;
  `})},91159:(se,U,l)=>{l.d(U,{n:()=>D});var y=l(68404),f=l(31439);const P=y.lazy(()=>Promise.all([l.e(1899),l.e(4254),l.e(924),l.e(9305),l.e(7142)]).then(l.bind(l,47864))),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,f.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)}}},31439:(se,U,l)=>{l.d(U,{Hk:()=>x,U9:()=>D,_z:()=>g,aC:()=>S,iS:()=>R,rf:()=>P,tU:()=>m});function y(E){return f(E/1e3)}function f(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)}},38435:(se,U,l)=>{l.d(U,{d:()=>m});var y=l(9892),f=l(68404),P=l(86253),s=l(20112),M=l(26418),D=l(72648),R=l(39904);function m({title:g,children:S,collapsedInfo:E,queryStats:h}){const[C,L]=(0,P.Z)(!1),A=(0,D.wW)(x),j=()=>{const{text:F,suffix:W}=(0,s.Cf)("bytes")(h.bytes,1);return F+W};return f.createElement("div",{className:A.wrapper},f.createElement(M.Stack,{gap:0,direction:"column"},f.createElement("div",{className:A.header,onClick:L,title:"Click to edit options"},f.createElement("div",{className:A.toggle},f.createElement(R.J,{name:C?"angle-down":"angle-right"})),f.createElement("h6",{className:A.title},g),!C&&f.createElement("div",{className:A.description},E.map((F,W)=>f.createElement("span",{key:W},F)))),C&&f.createElement("div",{className:A.body},S)),h&&f.createElement("p",{className:A.stats},"This query will process approximately ",j(),"."))}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})})},45204:(se,U,l)=>{l.d(U,{U:()=>D});var y=l(9892),f=l(57706),P=l.n(f),s=l(68404),M=l(72648);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})})},25644:(se,U,l)=>{l.r(U),l.d(U,{plugin:()=>Wa});var y=l(7238),f=l(55294),P=l(82378),s=l(68404),M=l(41818),D=l(35645);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(9892),x=l(50700),g=l(11543),S=l(81764),E=l(2594),h=l(30784),C=l(77117),L=l(72648),A=l(91159),j=l(26418),F=l(52081),W=l(45253),ne=l(60499),fe=l(98864),ie=l(3153),lt=l(45204),ct=l(68668),ut=l(38435),Y=l(82897),z=l(59980),Qe=l(49372),dt=l(85850),gt=l(12877),mt=l(7523),Oe=l(65583),$e=l(39859),q=l(9471),be=l(59724),Ue=l(86870),De=l(76997),ee=l(49922),Fe=l(33180),ve=l(46519),ye=l(37556),ht=l(14582),pt=l(22069),ge=l(20308),me=l(54899),Ee=l(40538),ft=l(8878),Te=l(91162);const _a=Object.freeze([0,0]),Va={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}=yt(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,v)=>{const p={kind:vt(u.type,this.monaco),label:u.label,insertText:u.insertText,sortText:v.toString().padStart(c,"0"),range:a,command:{id:this.registerInteractionCommandId||"noOp",title:"Report Interaction",arguments:[u.label,u.type]}};return Et(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 vt(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 yt(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 Et(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}${Tt(e)}`).join(" && ")}}`,Tt=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,St=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(69407);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(45331);const te=20;class bt extends pt.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)},v=c.instanceSettings.jsonData.derivedFields?.filter(p=>p.datasourceUid===this.uid&&p.matcherRegex).map(p=>p.matcherRegex)||[];return!v||v.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,v)))})))}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(Dt(e,o,c).pipe((0,Ue.b)(d=>xt(e,d,o).pipe((0,Ue.b)(u=>Ct(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,ft.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 Ie(t,e){return(0,Qe.D)((0,Te.ak)().get(e)).pipe((0,$e.z)(a=>a.query(t)))}function Dt(t,e,a){const n=Ne(t);return Ie(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=Be(e,a,"__data.fields.id","__data.fields[0]"),c.fields[0].config=Be(e,a,"__data.fields.target","__data.fields.target","__data.fields.source"),{data:[o,c],state:ee.Gu.Done}}))}function xt(t,e,a){const n=Ne(t);return n.targets=Ge([ae(_.rB,_.T1,t)]),Ie(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 Ct(t,e,a,n){let r=[],i="",o=[];const c=e.data[0][0]?.fields[1]?.values.toArray()??[];c.length>0&&(i=ae(_.$C,'span_name=~"'+c.join("|")+'"',t),r.push(i),c.map(u=>{const v=ae(_.vO,'span_name=~"'+u+'"',t);o.push(v),r.push(v)}));const d=Ne(t);return d.targets=Ge(r),Ie(d,a).pipe((0,De.q)(),(0,q.U)(u=>{const v=u.find(N=>!!N.error);if(v)throw new Error(v.error.message);const p=It(t,e,u[0],i,o,a,n);return p.fields.length===0?{data:[e.data[1],e.data[2]],state:ee.Gu.Done}:{data:[p,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 Be(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),je("View traces",`\${${n}}`,"",e)]}}function je(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 Ne(t){return{...t,targets:_.t3.map(e=>({format:"table",refId:e,expr:`rate(${e}${t.targets[0].serviceMapQuery||""}[$__range])`,instant:!0}))}}function It(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),v=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 O={};p.map((K,Z)=>{O[K]={value:N[Z]}});const Q=ze({...d},O);c.fields.push({...u[0].fields[2],name:"Error Rate",values:Q,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:Q,labels:null,config:{color:{mode:"continuous-RdYlGr"},custom:{cellOptions:{mode:Ee.QH.Lcd,type:Ee.h2.Gauge}},decimals:3}})}if(v.length>0&&v[0].fields?.length>1){let p={};v.map(N=>{const O=N.refId?.includes('span_name=~"')?'span_name=~"':'span_name="',Q=N.refId?.split(O)[1].split('"}')[0];p[Q]={value:N.fields[1].values.toArray()[0]}}),c.fields.push({...v[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:ht.fS.string,values:c.fields[0].values.map(()=>"Tempo"),config:{links:[je("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(j.EditorRow,null,s.createElement(ut.d,{title:"Options",collapsedInfo:[`Limit: ${e.limit||te}`]},s.createElement(j.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 Nt={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=["=","!=",">","<",">=","<=","=~"],Mt=["=","!=","=~"],wt=["=","!=",">","<",">=","<="],Lt=["duration","name","status","parent"],Pt=["resource","span"],Rt={ignoreCase:!1,defaultToken:"",tokenPostfix:".traceql",keywords:Lt.concat(Pt),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"]]}},At={id:"traceql",extensions:[".traceql"],aliases:["tempo","traceql"],mimetypes:[],def:{language:Rt,languageConfiguration:Nt}},Qt={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(53217),ue=l(46967);const Ot=/^\d+(?:\.\d)?\d*(?:us|µs|ns|ms|s|m|h)$/,$t=()=>({noBoxShadow:m.css`
    box-shadow: none;
    *:focus {
      box-shadow: none;
    }
  `}),Ze=({filter:t,operators:e,updateFilter:a})=>{const n=(0,L.wW)($t);let r=!1;return typeof t.value=="string"&&(r=t.value?!Ot.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)),Ut=()=>({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:v})=>{const p=(0,L.wW)(Ut),N=(0,s.useMemo)(()=>new Ce(e),[e]),O=(0,s.useMemo)(()=>xe(t),[t]),[Q,K]=(0,s.useState)(t.operator),[Z,H]=(0,s.useState)(t.value),b=async()=>{try{return await N.getOptionsV2(O)}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:B}=(0,x.Z)(b,[O,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:Q,value:t.value[0]})},[Z,Q,a,t]),(0,s.useEffect)(()=>{H(t.value)},[t.value]);const T=Object.values(G).map(I=>({label:I,value:I})),$=B?.filter(I=>I.type===B[0]?.type),de=B?.length===$?.length?B?.[0]?.type:void 0;let V=Ke;switch(de){case"string":V=Mt;break;case"int":case"float":V=wt}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:B,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}),v&&s.createElement(j.AccessoryButton,{variant:"secondary",icon:"times",onClick:()=>n?.(t),tooltip:"Remove tag","aria-label":`remove tag with ID ${t.id}`}))};var Ft=l(44288);const Wt=()=>({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)(Wt),u=()=>(0,Ft.Z)().slice(0,8),v=(0,s.useCallback)(()=>t({id:u(),operator:"=",scope:G.Span}),[t]);return(0,s.useEffect)(()=>{a?.length||v()},[a,v]),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(j.AccessoryButton,{variant:"secondary",icon:"plus",onClick:v,title:"Add tag"}))))},_t=({datasource:t,query:e,onChange:a})=>{const n=(0,L.wW)(Vt),[r,i]=(0,s.useState)(null),[o,c]=(0,s.useState)([]),[d,u]=(0,s.useState)(!0),[v,p]=(0,s.useState)(""),N=(0,s.useCallback)(b=>{const w={...e};w.filters||=[];const B=w.filters.findIndex(T=>T.id===b.id);B>=0?w.filters=Ve(w.filters,B,b):w.filters.push(b),a(w)},[a,e]),O=b=>{a({...e,filters:e.filters.filter(w=>w.id!==b.id)})};(0,s.useEffect)(()=>{p(We(e.filters||[]))},[e]);const Q=(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(B=>B==="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=>{Q(b.id)||N(b)})},[t.search?.filters,Q,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:St(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:Q(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:Q("min-duration")||{id:"min-duration",tag:"duration",operator:">",valueType:"duration"},operators:[">",">="],updateFilter:N}),s.createElement(Ze,{filter:Q("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:O,tags:Z,isTagsLoading:d}))),s.createElement(j.EditorRow,null,s.createElement(lt.U,{query:v,lang:{grammar:Qt,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)},Vt=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;
  `}),kt={};var Bt=(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))(Bt||{}),qe=l(9405);function jt(t){const{onChange:e,onRunQuery:a,placeholder:n}=t,r=Ht(t.datasource),i=(0,L.l4)(),o=qt(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:Yt,onEditorDidMount:(c,d)=>{t.readOnly||(r(c,d,Kt(c)),Gt(c,d,a),zt(c,d,o)),Zt(c)}})}function zt(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 Gt(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 Kt(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 Zt(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 Ht(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 Yt(t){if(!Je){Je=!0;const{aliases:e,extensions:a,mimetypes:n,def:r}=At;t.languages.register({id:he,aliases:e,extensions:a,mimetypes:n}),t.languages.setMonarchTokensProvider(he,r.language),t.languages.setLanguageConfiguration(he,r.languageConfiguration)}}const qt=(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 Jt(t){const e=(0,L.wW)(Xt),a=(0,Y.defaults)(t.query,kt),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(jt,{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 Xt=()=>({optionsContainer:m.css`
    margin-top: 10px;
  `});var Xe=l(63134),ea=l(27303),et=l(659);class ta{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}=ra(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((v,p)=>({kind:aa(v.type,this.monaco),label:v.label,insertText:v.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 aa(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 ra(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 sa={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 na(t){const{onChange:e,onBlur:a,placeholder:n}=t,r=la(t.datasource),i=(0,L.l4)(),o=ua(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:ca,onEditorDidMount:(c,d)=>{r(c,d),ia(c,d,o),oa(c)}})}function ia(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 oa(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 la(t){const e=(0,s.useRef)(new ta({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 ca(t){if(!tt){tt=!0;const{aliases:e,extensions:a,mimetypes:n,def:r}=sa;t.languages.register({id:pe,aliases:e,extensions:a,mimetypes:n}),t.languages.setMonarchTokensProvider(pe,r.language),t.languages.setLanguageConfiguration(pe,r.languageConfiguration)}}const ua=(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",da=({datasource:t,query:e,onChange:a,onBlur:n,onRunQuery:r})=>{const i=(0,L.wW)(ga),o=(0,s.useMemo)(()=>new Ce(t),[t]),[c,d]=(0,s.useState)(),[u,v]=(0,s.useState)(),[p,N]=(0,s.useState)(null),[O,Q]=(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,ea.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)),v(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]),B=(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(na,{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:!!O.minDuration,labelWidth:14,grow:!0},s.createElement(ue.I,{id:"minDuration",value:e.minDuration||"",placeholder:at,onBlur:()=>{const T=B.replace(e.minDuration??"");e.minDuration&&!(0,ye.IA)(T)?Q({...O,minDuration:!0}):Q({...O,minDuration:!1})},onChange:T=>a({...e,minDuration:T.currentTarget.value}),onKeyDown:b}))),s.createElement(g.Z,null,s.createElement(S._,{label:"Max Duration",invalid:!!O.maxDuration,labelWidth:14,grow:!0},s.createElement(ue.I,{id:"maxDuration",value:e.maxDuration||"",placeholder:at,onBlur:()=>{const T=B.replace(e.maxDuration??"");e.maxDuration&&!(0,ye.IA)(T)?Q({...O,maxDuration:!0}):Q({...O,maxDuration:!1})},onChange:T=>a({...e,maxDuration:T.currentTarget.value}),onKeyDown:b}))),s.createElement(g.Z,null,s.createElement(S._,{label:"Limit",invalid:!!O.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)?Q({...O,limit:!0}):Q({...O,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)},ga=t=>({container:m.css`
    max-width: 500px;
  `,alert:m.css`
    max-width: 75ch;
    margin-top: ${t.spacing(2)};
  `});var ma=l(44847),rt=l(86647);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 ha({graphDatasourceUid:t,query:e,onChange:a}){const n=(0,L.wW)(fa),r=(0,x.Z)(()=>st(t),[t]),[i,o]=(0,s.useState)(void 0);if((0,s.useEffect)(()=>{async function u(v){const p=await v.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=pa(e.serviceMapQuery||"");return s.createElement("div",null,s.createElement(g.Z,null,s.createElement(S._,{label:"Filter",labelWidth:14,grow:!0},s.createElement(ma.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 v=[...d];v.splice(u,1),a({...e,serviceMapQuery:Pe(v)})},changeFilter:(u,v)=>{const p=[...d];p.splice(u,1,v),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 pa(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 fa=t=>({alert:m.css`
    max-width: 75ch;
    margin-top: ${t.spacing(2)};
  `}),va=D.v.featureToggles.traceqlSearch?"traceqlSearch":"traceql";class ya 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:va})}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(Ea,{logsDatasourceUid:i,query:e,onRunQuery:this.onRunLinkedQuery,onChange:this.onChangeLinkedQuery}),e.queryType==="nativeSearch"&&s.createElement(da,{datasource:this.props.datasource,query:e,onChange:a,onBlur:this.props.onBlur,onRunQuery:this.props.onRunQuery}),e.queryType==="traceqlSearch"&&s.createElement(_t,{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(ha,{graphDatasourceUid:o,query:e,onChange:a}),e.queryType==="traceql"&&s.createElement(Jt,{datasource:this.props.datasource,query:e,onRunQuery:this.props.onRunQuery,onChange:a}))}}function Ea({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(A.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 Ta=(0,L.HE)(ya);var Sa=l(12006),ba=l(12580),Da=l(90950),xa=l(83437),Ca=l(48288),Ia=l(61966),k=l(5916),nt=l(53117),it=l(31403);function Na({options:t,onOptionsChange:e}){const a=(0,L.wW)(Ma),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 Ma=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(8944);function wa({options:t,onOptionsChange:e}){const a=(0,L.wW)(La);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 La=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 Pa({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 Ra({options:t,onOptionsChange:e}){const a=(0,L.wW)(Aa);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 Aa=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 Qa({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(v=>v==="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 v=t.jsonData.search?.filters;v||=[];const p=v.findIndex(N=>N.id===u.id);p>=0?v=Ve(v,p,u):v.push(u),(0,k.tp)({onOptionsChange:e,options:t},"search",{...t.jsonData.search,filters:v})},[e,t]),d=u=>{(0,k.tp)({onOptionsChange:e,options:t},"search",{...t.jsonData.search,filters:t.jsonData.search?.filters?.filter(v=>v.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 Oa({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(Qa,{datasource:r,options:t,onOptionsChange:e}))))}const Ae={container:m.css`
    label: container;
    width: 100%;
  `,row:m.css`
    label: row;
    align-items: baseline;
  `},$a=({options:t,onOptionsChange:e})=>s.createElement(s.Fragment,null,s.createElement(Sa.E,{defaultUrl:"http://tempo",dataSourceConfig:t,showAccessOptions:!1,onChange:e}),D.v.featureToggles.secureSocksDatasourceProxy&&s.createElement(ba.i,{options:t,onOptionsChange:e}),s.createElement("div",{className:"gf-form-group"},s.createElement(xa.Z,{options:t,onOptionsChange:e})),D.v.featureToggles.traceToMetrics?s.createElement("div",{className:"gf-form-group"},s.createElement(Ca.F,{options:t,onOptionsChange:e})):null,s.createElement("div",{className:"gf-form-group"},s.createElement(Ra,{options:t,onOptionsChange:e})),s.createElement("div",{className:"gf-form-group"},s.createElement(Da.n,{options:t,onOptionsChange:e})),s.createElement("div",{className:"gf-form-group"},D.v.featureToggles.traceqlSearch?s.createElement(Oa,{options:t,onOptionsChange:e}):s.createElement(Pa,{options:t,onOptionsChange:e})),s.createElement("div",{className:"gf-form-group"},s.createElement(Na,{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(Ia.SpanBarSettings,{options:t,onOptionsChange:e})));var Ua=l(35630);const Fa=({payload:{dashboardId:t,orgId:e,grafanaVersion:a,queries:n}})=>{try{const r=n[Ua.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),Wa=new y.hf(bt).setQueryEditor(Ta).setConfigEditor($a).setQueryEditorHelp(R);(0,P.N$)().subscribe(f.Pl,Fa)}}]);

//# sourceMappingURL=5644.376542d01ebd29e4e781.js.map