"use strict";(self.webpackChunkgrafana=self.webpackChunkgrafana||[]).push([[7963],{5562:(oe,U,i)=>{i.d(U,{i:()=>r});var y=i(42844),h=i(27702),L=i(66310);const r=({hideLine:T=!1})=>{const N=(0,L.wW)(M);return T?h.createElement("hr",{className:N.dividerHideLine}):h.createElement("hr",{className:N.divider})},M=T=>({divider:(0,y.css)`
    margin: ${T.spacing(4,0)};
  `,dividerHideLine:(0,y.css)`
    border: none;
    margin: ${T.spacing(3,0)};
  `})},29126:(oe,U,i)=>{i.d(U,{I:()=>x});var y=i(42844),h=i(27702),L=i(17312),r=i(78102),M=i(66310),T=i(71107),N=i(48024),v=i(42074),$=i(47449);function R({options:f,onOptionsChange:C}){const B=(0,M.wW)(p);return h.createElement("div",{className:B.container},h.createElement(T.Z,{className:B.row},h.createElement(N._,{tooltip:"Displays the node graph above the trace view. Default: disabled",label:"Enable node graph",labelWidth:26},h.createElement(v.x,{id:"enableNodeGraph",value:f.jsonData.nodeGraph?.enabled,onChange:w=>(0,L.tp)({onOptionsChange:C,options:f},"nodeGraph",{...f.jsonData.nodeGraph,enabled:w.currentTarget.checked})}))))}const x=({options:f,onOptionsChange:C})=>h.createElement(r._,{title:"Node graph",description:h.createElement($.W,{description:"Show or hide the node graph visualization.",suffix:`${f.type}/#node-graph`,feature:"the node graph"})},h.createElement(R,{options:f,onOptionsChange:C})),p=f=>({infoText:(0,y.css)`
    label: infoText;
    padding-bottom: ${f.spacing(2)};
    color: ${f.colors.text.secondary};
  `,container:(0,y.css)`
    label: container;
    width: 100%;
  `,row:(0,y.css)`
    label: row;
    align-items: baseline;
  `})},35977:(oe,U,i)=>{i.d(U,{Y:()=>w});var y=i(42844),h=i(27702),L=i(17312),r=i(19010),M=i(66310),T=i(71107),N=i(48024),v=i(66670),$=i(1128),R=i(53229),x=i(47449),p=i(71654),f=i(19059),C=i(51778);function B({options:E,onOptionsChange:Q}){const le=(0,M.wW)(Z);return h.createElement("div",{className:(0,y.css)({width:"100%"})},h.createElement(T.Z,{className:le.row},h.createElement(N._,{tooltip:"The Prometheus data source the trace is going to navigate to",label:"Data source",labelWidth:26},h.createElement(R.q,{inputId:"trace-to-metrics-data-source-picker",pluginId:"prometheus",current:E.jsonData.tracesToMetrics?.datasourceUid,noDefault:!0,width:40,onChange:A=>(0,L.tp)({onOptionsChange:Q,options:E},"tracesToMetrics",{...E.jsonData.tracesToMetrics,datasourceUid:A.uid})})),E.jsonData.tracesToMetrics?.datasourceUid?h.createElement(v.zx,{type:"button",variant:"secondary",size:"sm",fill:"text",onClick:()=>{(0,L.tp)({onOptionsChange:Q,options:E},"tracesToMetrics",{...E.jsonData.tracesToMetrics,datasourceUid:void 0})}},"Clear"):null),h.createElement(T.Z,null,h.createElement(p.w,{label:(0,C.mH)("start"),tooltip:(0,C.rr)("start"),value:E.jsonData.tracesToMetrics?.spanStartTimeShift||"",onChange:A=>{(0,L.tp)({onOptionsChange:Q,options:E},"tracesToMetrics",{...E.jsonData.tracesToMetrics,spanStartTimeShift:A})},isInvalidError:C.Ny})),h.createElement(T.Z,null,h.createElement(p.w,{label:(0,C.mH)("end"),tooltip:(0,C.rr)("end"),value:E.jsonData.tracesToMetrics?.spanEndTimeShift||"",onChange:A=>{(0,L.tp)({onOptionsChange:Q,options:E},"tracesToMetrics",{...E.jsonData.tracesToMetrics,spanEndTimeShift:A})},isInvalidError:C.Ny})),h.createElement(T.Z,null,h.createElement(N._,{tooltip:"Tags that will be used in the metrics query",label:"Tags",labelWidth:26},h.createElement(f.a,{values:E.jsonData.tracesToMetrics?.tags??[],onChange:A=>(0,L.tp)({onOptionsChange:Q,options:E},"tracesToMetrics",{...E.jsonData.tracesToMetrics,tags:A})}))),E.jsonData.tracesToMetrics?.queries?.map((A,z)=>h.createElement("div",{key:z,className:le.queryRow},h.createElement(N._,{label:"Link Label",labelWidth:26,tooltip:"Descriptive label for the linked query"},h.createElement($.I,{label:"Link Label",type:"text",allowFullScreen:!0,value:A.name,width:40,onChange:ee=>{let te=E.jsonData.tracesToMetrics?.queries.slice()??[];te[z].name=ee.currentTarget.value,(0,L.tp)({onOptionsChange:Q,options:E},"tracesToMetrics",{...E.jsonData.tracesToMetrics,queries:te})}})),h.createElement(N._,{label:"Query",labelWidth:10,tooltip:"The Prometheus query that will run when navigating from a trace to metrics. Interpolate tags using the `$__tags` keyword",grow:!0},h.createElement($.I,{label:"Query",type:"text",allowFullScreen:!0,value:A.query,onChange:ee=>{let te=E.jsonData.tracesToMetrics?.queries.slice()??[];te[z].query=ee.currentTarget.value,(0,L.tp)({onOptionsChange:Q,options:E},"tracesToMetrics",{...E.jsonData.tracesToMetrics,queries:te})}})),h.createElement(v.zx,{variant:"destructive",title:"Remove query",icon:"times",type:"button",onClick:()=>{let ee=E.jsonData.tracesToMetrics?.queries.slice();ee?.splice(z,1),(0,L.tp)({onOptionsChange:Q,options:E},"tracesToMetrics",{...E.jsonData.tracesToMetrics,queries:ee})}}))),h.createElement(v.zx,{variant:"secondary",title:"Add query",icon:"plus",type:"button",onClick:()=>{(0,L.tp)({onOptionsChange:Q,options:E},"tracesToMetrics",{...E.jsonData.tracesToMetrics,queries:[...E.jsonData.tracesToMetrics?.queries??[],{query:""}]})}},"Add query"))}const w=({options:E,onOptionsChange:Q})=>h.createElement(r.K,{title:"Trace to metrics",description:h.createElement(x.W,{description:"Navigate from a trace span to the selected data source's metrics.",suffix:`${E.type}/#trace-to-metrics`,feature:"trace to metrics"}),isCollapsible:!0,isInitiallyOpen:!0},h.createElement(B,{options:E,onOptionsChange:Q})),Z=E=>({infoText:(0,y.css)`
    padding-bottom: ${E.spacing(2)};
    color: ${E.colors.text.secondary};
  `,row:(0,y.css)`
    label: row;
    align-items: baseline;
  `,queryRow:(0,y.css)`
    label: queryRow;
    display: flex;
    flex-flow: wrap;
  `})},83392:(oe,U,i)=>{i.d(U,{n:()=>T});var y=i(27702),h=i(64826);const L=y.lazy(()=>Promise.all([i.e(3565),i.e(7142)]).then(i.bind(i,11742))),r=N=>y.createElement(y.Suspense,{fallback:null},y.createElement(L,{...N})),M=N=>{const v=(0,y.useRef)(null),{onRunQuery:$,onChange:R,...x}=N,p=C=>{v.current=C,R(C),$()},f=C=>{R(C)};return y.createElement(r,{onRunQuery:p,onBlur:f,...x})};class T extends y.PureComponent{constructor(v){super(v),this._isMounted=!1,this.onChangeQuery=($,R)=>{const{query:x,onChange:p,onRunQuery:f}=this.props;if(p){const C={...x,expr:$};p(C),R&&f&&f()}},this.state={labelsLoaded:!1}}async componentDidMount(){this._isMounted=!0,await this.props.datasource.languageProvider.start(),this._isMounted&&this.setState({labelsLoaded:!0})}componentWillUnmount(){this._isMounted=!1}componentDidUpdate(v){const{range:$,datasource:{languageProvider:R}}=this.props;(0,h.rf)($,v.range)&&R.fetchLabels()}render(){const{ExtraFieldElement:v,query:$,datasource:R,history:x,onRunQuery:p,onQueryType:f}=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--grow flex-shrink-1 min-width-15"},y.createElement(M,{datasource:R,history:x??[],onChange:this.onChangeQuery,onRunQuery:p,initialValue:$.expr??"",placeholder:C,onQueryType:f}))),v)}}},64826:(oe,U,i)=>{i.d(U,{Hk:()=>$,U9:()=>T,_z:()=>R,aC:()=>x,iS:()=>N,rf:()=>L,tU:()=>v});function y(p){return h(p/1e3)}function h(p){return Math.floor(p/60)}function L(p,f){if(p&&f){const C=y(p.from.valueOf())===y(f.from.valueOf()),B=y(p.to.valueOf())===y(f.to.valueOf());return!(C&&B)}return!1}const r=/[*+?()|\\.\[\]{}^$]/g;function M(p){return p.replace(r,"\\$&")}function T(p){return p.replace(/\\/g,"\\\\").replace(/\n/g,"\\n").replace(/"/g,'\\"')}function N(p){return p.replace(/\\n/g,`
`).replace(/\\"/g,'"').replace(/\\\\/g,"\\")}function v(p){return T(M(p))}function $(p,f){return R(f)?v(p):T(p)}function R(p){return!!(p&&(p.includes("=~")||p.includes("!~")))}function x(p){const f=["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+)?)(?:${f.join("|")})$`);return!!p.match(C)}},85187:(oe,U,i)=>{i.d(U,{d:()=>x});var y=i(42844),h=i(27702),L=i(73195),r=i(21609),M=i(23852),T=i(34667),N=i(66310),v=i(41640),$=i(80011),R=i(73453);function x({title:f,children:C,collapsedInfo:B,queryStats:w}){const[Z,E]=(0,L.Z)(!1),Q=(0,N.wW)(p),le=()=>{const{text:A,suffix:z}=(0,r.Cf)("bytes")(w.bytes,1);return A+z};return h.createElement("div",{className:Q.wrapper},h.createElement(v.U,{className:Q.collapse,collapsible:!0,isOpen:Z,onToggle:E,label:h.createElement(M.K,{gap:0,wrap:!1},h.createElement("h6",{className:Q.title},f),!Z&&h.createElement("div",{className:Q.description},B.map((A,z)=>h.createElement("span",{key:z},A))))},h.createElement("div",{className:Q.body},C)),w&&T.config.featureToggles.lokiQuerySplitting&&h.createElement($.u,{content:"Note: the query will be split into multiple parts and executed in sequence. Query limits will only apply each individual part."},h.createElement(R.J,{tabIndex:0,name:"info-circle",className:Q.tooltip,size:"sm"})),w&&h.createElement("p",{className:Q.stats},"This query will process approximately ",le(),"."))}const p=f=>({collapse:(0,y.css)({backgroundColor:"unset",border:"unset",marginBottom:0,["> button"]:{padding:f.spacing(0,1)}}),wrapper:(0,y.css)({width:"100%",display:"flex",justifyContent:"space-between",alignItems:"baseline"}),title:(0,y.css)({flexGrow:1,overflow:"hidden",fontSize:f.typography.bodySmall.fontSize,fontWeight:f.typography.fontWeightMedium,margin:0}),description:(0,y.css)({color:f.colors.text.secondary,fontSize:f.typography.bodySmall.fontSize,fontWeight:f.typography.bodySmall.fontWeight,paddingLeft:f.spacing(2),gap:f.spacing(2),display:"flex"}),body:(0,y.css)({display:"flex",gap:f.spacing(2),flexWrap:"wrap"}),stats:(0,y.css)({margin:"0px",color:f.colors.text.secondary,fontSize:f.typography.bodySmall.fontSize}),tooltip:(0,y.css)({marginRight:f.spacing(.25)})})},7963:(oe,U,i)=>{i.r(U),i.d(U,{plugin:()=>yr});var y=i(68246),h=i(84714),L=i(32713),r=i(27702),M=i(86312),T=i(34667);function N(){return(0,M.ff)("grafana_traces_cheatsheet_clicked",{datasourceType:"tempo",grafana_version:T.config.buildInfo.version}),r.createElement("div",null,r.createElement("h2",{id:"tempo-cheat-sheet"},"Tempo Cheat Sheet"),r.createElement("p",null,"Tempo is a trace id lookup store. Enter a trace id in the above field and hit \u201CRun Query\u201D to retrieve your trace. Tempo is generally paired with other datasources such as Loki or Prometheus to find traces."),r.createElement("p",null,"Here are some"," ",r.createElement("a",{href:"https://grafana.com/docs/tempo/latest/guides/instrumentation/",target:"blank"},"instrumentation examples")," ","to get you started with trace discovery through logs and metrics (exemplars)."))}var v=i(42844),$=i(13741),R=i(79399),x=i(71107),p=i(48024),f=i(64022),C=i(40705),B=i(66670),w=i(66310),Z=i(80601),E=i(53901),Q=i(83392),le=i(10864);const A=(t,e)=>{const a=t?` (${t})`:"";return`${e||"Error"}${a}. Please check the server logs for more details.`};async function z(t){if(!t)return;const e=(0,le.F)();try{return await e.get(t)}catch(a){console.error("Failed to load data source",a);return}}function ee({logsDatasourceUid:t,onChange:e,onRunQuery:a,query:s}){const n=(0,Z.Z)(()=>z(t),[t]);if(n.loading)return null;const o=n.value;return o?r.createElement(r.Fragment,null,r.createElement(E.W,null,"Tempo uses ",o.name," to find traces."),r.createElement(Q.n,{datasource:o,onChange:e,onRunQuery:a,query:s.linkedQuery??{refId:"linked"},history:[]})):t?t&&!o?r.createElement("div",{className:"text-warning"},"Loki search datasource is configured but the data source no longer exists. Please configure existing data source to use the search."):null:r.createElement("div",{className:"text-warning"},"Please set up a Loki search datasource in the datasource settings.")}var te=i(81078),Ie=i(32082),pe=i(73289),ve=i(39317),Nt=i(37221),ye=i(63439),ce=i(28580),Ee=i(1128),Je=i(33877),ae=i(73807),re=i(84749),k=i(89949),j=i(45383),qe=i(91053),Lt=i(91826),Xe=i(6857),et=i(42420),tt=i(78209),Ce=i(22479),q=i(39343),Me=i(56469),at=i(9045),$e=i(28037),Y=i(53933),rt=i(76305),Pe=i(99633),wt=i(62247),ue=i(29241),At=i(42751),Te=i(64167),Ot=i(26631),Ne=i(5926);const Er={filters:[]};var Se=(t=>(t.Done="done",t.Error="error",t.Pending="pending",t.Streaming="streaming",t))(Se||{}),G=(t=>(t.Resource="resource",t.Span="span",t.Unscoped="unscoped",t))(G||{});const Rt={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:{}},nt=["=","!=",">","<",">=","<=","=~"],Qt=["=","!=","=~"],$t=["=","!=",">","<",">=","<="],Le=["duration","kind","name","status"],We=["resource","span"],Wt={ignoreCase:!1,defaultToken:"",tokenPostfix:".traceql",keywords:Le.concat(We),operators:nt,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"]]}},Ut={id:"traceql",extensions:[".traceql"],aliases:["tempo","traceql"],mimetypes:[],def:{language:Wt,languageConfiguration:Rt}},Vt={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:/[{};()`,.]/},st=t=>`{${t.filter(e=>e.tag&&e.operator&&e.value?.length).map(e=>`${it(e)}${e.tag}${e.operator}${Ft(e)}`).join(" && ")}}`,Ft=t=>Array.isArray(t.value)&&t.value.length>1?`"${t.value.join("|")}"`:t.valueType==="string"?`"${t.value}"`:t.value,it=t=>Le.find(e=>e===t.tag)?"":(t.scope===G.Resource||t.scope===G.Span?t.scope?.toLowerCase():"")+".",Ue=t=>it(t)+t.tag,_t=t=>t.tag==="name"?"Span Name":(0,k.startCase)(Ue(t)),Bt=(t,e)=>[...Le,...t].filter(a=>!e.includes(a)),Ve=t=>(0,k.uniq)(t.map(e=>e.name&&e.name!=="intrinsic"&&e.tags?e.tags:[]).flat()),jt=t=>(0,k.uniq)(t.map(e=>e.tags?e.tags:[]).flat()),ot=(t,e)=>(0,k.uniq)(t.map(a=>a.name&&a.name===e&&a.tags?a.tags:[]).flat());function lt(t,e,a){const s=t.slice(0);return s[e]=a,s}const ct=t=>{const e={label:t,value:t};switch(t){case"=":e.description="Equals";break;case"!=":e.description="Not equals";break;case">":e.description="Greater";break;case">=":e.description="Greater or Equal";break;case"<":e.description="Less";break;case"<=":e.description="Less or Equal";break;case"=~":e.description="Matches regex";break;case"!~":e.description="Does not match regex";break}return e};var F=i(84160);class Fe extends y.iL{constructor(e,a){super(),this.request=async(s,n={})=>(await this.datasource.metadataRequest(s,n))?.data,this.start=async()=>(this.startTask||(this.startTask=this.fetchTags().then(()=>[])),this.startTask),this.setV1Tags=s=>{this.tagsV1=s},this.setV2Tags=s=>{this.tagsV2=s},this.getTags=s=>this.tagsV2&&s?s===G.Unscoped?Ve(this.tagsV2):ot(this.tagsV2,s):this.tagsV1?(this.tagsV1.find(n=>n==="status")||this.tagsV1.push("status"),this.tagsV1):[],this.getTraceqlAutocompleteTags=s=>{if(this.tagsV2){if(s){if(s===G.Unscoped)return Ve(this.tagsV2)}else return Ve(this.tagsV2);return ot(this.tagsV2,s)}else if(this.tagsV1)return this.tagsV1.find(n=>n==="status")||this.tagsV1.push("status"),this.tagsV1;return[]},this.getAutocompleteTags=()=>this.tagsV2?jt(this.tagsV2):this.tagsV1?(this.tagsV1.find(s=>s==="status.code")||this.tagsV1.push("status.code"),this.tagsV1):[],this.datasource=e,Object.assign(this,a)}async fetchTags(){let e,a;try{a=await this.request("/api/v2/search/tags",[])}catch{e=await this.request("/api/search/tags",[])}a&&a.scopes?this.setV2Tags(a.scopes):e&&this.setV1Tags(e.tagNames)}async getOptionsV1(e){const a=await this.request(`/api/search/tag/${e}/values`);let s=[];return a&&a.tagValues&&(s=a.tagValues.map(n=>({value:n,label:n}))),s}async getOptionsV2(e){const a=await this.request(`/api/v2/search/tag/${e}/values`);let s=[];return a&&a.tagValues&&(s=a.tagValues.map(n=>({type:n.type,value:n.value,label:n.value}))),s}}var de=i(71523),kt=i(63384),ut=i(66117),Kt=i(81087),zt=i(5168),Gt=i(43685);async function Ht(){return(0,ut.Z)()}function Zt(t,e,a,s){const n=a.range;let o,l=Y.Gu.NotStarted;return(0,kt.P)(()=>Ht()).pipe((0,Ce.z)(c=>{const d=performance.now();return(0,Gt.gj)().getStream({scope:Kt.z.DataSource,namespace:e.uid,path:`search/${c}`,data:{...t,timeRange:{from:n.from.toISOString(),to:n.to.toISOString()}}}).pipe((0,q.U)(u=>{if("message"in u&&u?.message){const m=performance.now()-d,S=u.message.data.values[0][0],I=u.message.data.values[1][0],W=u.message.data.values[2][0],D=u.message.data.values[3][0];switch(W){case Se.Done:l=Y.Gu.Done;break;case Se.Streaming:l=Y.Gu.Streaming;break;case Se.Error:throw new Error(D)}o=[Yt(I,W,m),...(0,de.xA)(S,s)]}return{data:o||[],state:l}}))}))}function Yt(t,e,a){const s={steps:[{color:"blue",value:-1/0},{color:"green",value:75}],mode:zt.H.Absolute};return{refId:"streaming-progress",name:"Streaming Progress",length:1,fields:[{name:"state",type:ue.fS.string,values:[(0,k.capitalize)(e.toString())],config:{displayNameFromDS:"State"}},{name:"elapsedTime",type:ue.fS.number,values:[a],config:{unit:"ms",displayNameFromDS:"Elapsed Time"}},{name:"totalBlocks",type:ue.fS.number,values:[t.totalBlocks],config:{displayNameFromDS:"Total Blocks"}},{name:"completedJobs",type:ue.fS.number,values:[t.completedJobs],config:{displayNameFromDS:"Completed Jobs"}},{name:"totalJobs",type:ue.fS.number,values:[t.totalJobs],config:{displayNameFromDS:"Total Jobs"}},{name:"progress",type:ue.fS.number,values:[e===Se.Done?100:(t.completedJobs||0)/(t.totalJobs||1)*100],config:{displayNameFromDS:"Progress",unit:"percent",min:0,max:100,custom:{cellOptions:{type:"gauge",mode:"gradient"}},thresholds:s}}],meta:{preferredVisualisationType:"table"}}}const me=20;class Jt extends At.CK{constructor(e,a=(0,ve.J)()){super(e),this.instanceSettings=e,this.templateSrv=a,this.uploadedJson=null,this.getLokiSearchDS=()=>{const s=this.tracesToLogs?.lokiSearch!==!1&&this.lokiSearch===void 0?this.tracesToLogs?.datasourceUid:void 0;return this.lokiSearch?.datasourceUid??s},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 Fe(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=[],s=e.targets.filter(l=>!l.hide),n=(0,k.groupBy)(s,l=>l.queryType||"traceql");if(n.clear)return(0,j.of)({data:[],state:Y.Gu.Done});const o=this.getLokiSearchDS();if(o&&n.search?.length>0){(0,M.ff)("grafana_traces_loki_search_queried",{datasourceType:"tempo",app:e.app??"",grafana_version:T.config.buildInfo.version,hasLinkedQueryExpr:!!(n.search[0].linkedQuery?.expr&&n.search[0].linkedQuery?.expr!=="")});const l=(0,Ne.ak)();a.push((0,qe.D)(l.get(o)).pipe((0,Ce.z)(c=>{const d={...e,targets:n.search.map(m=>m.linkedQuery)},g=c.instanceSettings.jsonData.derivedFields?.filter(m=>m.datasourceUid===this.uid&&m.matcherRegex).map(m=>m.matcherRegex)||[];return!g||g.length===0?(0,Lt._)(()=>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)(m=>m.error?m:(0,de.RY)(m,this.uid,this.name,g)))})))}if(n.nativeSearch?.length)try{(0,M.ff)("grafana_traces_search_queried",{datasourceType:"tempo",app:e.app??"",grafana_version:T.config.buildInfo.version,hasServiceName:!!n.nativeSearch[0].serviceName,hasSpanName:!!n.nativeSearch[0].spanName,resultLimit:n.nativeSearch[0].limit??"",hasSearch:!!n.nativeSearch[0].search,minDuration:n.nativeSearch[0].minDuration??"",maxDuration:n.nativeSearch[0].maxDuration??""});const l={startTime:e.range.from.unix(),endTime:e.range.to.unix()},c=this.applyVariables(n.nativeSearch[0],e.scopedVars),d=this.buildSearchQuery(c,l);a.push(this._request("/api/search",d).pipe((0,q.U)(u=>({data:[(0,de.n4)(u.data.traces,this.instanceSettings)]})),(0,Me.K)(u=>(0,j.of)({error:{message:A(u.data.message)},data:[]}))))}catch(l){return(0,j.of)({error:{message:l instanceof Error?l.message:"Unknown error occurred"},data:[]})}if(n.traceql?.length)try{const c=this.applyVariables(n.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:T.config.buildInfo.version,hasQuery:c!==""}),a.push(this.handleTraceIdQuery(e,n.traceql))):((0,M.ff)("grafana_traces_traceql_queried",{datasourceType:"tempo",app:e.app??"",grafana_version:T.config.buildInfo.version,query:c??"",streaming:T.config.featureToggles.traceQLStreaming}),T.config.featureToggles.traceQLStreaming?a.push(this.handleStreamingSearch(e,n.traceql)):a.push(this._request("/api/search",{q:c,limit:e.targets[0].limit??me,start:e.range.from.unix(),end:e.range.to.unix()}).pipe((0,q.U)(u=>({data:(0,de.xA)(u.data.traces,this.instanceSettings)})),(0,Me.K)(u=>(0,j.of)({error:{message:A(u.data.message)},data:[]})))))}catch(l){return(0,j.of)({error:{message:l instanceof Error?l.message:"Unknown error occurred"},data:[]})}if(n.traceqlSearch?.length)try{const l=st(n.traceqlSearch[0].filters);(0,M.ff)("grafana_traces_traceql_search_queried",{datasourceType:"tempo",app:e.app??"",grafana_version:T.config.buildInfo.version,query:l??"",streaming:T.config.featureToggles.traceQLStreaming}),T.config.featureToggles.traceQLStreaming?a.push(this.handleStreamingSearch(e,n.traceqlSearch,l)):a.push(this._request("/api/search",{q:l,limit:e.targets[0].limit??me,start:e.range.from.unix(),end:e.range.to.unix()}).pipe((0,q.U)(c=>({data:(0,de.xA)(c.data.traces,this.instanceSettings)})),(0,Me.K)(c=>(0,j.of)({error:{message:A(c.data.message)},data:[]}))))}catch(l){return(0,j.of)({error:{message:l instanceof Error?l.message:"Unknown error occurred"},data:[]})}if(n.upload?.length)if(this.uploadedJson){(0,M.ff)("grafana_traces_json_file_uploaded",{datasourceType:"tempo",app:e.app??"",grafana_version:T.config.buildInfo.version});const l=JSON.parse(this.uploadedJson),c=l.batches,d=Array.isArray(l)&&l.some(u=>u?.meta?.preferredVisualisationType==="nodeGraph");c?a.push((0,j.of)((0,de.IM)(l.batches,this.nodeGraph?.enabled))):d?a.push((0,j.of)({data:l,state:Y.Gu.Done})):a.push((0,j.of)({error:{message:"Unable to parse uploaded data."},data:[]}))}else a.push((0,j.of)({data:[],state:Y.Gu.Done}));if(this.serviceMap?.datasourceUid&&n.serviceMap?.length>0){(0,M.ff)("grafana_traces_service_graph_queried",{datasourceType:"tempo",app:e.app??"",grafana_version:T.config.buildInfo.version,hasServiceMapQuery:!!n.serviceMap[0].serviceMapQuery});const l=this.serviceMap.datasourceUid,c=this.uid;a.push(qt(e,l,c).pipe((0,at.b)(d=>Xt(e,d,l).pipe((0,at.b)(u=>ea(e,u,l,c))))))}return(0,Xe.T)(...a)}applyTemplateVariables(e,a){return this.applyVariables(e,a)}interpolateVariablesInQueries(e,a){return!e||e.length===0?[]:e.map(s=>({...s,datasource:this.getRef(),...this.applyVariables(s,a)}))}applyVariables(e,a){const s={...e};return e.linkedQuery&&(s.linkedQuery={...e.linkedQuery,expr:this.templateSrv.replace(e.linkedQuery?.expr??"",a)}),{...s,query:this.templateSrv.replace(e.query??"",a,Te.b8.Pipe),serviceName:this.templateSrv.replace(e.serviceName??"",a),spanName:this.templateSrv.replace(e.spanName??"",a),search:this.templateSrv.replace(e.search??"",a),minDuration:this.templateSrv.replace(e.minDuration??"",a),maxDuration:this.templateSrv.replace(e.maxDuration??"",a)}}handleTraceIdQuery(e,a){const s=a.filter(o=>o.query).map(o=>({...o,query:o.query.trim(),queryType:"traceId"}));if(!s.length)return et.E;const n=this.traceIdQueryRequest(e,s);return super.query(n).pipe((0,q.U)(o=>o.error?o:(0,de.Jk)(o,this.nodeGraph?.enabled)))}traceIdQueryRequest(e,a){const s={...e,targets:a};return this.traceQuery?.timeShiftEnabled?s.range=e.range&&{...e.range,from:e.range.from.subtract(rt.intervalToMs(this.traceQuery?.spanStartTimeShift||"30m"),"milliseconds"),to:e.range.to.add(rt.intervalToMs(this.traceQuery?.spanEndTimeShift||"30m"),"milliseconds")}:s.range={from:(0,Pe.CQ)(0),to:(0,Pe.CQ)(0),raw:{from:(0,Pe.CQ)(0),to:(0,Pe.CQ)(0)}},s}handleStreamingSearch(e,a,s){const n=a.filter(o=>o.query||s).map(o=>({...o,query:s||o.query.trim()}));return n.length?(0,Xe.T)(...n.map(o=>Zt(o,this,e,this.instanceSettings))):et.E}async metadataRequest(e,a={}){return await(0,tt.n)(this._request(e,a,{method:"GET",hideFromInspector:!0}))}_request(e,a,s){const n=a?(0,Ot.tW)(a):"",o=`${this.instanceSettings.url}${e}${n.length?`?${n}`:""}`,l={...s,url:o};return(0,pe.i)().fetch(l)}async testDatasource(){const e={headers:{},method:"GET",url:`${this.instanceSettings.url}/api/echo`};return await(0,tt.n)((0,pe.i)().fetch(e).pipe((0,Ce.z)(()=>(0,j.of)({status:"success",message:"Data source successfully connected."})),(0,Me.K)(a=>(0,j.of)({status:"error",message:A(a.data.message,"Unable to connect with Tempo")}))))}getQueryDisplayText(e){if(e.queryType==="nativeSearch"){let a=[];for(const s of["serviceName","spanName","search","minDuration","maxDuration","limit"])e.hasOwnProperty(s)&&e[s]&&a.push(`${(0,k.startCase)(s)}: ${e[s]}`);return a.join(", ")}return e.query}buildSearchQuery(e,a){let s=e.search??"",n=(0,k.pick)(e,["minDuration","maxDuration","limit"]);if(n=(0,k.pickBy)(n,k.identity),e.serviceName&&(s+=` service.name="${e.serviceName}"`),e.spanName&&(s+=` name="${e.spanName}"`),n.limit||(n.limit=me),n.minDuration){if(n.minDuration=this.templateSrv.replace(n.minDuration??""),!(0,Ie.IA)(n.minDuration))throw new Error("Please enter a valid min duration.");n.minDuration=n.minDuration.replace(/\s/g,"")}if(n.maxDuration){if(n.maxDuration=this.templateSrv.replace(n.maxDuration??""),!(0,Ie.IA)(n.maxDuration))throw new Error("Please enter a valid max duration.");n.maxDuration=n.maxDuration.replace(/\s/g,"")}if(!Number.isInteger(n.limit)||n.limit<=0)throw new Error("Please enter a valid limit.");let o={tags:s,...n};return a&&(o.start=a.startTime,o.end=a.endTime),o}}function _e(t,e){return(0,qe.D)((0,Ne.ak)().get(e)).pipe((0,Ce.z)(a=>a.query(t)))}function qt(t,e,a){const s=Be(t);return _e(s,e).pipe((0,$e.q)(),(0,q.U)(n=>{const o=n.find(d=>!!d.error);if(o)throw new Error(A(o.error?.message));const{nodes:l,edges:c}=(0,F.BC)(n,t.range);if(l.fields.length>0&&c.fields.length>0){const d=l.fields[0].values.length,u=c.fields[0].values.length;(0,M.ff)("grafana_traces_service_graph_size",{datasourceType:"tempo",grafana_version:T.config.buildInfo.version,nodeLength:d,edgeLength:u})}return l.refId=t.targets[0].refId,c.refId=t.targets[0].refId,l.fields[0].config=dt(e,a,"__data.fields.id","__data.fields[0]"),c.fields[0].config=dt(e,a,"__data.fields.target","__data.fields.target","__data.fields.source"),{data:[l,c],state:Y.Gu.Done}}))}function Xt(t,e,a){const s=Be(t);return s.targets=pt([ge(F.rB,F.T1,t)]),_e(s,a).pipe((0,$e.q)(),(0,q.U)(n=>{const o=n.find(l=>!!l.error);if(o)throw new Error(A(o.error?.message));return{data:[n[0]?.data??[],e.data[0],e.data[1]],state:Y.Gu.Done}}))}function ea(t,e,a,s){let n=[],o="",l=[],c=[];if(e.data[0][0]&&t.app===wt.zj.Explore){const g=e.data[0][0].fields.find(m=>m.name==="span_name");g&&g.values&&(c=g.values)}else e.data[0]&&e.data[0].map(g=>{const m=g.fields.find(S=>S.labels?.span_name);m&&c.push(m.labels?.span_name)});const d=ta(c);d.length>0&&(o=ge(F.$C,'span_name=~"'+d.join("|")+'"',t),n.push(o),d.map(g=>{const m=ge(F.vO,'span_name=~"'+g+'"',t);l.push(m),n.push(m)}));const u=Be(t);return u.targets=pt(n),_e(u,a).pipe((0,$e.q)(),(0,q.U)(g=>{const m=g.find(I=>!!I.error);if(m)throw new Error(A(m.error?.message));const S=aa(t,e,g[0],o,l,a,s);return S.fields.length===0?{data:[e.data[1],e.data[2]],state:Y.Gu.Done}:{data:[S,e.data[1],e.data[2]],state:Y.Gu.Done}}))}function he(t,e,a,s){return{url:"",title:t,internal:{query:{expr:e,range:!s,exemplar:!s,instant:s},datasourceUid:a,datasourceName:(0,Ne.ak)().getDataSourceSettingsByUid(a)?.name??""}}}function ta(t){return t.map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\\\$&"))}function dt(t,e,a,s,n){return n=n?`client="\${${n}}",`:"",{links:[he("Request rate",`sum by (client, server)(rate(${F.Yt}{${n}server="\${${a}}"}[$__rate_interval]))`,t,!1),he("Request histogram",`histogram_quantile(0.9, sum(rate(${F.NZ}{${n}server="\${${a}}"}[$__rate_interval])) by (le, client, server))`,t,!1),he("Failed request rate",`sum by (client, server)(rate(${F.yf}{${n}server="\${${a}}"}[$__rate_interval]))`,t,!1),mt("View traces",`\${${s}}`,"",e)]}}function mt(t,e,a,s){let n={queryType:"nativeSearch"};return e!==""&&(n.serviceName=e),a!==""&&(n.spanName=a),{url:"",title:t,internal:{query:n,datasourceUid:s,datasourceName:(0,Ne.ak)().getDataSourceSettingsByUid(s)?.name??""}}}function Be(t){return{...t,targets:F.t3.map(e=>{const{serviceMapQuery:a,serviceMapIncludeNamespace:s}=t.targets[0];return{format:"table",refId:e,expr:`sum by (client, server${s?", client_service_namespace, server_service_namespace":""}) (rate(${e}${a||""}[$__range]))`,instant:!0}})}}function aa(t,e,a,s,n,o,l){let c={fields:[]};const d=e.data[0]?.filter(m=>m.refId===ge(F.rB,F.T1,t)),u=a.data.filter(m=>m.refId===s),g=a.data.filter(m=>n.includes(m.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:[he("Rate",je(ge(F.rB,'span_name="${__data.fields[0]}"',t)),o,!1)],decimals:2}}),c.fields.push({...d[0].fields[2],name:"  ",labels:null,config:{color:{mode:"continuous-BlPu"},custom:{cellOptions:{mode:Te.QH.Lcd,type:Te.h2.Gauge}},decimals:3}})),u.length>0&&u[0].fields?.length>2){const m=u[0].fields[1]?.values??[],S=u[0].fields[2]?.values??[];let I={};m.map((D,O)=>{I[D]={value:S[O]}});const W=gt({...d},I);c.fields.push({...u[0].fields[2],name:"Error Rate",values:W,config:{links:[he("Error Rate",je(ge(F.$C,'span_name="${__data.fields[0]}"',t)),o,!1)],decimals:2}}),c.fields.push({...u[0].fields[2],name:"   ",values:W,labels:null,config:{color:{mode:"continuous-RdYlGr"},custom:{cellOptions:{mode:Te.QH.Lcd,type:Te.h2.Gauge}},decimals:3}})}if(g.length>0&&g[0].fields?.length>1){let m={};g.map(S=>{const I=S.refId?.includes('span_name=~"')?'span_name=~"':'span_name="',W=S.refId?.split(I)[1].split('"}')[0];m[W]={value:S.fields[1].values[0]}}),c.fields.push({...g[0].fields[1],name:"Duration (p90)",values:gt({...d},m),config:{links:[he("Duration",je(ge(F.vO,'span_name="${__data.fields[0]}"',t)),o,!1)],unit:"s"}})}return c.fields.length>0&&c.fields[0].values&&c.fields.push({name:"Links",type:ue.fS.string,values:c.fields[0].values.map(()=>"Tempo"),config:{links:[mt("Tempo","","${__data.fields[0]}",l)]}}),c}function ge(t,e,a){let s=a.targets[0]?.serviceMapQuery??"";const n=s.match(/^{(.*)}$/);n?.length&&(s=n[1]),s=s.replace("client","service").replace("server","service");const o=s.includes("span_name")?t.params.concat(s):t.params.concat(s).concat(e).filter(l=>l);return t.expr.replace("{}","{"+o.join(",")+"}")}function je(t){return t=t.replace("topk(5, ","").replace(" by (span_name))",""),t.replace("__range","__rate_interval")}function gt(t,e){const a=t[0]?.fields[1]?.values??[];let s=[];for(let n=0;n<a.length;n++)Object.keys(e).includes(a[n])?s.push(e[a[n]].value):s.push("0");return s}function pt(t){return t.map(e=>({refId:e,expr:e,instant:!0}))}var ht=i(11649),fe=i(4021);class ra{constructor(e){this.triggerCharacters=["="," "],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:s,offset:n}=sa(this.monaco,e,a),o=this.getSituation(e.getValue(),n);return this.getCompletions(o).then(c=>{const d=c.length.toString().length;return{suggestions:c.map((g,m)=>({kind:na(g.type,this.monaco),label:g.label,insertText:g.insertText,sortText:m.toString().padStart(d,"0"),range:s}))}})}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){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),s=[],n=o=>`"${o.label}"`;return a.forEach(o=>{o?.label&&s.push({label:o.label,insertText:n(o),type:"TAG_VALUE"})}),s;default:throw new Error(`Unexpected situation ${e}`)}}getTagsCompletions(){return this.languageProvider.getAutocompleteTags().sort((a,s)=>a.localeCompare(s,void 0,{sensitivity:"accent"})).map(a=>({label:a,insertText:a,type:"TAG_NAME"}))}getSituation(e,a){if(e===""||a===0||e[e.length-1]===" ")return{type:"EMPTY"};const s=e.substring(0,a),n=/(?<key>[^= ]+)(?<equals>=)?(?<value>([^ "]+)|"([^"]*)")?/,o=s.match(new RegExp(n,"g"));if(o?.length){const c=o[o.length-1].match(n);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 na(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 sa(t,e,a){const s=e.getWordAtPosition(a),n=s!=null?t.Range.lift({startLineNumber:a.lineNumber,endLineNumber:a.lineNumber,startColumn:s.startColumn,endColumn:s.endColumn}):t.Range.fromPositions(a),o={column:a.column,lineNumber:a.lineNumber};return{offset:e.getOffsetAt(o),range:n}}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:s}=t,n=ua(t.datasource),o=(0,w.l4)(),l=ma(o,s);return r.createElement(ht.p,{value:t.value,language:De,onBlur:a,onChange:e,containerStyles:l.queryField,monacoOptions:{folding:!1,fontSize:14,lineNumbers:"off",overviewRulerLanes:0,renderLineHighlight:"none",scrollbar:{vertical:"hidden",verticalScrollbarSize:8,horizontal:"hidden",horizontalScrollbarSize:0},scrollBeyondLastLine:!1,wordWrap:"on"},onBeforeEditorMount:da,onEditorDidMount:(c,d)=>{n(c,d),la(c,d,l),ca(c)}})}function la(t,e,a){const s=[{range:new e.Range(1,1,1,1),options:{className:a.placeholder,isWholeLine:!0}}];let n=[];const o=()=>{const l=t.getModel();if(!l)return;const c=l.getValueLength()===0?s:[];n=l.deltaDecorations(n,c)};o(),t.onDidChangeModelContent(o)}function ca(t){const e=t.getDomNode(),a=()=>{if(e){const s=Math.min(1e3,t.getContentHeight()),n=parseInt(e.style.width,10);e.style.width=`${n}px`,e.style.height=`${s}px`,t.layout({width:n,height:s})}};t.onDidContentSizeChange(a),a()}function ua(t){const e=(0,r.useRef)(new ra({languageProvider:t.languageProvider}));(0,r.useEffect)(()=>{(async()=>{try{await t.languageProvider.start()}catch(n){n instanceof Error&&(0,re.WI)((0,fe.$l)((0,ae.t_)("Error",n)))}})()},[t]);const a=(0,r.useRef)(null);return(0,r.useEffect)(()=>()=>{a.current?.()},[]),(s,n)=>{e.current.editor=s,e.current.monaco=n;const{dispose:o}=n.languages.registerCompletionItemProvider(De,e.current);a.current=o}}let ft=!1;const De="tagsfield";function da(t){if(!ft){ft=!0;const{aliases:e,extensions:a,mimetypes:s,def:n}=ia;t.languages.register({id:De,aliases:e,extensions:a,mimetypes:s}),t.languages.setMonarchTokensProvider(De,n.language),t.languages.setLanguageConfiguration(De,n.languageConfiguration)}}const ma=(t,e)=>({queryField:(0,v.css)`
      border-radius: ${t.shape.borderRadius()};
      border: 1px solid ${t.components.input.borderColor};
      flex: 1;
    `,placeholder:(0,v.css)`
      ::after {
        content: '${e}';
        font-family: ${t.typography.fontFamilyMonospace};
        opacity: 0.3;
      }
    `}),vt="e.g. 1.2s, 100ms",ga=({datasource:t,query:e,onChange:a,onBlur:s,onRunQuery:n})=>{const o=(0,w.wW)(pa),l=(0,r.useMemo)(()=>new Fe(t),[t]),[c,d]=(0,r.useState)(),[u,g]=(0,r.useState)(),[m,S]=(0,r.useState)(null),[I,W]=(0,r.useState)({}),[D,O]=(0,r.useState)({serviceName:!1,spanName:!1}),J=(0,r.useCallback)(async(b,V="")=>{const ie=b==="serviceName"?"service.name":"name";O(_=>({..._,[b]:!0}));try{return(await l.getOptionsV1(ie)).filter(Qe=>Qe.value?(0,Nt.C)(Qe.value,V).found:!1)}catch(_){return(0,pe.kW)(_)&&_?.status===404?S(_):_ instanceof Error&&(0,re.WI)((0,Je.$l)((0,ae.t_)("Error",_))),[]}finally{O(_=>({..._,[b]:!1}))}},[l]);(0,r.useEffect)(()=>{(async()=>{try{const[V,ie]=await Promise.all([J("serviceName"),J("spanName")]);e.serviceName&&(0,ve.J)().containsTemplate(e.serviceName)&&V.push((0,te.E)(e.serviceName)),d(V),e.spanName&&(0,ve.J)().containsTemplate(e.spanName)&&ie.push((0,te.E)(e.spanName)),g(ie)}catch(V){(0,pe.kW)(V)&&V?.status===404?S(V):V instanceof Error&&(0,re.WI)((0,Je.$l)((0,ae.t_)("Error",V)))}})()},[l,J,e.serviceName,e.spanName]);const X=b=>{b.key==="Enter"&&(b.shiftKey||b.ctrlKey)&&n()},Ye=(0,r.useCallback)(b=>{a({...e,search:b})},[a,e]),se=(0,ve.J)();return r.createElement(r.Fragment,null,r.createElement("div",{className:o.container},r.createElement(ye.b,{title:"Deprecated query type",severity:"warning"},"This query type has been deprecated and will be removed in Grafana v10.3. Please migrate to another Tempo query type."),r.createElement(x.Z,null,r.createElement(p._,{label:"Service Name",labelWidth:14,grow:!0},r.createElement(ce.Ph,{inputId:"service",options:c,onOpenMenu:()=>{J("serviceName")},isLoading:D.serviceName,value:c?.find(b=>b?.value===e.serviceName)||e.serviceName,onChange:b=>{a({...e,serviceName:b?.value})},placeholder:"Select a service",isClearable:!0,onKeyDown:X,"aria-label":"select-service-name",allowCustomValue:!0}))),r.createElement(x.Z,null,r.createElement(p._,{label:"Span Name",labelWidth:14,grow:!0},r.createElement(ce.Ph,{inputId:"spanName",options:u,onOpenMenu:()=>{J("spanName")},isLoading:D.spanName,value:u?.find(b=>b?.value===e.spanName)||e.spanName,onChange:b=>{a({...e,spanName:b?.value})},placeholder:"Select a span",isClearable:!0,onKeyDown:X,"aria-label":"select-span-name",allowCustomValue:!0}))),r.createElement(x.Z,null,r.createElement(p._,{label:"Tags",labelWidth:14,grow:!0,tooltip:"Values should be in logfmt."},r.createElement(oa,{placeholder:"http.status_code=200 error=true",value:e.search||"",onChange:Ye,onBlur:s,datasource:t}))),r.createElement(x.Z,null,r.createElement(p._,{label:"Min Duration",invalid:!!I.minDuration,labelWidth:14,grow:!0},r.createElement(Ee.I,{id:"minDuration",value:e.minDuration||"",placeholder:vt,onBlur:()=>{const b=se.replace(e.minDuration??"");e.minDuration&&!(0,Ie.IA)(b)?W({...I,minDuration:!0}):W({...I,minDuration:!1})},onChange:b=>a({...e,minDuration:b.currentTarget.value}),onKeyDown:X}))),r.createElement(x.Z,null,r.createElement(p._,{label:"Max Duration",invalid:!!I.maxDuration,labelWidth:14,grow:!0},r.createElement(Ee.I,{id:"maxDuration",value:e.maxDuration||"",placeholder:vt,onBlur:()=>{const b=se.replace(e.maxDuration??"");e.maxDuration&&!(0,Ie.IA)(b)?W({...I,maxDuration:!0}):W({...I,maxDuration:!1})},onChange:b=>a({...e,maxDuration:b.currentTarget.value}),onKeyDown:X}))),r.createElement(x.Z,null,r.createElement(p._,{label:"Limit",invalid:!!I.limit,labelWidth:14,grow:!0,tooltip:"Maximum number of returned results"},r.createElement(Ee.I,{id:"limit",value:e.limit||"",placeholder:`Default: ${me}`,type:"number",onChange:b=>{let V=b.currentTarget.value?parseInt(b.currentTarget.value,10):void 0;V&&(!Number.isInteger(V)||V<=0)?W({...I,limit:!0}):W({...I,limit:!1}),a({...e,limit:b.currentTarget.value?parseInt(b.currentTarget.value,10):void 0})},onKeyDown:X})))),m?r.createElement(ye.b,{title:"Unable to connect to Tempo search",severity:"info",className:o.alert},"Please ensure that Tempo is configured with search enabled. If you would like to hide this tab, you can configure it in the ",r.createElement("a",{href:`/datasources/edit/${t.uid}`},"datasource settings"),"."):null)},pa=t=>({container:(0,v.css)`
    max-width: 500px;
  `,alert:(0,v.css)`
    max-width: 75ch;
    margin-top: ${t.spacing(2)};
  `});var yt=i(57942),ha=i(86383),fa=i(81924),va=i(31465),ya=i(85187);const ke=r.memo(({onChange:t,query:e})=>{e.hasOwnProperty("limit")||(e.limit=me);const a=n=>{t({...e,limit:parseInt(n.currentTarget.value,10)})},s=[`Limit: ${e.limit||me}`];return r.createElement(r.Fragment,null,r.createElement(yt.p,null,r.createElement(ya.d,{title:"Options",collapsedInfo:s},r.createElement(fa.S,{label:"Limit",tooltip:"Maximum number of traces to return."},r.createElement(va.H,{className:"width-4",placeholder:"auto",type:"number",min:1,defaultValue:e.limit||me,onCommitChange:a,value:e.limit})))))});ke.displayName="TempoQueryBuilderOptions";const Ea=/^\d+(?:\.\d)?\d*(?:us|µs|ns|ms|s|m|h)$/,Ta=()=>({noBoxShadow:(0,v.css)`
    box-shadow: none;
    *:focus {
      box-shadow: none;
    }
  `}),Et=({filter:t,operators:e,updateFilter:a})=>{const s=(0,w.wW)(Ta);let n=!1;return typeof t.value=="string"&&(n=t.value?!Ea.test(t.value.concat("")):!1),r.createElement(f.Lh,{spacing:"none"},r.createElement(ce.Ph,{className:s.noBoxShadow,inputId:`${t.id}-operator`,options:e.map(ct),value:t.operator,onChange:o=>{a({...t,operator:o?.value})},isClearable:!1,"aria-label":`select ${t.id} operator`,allowCustomValue:!0,width:8}),r.createElement(Ee.I,{className:s.noBoxShadow,value:t.value,onChange:o=>{a({...t,value:o.currentTarget.value})},placeholder:"e.g. 100ms, 1.2s","aria-label":`select ${t.id} value`,invalid:n,width:18}))},Ke=({label:t,tooltip:e,children:a})=>r.createElement(x.Z,null,r.createElement(p._,{label:t,labelWidth:28,grow:!0,tooltip:e},a));var Tt=i(76715);const Sa=()=>({dropdown:(0,v.css)`
    box-shadow: none;
  `}),St=({filter:t,datasource:e,updateFilter:a,deleteFilter:s,isTagsLoading:n,tags:o,setError:l,hideScope:c,hideTag:d,hideValue:u,allowDelete:g})=>{const m=(0,w.wW)(Sa),S=(0,r.useMemo)(()=>new Fe(e),[e]),I=(0,r.useMemo)(()=>Ue(t),[t]),[W,D]=(0,r.useState)(t.operator),[O,J]=(0,r.useState)(t.value),X=async()=>{try{return await S.getOptionsV2(I)}catch(P){(0,pe.kW)(P)&&P?.status===404?l(P):P instanceof Error&&(0,re.WI)((0,fe.$l)((0,ae.t_)("Error",P)))}return[]},{loading:Ye,value:se}=(0,Z.Z)(X,[I,S,l]);(0,r.useEffect)(()=>{Array.isArray(t.value)&&t.value.length>1&&t.operator!=="=~"&&(D(t.operator),a({...t,operator:"=~"})),Array.isArray(t.value)&&t.value.length<=1&&(O?.length||0)>1&&a({...t,operator:W,value:t.value[0]})},[O,W,a,t]),(0,r.useEffect)(()=>{J(t.value)},[t.value]);const b=Object.values(G).map(P=>({label:P,value:P})),V=se?.filter(P=>P.type===se[0]?.type),ie=se?.length===V?.length?se?.[0]?.type:void 0;let _=nt;switch(ie){case"string":_=Qt;break;case"int":case"float":_=$t}return r.createElement(f.Lh,{spacing:"none",width:"auto"},!c&&r.createElement(ce.Ph,{className:m.dropdown,inputId:`${t.id}-scope`,options:b,value:t.scope,onChange:P=>{a({...t,scope:P?.value})},placeholder:"Select scope","aria-label":`select ${t.id} scope`}),!d&&r.createElement(ce.Ph,{className:m.dropdown,inputId:`${t.id}-tag`,isLoading:n,options:(t.tag!==void 0?(0,k.uniq)([t.tag,...o]):o).map(P=>({label:P,value:P})),value:t.tag,onChange:P=>{a({...t,tag:P?.value})},placeholder:"Select tag",isClearable:!0,"aria-label":`select ${t.id} tag`,allowCustomValue:!0}),r.createElement(ce.Ph,{className:m.dropdown,inputId:`${t.id}-operator`,options:_.map(ct),value:t.operator,onChange:P=>{a({...t,operator:P?.value})},isClearable:!1,"aria-label":`select ${t.id} operator`,allowCustomValue:!0,width:8}),!u&&r.createElement(ce.Ph,{className:m.dropdown,inputId:`${t.id}-value`,isLoading:Ye,options:se,value:t.value,onChange:P=>{Array.isArray(P)?a({...t,value:P.map(Qe=>Qe.value),valueType:P[0]?.type||ie}):a({...t,value:P?.value,valueType:P?.type||ie})},placeholder:"Select value",isClearable:!1,"aria-label":`select ${t.id} value`,allowCustomValue:!0,isMulti:!0,allowCreateWhileLoading:!0}),g&&r.createElement(Tt._,{variant:"secondary",icon:"times",onClick:()=>s?.(t),tooltip:"Remove tag","aria-label":`remove tag with ID ${t.id}`}))},Da=()=>({vertical:(0,v.css)`
    display: flex;
    flex-direction: column;
    gap: 0.25rem;
  `,horizontal:(0,v.css)`
    display: flex;
    flex-direction: row;
    gap: 1rem;
  `}),Dt=({updateFilter:t,deleteFilter:e,filters:a,datasource:s,setError:n,staticTags:o,isTagsLoading:l,hideValues:c})=>{const d=(0,w.wW)(Da),u=()=>(0,ut.Z)().slice(0,8),g=(0,r.useCallback)(()=>t({id:u(),operator:"=",scope:G.Span}),[t]);(0,r.useEffect)(()=>{a?.length||g()},[a,g]);const m=S=>{const I=s.languageProvider.getTags(S.scope);return Bt(I,o)};return r.createElement("div",{className:d.vertical},a?.map((S,I)=>r.createElement("div",{className:d.horizontal,key:S.id},r.createElement(St,{filter:S,datasource:s,setError:n,updateFilter:t,tags:m(S),isTagsLoading:l,deleteFilter:e,allowDelete:!0,hideValue:c}),I===a.length-1&&r.createElement(Tt._,{variant:"secondary",icon:"plus",onClick:g,title:"Add tag"}))))},ba=({datasource:t,query:e,onChange:a})=>{const s=(0,w.wW)(xa),[n,o]=(0,r.useState)(null),[l,c]=(0,r.useState)(!0),[d,u]=(0,r.useState)(""),g=(0,r.useCallback)(D=>{const O={...e};O.filters||=[];const J=O.filters.findIndex(X=>X.id===D.id);J>=0?O.filters=lt(O.filters,J,D):O.filters.push(D),a(O)},[a,e]),m=D=>{a({...e,filters:e.filters.filter(O=>O.id!==D.id)})};(0,r.useEffect)(()=>{u(st(e.filters||[]))},[e]);const S=(0,r.useCallback)(D=>e.filters?.find(O=>O.id===D),[e.filters]);(0,r.useEffect)(()=>{(async()=>{try{await t.languageProvider.start(),c(!1)}catch(O){O instanceof Error&&(0,re.WI)((0,fe.$l)((0,ae.t_)("Error",O)))}})()},[t]),(0,r.useEffect)(()=>{t.search?.filters?.filter(D=>D.value).forEach(D=>{S(D.id)||g(D)})},[t.search?.filters,S,g]);const I=t.search?.filters?.map(D=>D.tag)||[];I.push("duration");const W=(e.filters||[]).filter(D=>D.tag!=="duration"&&(t.search?.filters?.findIndex(O=>O.id===D.id)||0)===-1);return r.createElement(r.Fragment,null,r.createElement("div",{className:s.container},r.createElement("div",null,t.search?.filters?.map(D=>r.createElement(Ke,{key:D.id,label:_t(D),tooltip:`Filter your search by ${Ue(D)}. To modify the default filters shown for search visit the Tempo datasource configuration page.`},r.createElement(St,{filter:S(D.id)||D,datasource:t,setError:o,updateFilter:g,tags:[],hideScope:!0,hideTag:!0}))),r.createElement(Ke,{label:"Duration",tooltip:"The span duration, i.e.	end - start time of the span. Accepted units are ns, ms, s, m, h"},r.createElement(f.Lh,{spacing:"sm"},r.createElement(Et,{filter:S("min-duration")||{id:"min-duration",tag:"duration",operator:">",valueType:"duration"},operators:[">",">="],updateFilter:g}),r.createElement(Et,{filter:S("max-duration")||{id:"max-duration",tag:"duration",operator:"<",valueType:"duration"},operators:["<","<="],updateFilter:g}))),r.createElement(Ke,{label:"Tags"},r.createElement(Dt,{filters:W,datasource:t,setError:o,updateFilter:g,deleteFilter:m,staticTags:I,isTagsLoading:l}))),r.createElement(yt.p,null,r.createElement(ha.U,{query:d,lang:{grammar:Vt,name:"traceql"}})),r.createElement(ke,{onChange:a,query:e})),n?r.createElement(ye.b,{title:"Unable to connect to Tempo search",severity:"info",className:s.alert},"Please ensure that Tempo is configured with search enabled. If you would like to hide this tab, you can configure it in the ",r.createElement("a",{href:`/datasources/edit/${t.uid}`},"datasource settings"),"."):null)},xa=t=>({alert:(0,v.css)`
    max-width: 75ch;
    margin-top: ${t.spacing(2)};
  `,container:(0,v.css)`
    display: flex;
    gap: 4px;
    flex-wrap: wrap;
    flex-direction: column;
  `});var Ia=i(80280);function Ca({graphDatasourceUid:t,query:e,onChange:a}){const s=(0,w.wW)(Pa),n=(0,Z.Z)(()=>z(t),[t]),[o,l]=(0,r.useState)(void 0);if((0,r.useEffect)(()=>{async function u(g){const m=await g.getTagKeys({series:["traces_service_graph_request_server_seconds_sum","traces_service_graph_request_total","traces_service_graph_request_failed_total"]});l(!!m.length)}!n.loading&&n.value&&u(n.value)},[n]),n.loading)return null;const c=n.value;if(!t)return r.createElement("div",{className:"text-warning"},"Please set up a service graph datasource in the datasource settings.");if(t&&!c)return r.createElement("div",{className:"text-warning"},"Service graph datasource is configured but the data source no longer exists. Please configure existing data source to use the service graph functionality.");const d=Ma(e.serviceMapQuery||"");return r.createElement("div",null,r.createElement(x.Z,null,r.createElement(p._,{label:"Filter",labelWidth:14,grow:!0},r.createElement(Ia.F,{datasource:{uid:t},filters:d,getTagKeysOptions:{series:["traces_service_graph_request_total","traces_spanmetrics_calls_total"]},addFilter:u=>{a({...e,serviceMapQuery:ze([...d,u])})},removeFilter:u=>{const g=[...d];g.splice(u,1),a({...e,serviceMapQuery:ze(g)})},changeFilter:(u,g)=>{const m=[...d];m.splice(u,1,g),a({...e,serviceMapQuery:ze(m)})}}))),o===!1?r.createElement(ye.b,{title:"No service graph data found",severity:"info",className:s.alert},"Please ensure that service graph metrics are set up correctly according to the"," ",r.createElement("a",{target:"_blank",rel:"noreferrer noopener",href:"https://grafana.com/docs/grafana/latest/datasources/tempo/#service-graph",className:s.link},"Tempo documentation"),"."):null)}function Ma(t){let e,a=[];const s=/([\w_]+)(=|!=|<|>|=~|!~)"(.*?)"/g;for(;(e=s.exec(t))!==null;)a.push({key:e[1],operator:e[2],value:e[3],condition:""});return a}function ze(t){return`{${t.map(e=>`${e.key}${e.operator}"${e.value}"`).join(",")}}`}const Pa=t=>({alert:(0,v.css)`
    max-width: 75ch;
    margin-top: ${t.spacing(2)};
  `,link:(0,v.css)`
    color: ${t.colors.text.link};
    text-decoration: underline;
  `}),Na={};var La=(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))(La||{});const Ge=class{constructor(t){this.triggerCharacters=["{",".","[","(","=","~"," ",'"'],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:s}=Aa(this.monaco,t,e),n=this.getSituation(t.getValue(),s);return this.getCompletions(n).then(l=>{const c=l.length.toString().length;return{suggestions:l.map((u,g)=>{const m={kind:wa(u.type,this.monaco),label:u.label,insertText:u.insertText,sortText:g.toString().padStart(c,"0"),range:a,command:{id:this.registerInteractionCommandId||"noOp",title:"Report Interaction",arguments:[u.label,u.type]}};return Oa(m,u.type,t,s),m})}})}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){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(void 0,t.scope);case"SPANSET_AFTER_NAME":return Ge.operators.map(n=>({label:n,insertText:n,type:"OPERATOR"}));case"SPANSET_IN_VALUE":let e;try{e=await this.getTagValues(t.tagName)}catch(n){(0,pe.kW)(n)?(0,re.WI)((0,fe.$l)((0,ae.t_)(n.data.error,new Error(n.data.message)))):n instanceof Error&&(0,re.WI)((0,fe.$l)((0,ae.t_)("Error",n)))}const a=[],s=n=>t.betweenQuotes?n.label:n.type==="string"?`"${n.label}"`:n.label;return e?.forEach(n=>{n?.label&&a.push({label:n.label,insertText:s(n),type:"TAG_VALUE"})}),a;case"SPANSET_AFTER_VALUE":return Ge.logicalOps.concat("}").map(n=>({label:n,insertText:n,type:"OPERATOR"}));default:throw new Error(`Unexpected situation ${t}`)}}getTagsCompletions(t,e){return this.languageProvider.getTraceqlAutocompleteTags(e).sort((s,n)=>s.localeCompare(n,void 0,{sensitivity:"accent"})).map(s=>({label:s,insertText:(t||"")+s,type:"TAG_NAME"}))}getIntrinsicsCompletions(t){return Le.map(e=>({label:e,insertText:(t||"")+e,type:"KEYWORD"}))}getScopesCompletions(t){return We.map(e=>({label:e,insertText:(t||"")+e,type:"SCOPE"}))}getSituationInSpanSet(t){const e=/(?<name>[\w./-]+)?/,a=/(?<op>[!=+\-<>]+)/,s=/(?<value>(?<open_quote>")([^"\n&|]+)?(?<close_quote>")?|([^"\n\s&|]+))?/,n=new RegExp("([\\s{])("+e.source+"(?<space1>\\s*)("+a.source+"(?<space2>\\s*)"+s.source+")?)(?<space3>\\s*)$"),o=t.match(n);if(o){const l=o.groups?.name,c=o.groups?.op;if(!l)return{type:"SPANSET_EMPTY"};if(l===".")return{type:"SPANSET_ONLY_DOT"};const d=l.match(/^(?<pre_dot>\.)?(?<word>\w[\w./-]*\w)(?<post_dot>\.)?$/);return c?o.groups?.space3&&o.groups.open_quote===o.groups.close_quote?{type:"SPANSET_AFTER_VALUE"}:{type:"SPANSET_IN_VALUE",tagName:l,betweenQuotes:!!o.groups?.open_quote}:We.filter(u=>u===d?.groups?.word)&&d?.groups?.post_dot?{type:"SPANSET_IN_NAME_SCOPE",scope:d?.groups?.word||""}:{type:o.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 He=Ge;He.operators=["=","-","+","<",">",">=","<=","=~"],He.logicalOps=["&&","||"];function wa(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 Aa(t,e,a){const s=e.getWordAtPosition(a),n=s!=null?t.Range.lift({startLineNumber:a.lineNumber,endLineNumber:a.lineNumber,startColumn:s.startColumn,endColumn:s.endColumn}):t.Range.fromPositions(a),o={column:a.column,lineNumber:a.lineNumber};return{offset:e.getOffsetAt(o),range:n}}function Oa(t,e,a,s){if(e==="TAG_NAME"){const n=a.getValue().substring(0,s).match(/(span\.|resource\.|\.)?([\w./-]*)$/);if(n){const o=n[1],l=n[2];l&&(!o&&t.insertText[0]!=="."&&(t.insertText="."+t.insertText),t.range={...t.range,startColumn:s-l.length+1})}}}function Ra(t){const{onChange:e,onRunQuery:a,placeholder:s}=t,n=Va(t.datasource),o=(0,w.l4)(),l=_a(o,s),c=(0,r.useRef)(a);return c.current=a,r.createElement(ht.p,{value:t.value,language:be,onBlur:e,onChange:e,containerStyles:l.queryField,readOnly:t.readOnly,monacoOptions:{folding:!1,fontSize:14,lineNumbers:"off",overviewRulerLanes:0,renderLineHighlight:"none",scrollbar:{vertical:"hidden",verticalScrollbarSize:8,horizontal:"hidden",horizontalScrollbarSize:0},scrollBeyondLastLine:!1,wordWrap:"on"},onBeforeEditorMount:Fa,onEditorDidMount:(d,u)=>{t.readOnly||(n(d,u,Wa(d)),$a(d,u,()=>c.current()),Qa(d,u,l)),Ua(d)}})}function Qa(t,e,a){const s=[{range:new e.Range(1,1,1,1),options:{className:a.placeholder,isWholeLine:!0}}];let n=[];const o=()=>{const l=t.getModel();if(!l)return;const c=l.getValueLength()===0?s:[];n=l.deltaDecorations(n,c)};o(),t.onDidChangeModelContent(o)}function $a(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 Wa(t){return t.addCommand(0,function(e,a,s){const n={datasourceType:"tempo",type:s};s!=="TAG_VALUE"&&(n.label=a),(0,M.ff)("grafana_traces_traceql_completion",n)})}function Ua(t){const e=t.getDomNode(),a=()=>{if(e){const s=Math.min(1e3,t.getContentHeight()),n=parseInt(e.style.width,10);e.style.width=`${n}px`,e.style.height=`${s}px`,t.layout({width:n,height:s})}};t.onDidContentSizeChange(a),a()}function Va(t){const e=(0,r.useRef)(new He({languageProvider:t.languageProvider}));(0,r.useEffect)(()=>{(async()=>{try{await t.languageProvider.start()}catch(n){n instanceof Error&&(0,re.WI)((0,fe.$l)((0,ae.t_)("Error",n)))}})()},[t]);const a=(0,r.useRef)(null);return(0,r.useEffect)(()=>()=>{a.current?.()},[]),(s,n,o)=>{e.current.editor=s,e.current.monaco=n,e.current.setRegisterInteractionCommandId(o);const{dispose:l}=n.languages.registerCompletionItemProvider(be,e.current);a.current=l}}let bt=!1;const be="traceql";function Fa(t){if(!bt){bt=!0;const{aliases:e,extensions:a,mimetypes:s,def:n}=Ut;t.languages.register({id:be,aliases:e,extensions:a,mimetypes:s}),t.languages.setMonarchTokensProvider(be,n.language),t.languages.setLanguageConfiguration(be,n.languageConfiguration)}}const _a=(t,e)=>({queryField:(0,v.css)`
      border-radius: ${t.shape.borderRadius()};
      border: 1px solid ${t.components.input.borderColor};
      flex: 1;
    `,placeholder:(0,v.css)`
      ::after {
        content: '${e}';
        font-family: ${t.typography.fontFamilyMonospace};
        opacity: 0.3;
      }
    `});function Ba(t){const e=(0,w.wW)(ja),a=(0,k.defaults)(t.query,Na),s=n=>{t.onChange({...a,query:n})};return r.createElement(r.Fragment,null,r.createElement(E.W,null,"Build complex queries using TraceQL to select a list of traces."," ",r.createElement("a",{rel:"noreferrer",target:"_blank",href:"https://grafana.com/docs/tempo/latest/traceql/"},"Documentation")),r.createElement(Ra,{placeholder:"Enter a TraceQL query or trace ID (run with Shift+Enter)",value:a.query,onChange:s,datasource:t.datasource,onRunQuery:t.onRunQuery}),r.createElement("div",{className:e.optionsContainer},r.createElement(ke,{query:a,onChange:t.onChange})))}const ja=()=>({optionsContainer:(0,v.css)`
    margin-top: 10px;
  `}),ka="traceqlSearch";class Ka extends r.PureComponent{constructor(e){super(e),this.onChangeLinkedQuery=a=>{const{query:s,onChange:n}=this.props;n({...s,linkedQuery:{...a,refId:"linked"}})},this.onRunLinkedQuery=()=>{this.props.onRunQuery()},this.onClearResults=()=>{const{onChange:a,query:s,onRunQuery:n}=this.props;a({...s,queryType:"clear"}),n()},this.state={uploadModalOpen:!1}}async componentDidMount(){(!this.props.query.queryType||this.props.query.queryType==="clear")&&this.props.onChange({...this.props.query,queryType:ka})}render(){const{query:e,onChange:a,datasource:s,app:n}=this.props,o=s.getLokiSearchDS(),l=s.serviceMap?.datasourceUid;let c=[{value:"traceqlSearch",label:"Search"},{value:"traceql",label:"TraceQL"},{value:"serviceMap",label:"Service Graph"}];return o&&(s?.search?.hide?c.unshift({value:"search",label:"Search"}):c.push({value:"search",label:"Loki Search"})),(e.spanName||e.serviceName||e.search||e.maxDuration||e.minDuration||e.queryType==="nativeSearch")&&c.unshift({value:"nativeSearch",label:"[Deprecated] Search"}),r.createElement(r.Fragment,null,r.createElement($.u,{title:"Upload trace",isOpen:this.state.uploadModalOpen,onDismiss:()=>this.setState({uploadModalOpen:!1})},r.createElement("div",{className:(0,v.css)({padding:this.props.theme.spacing(2)})},r.createElement(R.Yo,{options:{multiple:!1},onLoad:d=>{this.props.datasource.uploadedJson=d,a({...e,queryType:"upload"}),this.setState({uploadModalOpen:!1}),this.props.onRunQuery()}}))),r.createElement(x.Z,null,r.createElement(p._,{label:"Query type",grow:!0},r.createElement(f.Lh,{spacing:"sm",align:"center",justify:"space-between"},r.createElement(C.S,{options:c,value:e.queryType,onChange:d=>{(0,M.ff)("grafana_traces_query_type_changed",{datasourceType:"tempo",app:n??"",grafana_version:T.config.buildInfo.version,newQueryType:d,previousQueryType:e.queryType??""}),this.onClearResults(),a({...e,queryType:d})},size:"md"}),r.createElement(B.zx,{variant:"secondary",size:"sm",onClick:()=>{this.setState({uploadModalOpen:!0})}},"Import trace")))),e.queryType==="search"&&r.createElement(ee,{logsDatasourceUid:o,query:e,onRunQuery:this.onRunLinkedQuery,onChange:this.onChangeLinkedQuery}),e.queryType==="nativeSearch"&&r.createElement(ga,{datasource:this.props.datasource,query:e,onChange:a,onBlur:this.props.onBlur,onRunQuery:this.props.onRunQuery}),e.queryType==="traceqlSearch"&&r.createElement(ba,{datasource:this.props.datasource,query:e,onChange:a,onBlur:this.props.onBlur}),e.queryType==="serviceMap"&&r.createElement(Ca,{graphDatasourceUid:l,query:e,onChange:a}),e.queryType==="traceql"&&r.createElement(Ba,{datasource:this.props.datasource,query:e,onRunQuery:this.props.onRunQuery,onChange:a}))}}const za=(0,w.HE)(Ka);var Ga=i(77195),Ha=i(9058),Za=i(36859),Ya=i(83320),Ja=i(19010),qa=i(72699),xe=i(78102),Xa=Object.defineProperty,er=Object.defineProperties,tr=Object.getOwnPropertyDescriptors,xt=Object.getOwnPropertySymbols,ar=Object.prototype.hasOwnProperty,rr=Object.prototype.propertyIsEnumerable,It=(t,e,a)=>e in t?Xa(t,e,{enumerable:!0,configurable:!0,writable:!0,value:a}):t[e]=a,we=(t,e)=>{for(var a in e||(e={}))ar.call(e,a)&&It(t,a,e[a]);if(xt)for(var a of xt(e))rr.call(e,a)&&It(t,a,e[a]);return t},Ae=(t,e)=>er(t,tr(e));const nr=({config:t,onChange:e,className:a})=>{const s=l=>{e(Ae(we({},t),{jsonData:Ae(we({},t.jsonData),{keepCookies:l})}))},n=l=>{e(Ae(we({},t),{jsonData:Ae(we({},t.jsonData),{timeout:parseInt(l.currentTarget.value,10)})}))},o={container:(0,v.css)({maxWidth:578})};return r.createElement(xe._,{title:"Advanced HTTP settings",className:(0,v.cx)(o.container,a)},r.createElement(p._,{htmlFor:"advanced-http-cookies",label:"Allowed cookies",labelWidth:24,tooltip:"Grafana proxy deletes forwarded cookies by default. Specify cookies by name that should be forwarded to the data source.",disabled:t.readOnly,grow:!0},r.createElement(qa.B,{id:"advanced-http-cookies",placeholder:"New cookie (hit enter to add)",tags:t.jsonData.keepCookies,onChange:s})),r.createElement(p._,{htmlFor:"advanced-http-timeout",label:"Timeout",labelWidth:24,tooltip:"HTTP request timeout in seconds",disabled:t.readOnly,grow:!0},r.createElement(Ee.I,{id:"advanced-http-timeout",type:"number",min:0,placeholder:"Timeout in seconds","aria-label":"Timeout in seconds",value:t.jsonData.timeout,onChange:n})))};var sr=i(79510),Oe=i(47449),H=i(5562),ir=i(29126),Ze=i(51778),or=i(35977),lr=i(32042),K=i(17312),Ct=i(53229),Mt=i(42074),Pt=i(71654);function cr({options:t,onOptionsChange:e}){const a=(0,w.wW)(Re),s=o=>`Time shift for ${o} of search`,n=o=>`Shifts the ${o} 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`;return r.createElement("div",{className:a.container},r.createElement(p._,{label:"Use time range in query",tooltip:"The time range can be used when there are performance issues or timeouts since it will narrow down the search to the defined range. Default: disabled",labelWidth:26},r.createElement(Mt.x,{id:"enable-time-shift",value:t.jsonData.traceQuery?.timeShiftEnabled||!1,onChange:o=>{(0,K.tp)({onOptionsChange:e,options:t},"traceQuery",{...t.jsonData.traceQuery,timeShiftEnabled:o.currentTarget.checked})}})),r.createElement(Pt.w,{label:s("start"),tooltip:n("start"),value:t.jsonData.traceQuery?.spanStartTimeShift||"",disabled:!t.jsonData.traceQuery?.timeShiftEnabled,onChange:o=>{(0,K.tp)({onOptionsChange:e,options:t},"traceQuery",{...t.jsonData.traceQuery,spanStartTimeShift:o})},isInvalidError:Ze.Ny}),r.createElement(Pt.w,{label:s("end"),tooltip:n("end"),value:t.jsonData.traceQuery?.spanEndTimeShift||"",disabled:!t.jsonData.traceQuery?.timeShiftEnabled,onChange:o=>{(0,K.tp)({onOptionsChange:e,options:t},"traceQuery",{...t.jsonData.traceQuery,spanEndTimeShift:o})},isInvalidError:Ze.Ny}))}const Re=t=>({infoText:(0,v.css)`
    padding-bottom: ${t.spacing(2)};
    color: ${t.colors.text.secondary};
  `,container:(0,v.css)`
    width: 100%;
  `,row:(0,v.css)`
    align-items: baseline;
  `});function ur({options:t,onOptionsChange:e}){const a=(0,w.wW)(Re),s=t.jsonData.tracesToLogs?.lokiSearch!==!1?t.jsonData.tracesToLogs?.datasourceUid:void 0;return s&&t.jsonData.lokiSearch===void 0&&(0,K.tp)({onOptionsChange:e,options:t},"lokiSearch",{datasourceUid:s}),r.createElement("div",{className:a.container},r.createElement(x.Z,{className:a.row},r.createElement(p._,{tooltip:"The Loki data source with the service graph data",label:"Data source",labelWidth:26},r.createElement(Ct.q,{inputId:"loki-search-data-source-picker",pluginId:"loki",current:t.jsonData.lokiSearch?.datasourceUid,noDefault:!0,width:40,onChange:n=>(0,K.tp)({onOptionsChange:e,options:t},"lokiSearch",{datasourceUid:n.uid})})),t.jsonData.lokiSearch?.datasourceUid?r.createElement(B.zx,{type:"button",variant:"secondary",size:"sm",fill:"text",onClick:()=>{(0,K.tp)({onOptionsChange:e,options:t},"lokiSearch",{datasourceUid:void 0})}},"Clear"):null))}function dr({options:t,onOptionsChange:e}){const a=(0,w.wW)(Re);return r.createElement("div",{className:a.container},r.createElement(x.Z,{className:a.row},r.createElement(p._,{tooltip:"The Prometheus data source with the service graph data",label:"Data source",labelWidth:26},r.createElement(Ct.q,{inputId:"service-graph-data-source-picker",pluginId:"prometheus",current:t.jsonData.serviceMap?.datasourceUid,noDefault:!0,width:40,onChange:s=>(0,K.tp)({onOptionsChange:e,options:t},"serviceMap",{datasourceUid:s.uid})})),t.jsonData.serviceMap?.datasourceUid?r.createElement(B.zx,{type:"button",variant:"secondary",size:"sm",fill:"text",onClick:()=>{(0,K.tp)({onOptionsChange:e,options:t},"serviceMap",{datasourceUid:void 0})}},"Clear"):null))}function mr({options:t,onOptionsChange:e,datasource:a}){const s=async()=>{if(!a)throw new Error("Unable to retrieve datasource");try{await a.languageProvider.start()}catch(u){throw new Error(A(u.data.message,"Unable to query Tempo"))}},{error:n,loading:o}=(0,Z.Z)(s,[a,t]),l=(0,r.useCallback)(u=>{let g=t.jsonData.search?.filters;g||=[];const m=g.findIndex(S=>S.id===u.id);m>=0?g=lt(g,m,u):g.push(u),(0,K.tp)({onOptionsChange:e,options:t},"search",{...t.jsonData.search,filters:g})},[e,t]),c=u=>{(0,K.tp)({onOptionsChange:e,options:t},"search",{...t.jsonData.search,filters:t.jsonData.search?.filters?.filter(g=>g.id!==u.id)})};(0,r.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]);const d=["duration"];return r.createElement(r.Fragment,null,a?r.createElement(Dt,{updateFilter:l,deleteFilter:c,filters:t.jsonData.search?.filters||[],datasource:a,setError:()=>{},staticTags:d,isTagsLoading:o,hideValues:!0}):r.createElement("div",null,"Invalid data source, please create a valid data source and try again"),n&&r.createElement(ye.b,{title:"Unable to fetch TraceQL tags",severity:"error",topSpacing:1},n.message))}function gr({options:t,onOptionsChange:e}){const a=(0,w.wW)(Re),s=(0,le.F)(),n=async()=>await s.get({type:t.type,uid:t.uid}),{value:o}=(0,Z.Z)(n,[s,t]);return r.createElement("div",{className:a.container},r.createElement(x.Z,{className:a.row},r.createElement(p._,{tooltip:"Removes the search tab from the query editor",label:"Hide search",labelWidth:26},r.createElement(Mt.x,{id:"hideSearch",value:t.jsonData.search?.hide,onChange:l=>(0,K.tp)({onOptionsChange:e,options:t},"search",{...t.jsonData.search,hide:l.currentTarget.checked})}))),r.createElement(x.Z,{className:a.row},r.createElement(p._,{tooltip:"Configures which fields are available in the UI",label:"Static filters",labelWidth:26},r.createElement(mr,{datasource:o,options:t,onOptionsChange:e}))))}const pr=({options:t,onOptionsChange:e})=>{const a=(0,w.wW)(hr);return r.createElement("div",{className:a.container},r.createElement(Ga.j,{dataSourceName:"Tempo",docsLink:"https://grafana.com/docs/grafana/latest/datasources/tempo",hasRequiredFields:!1}),r.createElement(H.i,null),r.createElement(Ha.f,{config:t,onChange:e}),r.createElement(H.i,null),r.createElement(Za.g,{...(0,Ya.T2)({config:t,onChange:e})}),T.config.secureSocksDSProxyEnabled&&r.createElement(sr.i,{options:t,onOptionsChange:e}),r.createElement(H.i,null),r.createElement(Ze.dw,{options:t,onOptionsChange:e}),r.createElement(H.i,null),T.config.featureToggles.traceToMetrics?r.createElement(r.Fragment,null,r.createElement(or.Y,{options:t,onOptionsChange:e}),r.createElement(H.i,null)):null,r.createElement(Ja.K,{title:"Additional settings",description:"Additional settings are optional settings that can be configured for more control over your data source.",isCollapsible:!0,isInitiallyOpen:!1},r.createElement(nr,{config:t,onChange:e}),r.createElement(H.i,{hideLine:!0}),r.createElement(xe._,{title:"Service graph",description:r.createElement(Oe.W,{description:"Select a Prometheus data source that contains the service graph data.",suffix:"tempo/#service-graph",feature:"the service graph"})},r.createElement(dr,{options:t,onOptionsChange:e})),r.createElement(H.i,{hideLine:!0}),r.createElement(ir.I,{options:t,onOptionsChange:e}),r.createElement(H.i,{hideLine:!0}),r.createElement(xe._,{title:"Tempo search",description:r.createElement(Oe.W,{description:"Modify how traces are searched.",suffix:"tempo/#tempo-search",feature:"Tempo search"})},r.createElement(gr,{options:t,onOptionsChange:e})),r.createElement(H.i,{hideLine:!0}),r.createElement(xe._,{title:"Loki search",description:r.createElement(Oe.W,{description:"Select a Loki data source to search for traces. Derived fields must be configured in the Loki data source.",suffix:"tempo/#loki-search",feature:"Loki search"})},r.createElement(ur,{options:t,onOptionsChange:e})),r.createElement(H.i,{hideLine:!0}),r.createElement(xe._,{title:"TraceID query",description:r.createElement(Oe.W,{description:"Modify how TraceID queries are run.",suffix:"tempo/#traceid-query",feature:"the TraceID query"})},r.createElement(cr,{options:t,onOptionsChange:e})),r.createElement(H.i,{hideLine:!0}),r.createElement(lr.vc,{options:t,onOptionsChange:e})))},hr=t=>({container:(0,v.css)`
    label: container;
    margin-bottom: ${t.spacing(2)};
    max-width: 900px;
  `});var fr=i(35630);const vr=({payload:{dashboardId:t,orgId:e,grafanaVersion:a,queries:s}})=>{try{const n=s[fr.id];if(!n?.length)return;let o={grafana_version:a,dashboard_id:t,org_id:e,native_search_query_count:0,search_query_count:0,service_map_query_count:0,traceql_query_count:0,upload_query_count:0,native_search_queries_with_template_variables_count:0,search_queries_with_template_variables_count:0,service_map_queries_with_template_variables_count:0,traceql_queries_with_template_variables_count:0};for(const l of n)l.hide||(l.queryType==="nativeSearch"?(o.native_search_query_count++,(l.serviceName&&ne(l.serviceName)||l.spanName&&ne(l.spanName)||l.search&&ne(l.search)||l.minDuration&&ne(l.minDuration)||l.maxDuration&&ne(l.maxDuration))&&o.native_search_queries_with_template_variables_count++):l.queryType==="search"?(o.search_query_count++,l.linkedQuery&&l.linkedQuery.expr&&ne(l.linkedQuery.expr)&&o.search_queries_with_template_variables_count++):l.queryType==="serviceMap"?(o.service_map_query_count++,l.serviceMapQuery&&ne(l.serviceMapQuery)&&o.service_map_queries_with_template_variables_count++):l.queryType==="traceql"?(o.traceql_query_count++,ne(l.query)&&o.traceql_queries_with_template_variables_count++):l.queryType==="upload"&&o.upload_query_count++);(0,M.ff)("grafana_tempo_dashboard_loaded",o)}catch(n){console.error("error in tempo tracking handler",n)}},ne=t=>(0,ve.J)().containsTemplate(t),yr=new y.hf(Jt).setQueryEditor(za).setConfigEditor(pr).setQueryEditorHelp(N);(0,L.N$)().subscribe(h.Pl,vr)},80601:(oe,U,i)=>{var y;y={value:!0};var h=i(48314),L=i(27702),r=h.__importDefault(i(58281));function M(T,N){N===void 0&&(N=[]);var v=r.default(T,N,{loading:!0}),$=v[0],R=v[1];return L.useEffect(function(){R()},[R]),$}U.Z=M}}]);

//# sourceMappingURL=7963.42e022088475dcf3b17e.js.map