@stackone/olap 1.51.0 → 1.52.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +562 -1
- package/dist/index.d.cts +64 -7
- package/dist/index.d.mts +64 -7
- package/dist/index.mjs +562 -1
- package/package.json +2 -1
package/dist/index.mjs
CHANGED
|
@@ -1 +1,562 @@
|
|
|
1
|
-
import"./chunk-BhWHdk3m.mjs";import{convertKeysToCamelCase as e,exceedsSize as t,extractSchema as n,isMissing as r,isString as i}from"@stackone/utils";import{CensorType as a,redactFields as o,redactObject as s,redactUrl as c}from"@stackone/redaction";import{GetObjectCommand as l,HeadObjectCommand as u,PutObjectCommand as d,S3Client as f}from"@aws-sdk/client-s3";import{OTLPTraceExporter as p}from"@opentelemetry/exporter-trace-otlp-proto";import{resourceFromAttributes as m}from"@opentelemetry/resources";import{BasicTracerProvider as h,BatchSpanProcessor as g}from"@opentelemetry/sdk-trace-base";import{ATTR_SERVICE_NAME as _}from"@opentelemetry/semantic-conventions";import{ZodError as v,z as y}from"zod";import b from"node:http";import{HttpClient as x}from"@stackone/transport";const S={Action:`action`,Step:`step`,Unified:`unified`,Provider:`provider`},C={StartTime:`startTime`,EndTime:`endTime`,EventTime:`eventTime`,DurationMs:`durationMs`},w={Asc:`asc`,Desc:`desc`},T={Minute:`minute`,Hour:`hour`,Day:`day`,Week:`week`,Month:`month`},E={ConnectorKey:`connectorKey`,Success:`success`,ActionType:`actionType`,Mode:`mode`,Service:`service`,Resource:`resource`,ActionId:`actionId`,HttpMethod:`httpMethod`,AccountSecureId:`accountSecureId`,SourceType:`sourceType`,StatusCode:`statusCode`,OriginOwnerId:`originOwnerId`,SourceId:`sourceId`,IsBackground:`isBackground`},D={RequestTester:`REQUEST_TESTER`,ActionTester:`ACTION_TESTER`,Discode:`DISCODE`,Dashboard:`DASHBOARD`,Playground:`PLAYGROUND`,SDK:`SDK`,API:`API`,Scheduler:`SCHEDULER`,Webhook:`WEBHOOK`,Agent:`AGENT`,Application:`APPLICATION`,DataSync:`DATA_SYNC`,Internal:`INTERNAL`},O={HTTP:`HTTP`,MCP:`MCP`,ActionRPC:`ACTION_RPC`,WebSocket:`WEBSOCKET`},k={HTTP:`HTTP`,WebSocket:`WEBSOCKET`,SSE:`SSE`},A={APIKey:`API_KEY`,SessionToken:`SESSION_TOKEN`,UserSession:`USER_SESSION`,Cookie:`COOKIE`,Webhook:`WEBHOOK`,Signature:`SIGNATURE`},j=[`refresh_authentication`,`data_sync`,`test_action`,`webhook_setup`],M=[D.Scheduler,D.DataSync,D.Internal],N=[`data_sync`],P=[D.DataSync];function isBackgroundLog(e,t){return!!(e&&j.includes(e)||t&&M.includes(t))}function isDataSync(e,t){return!!(e&&N.includes(e)||t&&P.includes(t))}const safeSerialize=e=>{try{return JSON.stringify(e)}catch{return`[Unserializable payload]`}},F=[`x-datadog-parent-id`,`x-datadog-sampling-priority`,`x-datadog-tags`,`x-datadog-trace-id`,`x-forwarded-proto`,`x-forwarded-port`,`x-forwarded-for`,`x-amzn-trace-id`,`traceparent`,`tracestate`,`x-request-nonce`,`x-signing-method`,`x-signature`,`host`,`via`],I=[`application/octet-stream`,`application/pdf`,`application/msword`,`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,`application/vnd.ms-excel`,`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,`application/zip`,`application/x-zip-compressed`],L=[`image/`,`audio/`,`video/`,`application/vnd.`,`binary`];var AdvancedSink=class{#e;#t;#n;#r;constructor(e,t,n){this.#e=e,this.#t=t?.bucket,this.#n=t?.maxItemSizeBytes??10485760,this.#r=n}async initialize(){if(!this.#e){this.#r?.warning({message:`No s3 client provided, advanced sink will not function`,category:`AdvancedSink`});return}}requireBucket(){if(!this.#t)throw Error(`Advanced sink bucket is not configured`);return this.#t}async sendAction(e,t,n){return(await this.sendActions([{input:e,result:t}],n))[0]??null}async sendActions(e,t){let n=[];for(let{input:r,result:i}of e){if(this.#r?.debug({message:`Advanced sink called to send action`,category:`AdvancedSink`,context:{mode:r.mode,actionId:r.actionId,actionRunId:r.actionRunId,success:i.success,statusCode:i.statusCode,options:{enabled:t?.enabled,errorsOnly:t?.errorsOnly,includeBackground:t?.includeBackground,ttl:t?.ttl}}}),!t?.enabled){this.#r?.debug({message:`Advanced sink is disabled, skipping sending action to advanced sink`,category:`AdvancedSink`}),n.push(null);continue}if(isDataSync(r.mode,r.sourceType)){this.#r?.debug({message:`Advanced sink does not record data sync, skipping sending action to advanced sink`,category:`AdvancedSink`}),n.push(null);continue}if(t.errorsOnly&&i.success){this.#r?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful action for ${r.mode||`action`}`,category:`AdvancedSink`}),n.push(null);continue}if(isBackgroundLog(r.mode,r.sourceType)&&!t.includeBackground){this.#r?.debug({message:`Advanced sink is configured to exclude background logs, skipping action with mode ${r.mode}`,category:`AdvancedSink`}),n.push(null);continue}let e=this.createActionS3(r,i,t?.ttl),a=await this.send(e,t?.ttl);n.push(a)}return n}async sendStep(e,t,n){if(this.#r?.debug({message:`Advanced sink called to send step`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,success:t.success,options:{enabled:n?.enabled,errorsOnly:n?.errorsOnly,includeBackground:n?.includeBackground,ttl:n?.ttl}}}),!n?.enabled)return this.#r?.debug({message:`Advanced sink is disabled, skipping sending step to advanced sink`,category:`AdvancedSink`}),null;if(isDataSync(e.actionMode))return this.#r?.debug({message:`Advanced sink does not record data sync, skipping sending step to advanced sink`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,stepIndex:e.stepIndex}}),null;if(n.errorsOnly&&e.actionSuccess===!0)return this.#r?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful action for ${e.actionMode||`action`}`,category:`AdvancedSink`}),null;if(isBackgroundLog(e.actionMode)&&!n.includeBackground)return this.#r?.debug({message:`Advanced sink is configured to exclude background logs, skipping action with mode ${e.actionMode}`,category:`AdvancedSink`}),null;let r=this.createStepS3(e,t,n?.ttl);try{return await this.send(r,n?.ttl)}catch(t){return this.#r?.error({message:`Failed to send step to advanced sink`,error:t,code:`AdvancedStepWriteError`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,stepIndex:e.stepIndex}}),null}}async sendSteps(e,t){let n=[];for(let{input:r,result:i}of e){let e=await this.sendStep(r,i,t);n.push(e)}return n}async sendUnified(e,t,n){if(!n?.enabled)return this.#r?.debug({message:`Advanced sink is disabled, skipping sending unified to advanced sink`,category:`AdvancedSink`}),null;if(n.errorsOnly&&t.success)return this.#r?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful unified request`,category:`AdvancedSink`}),null;if(isBackgroundLog(e.mode,e.sourceType)&&!n.includeBackground)return this.#r?.debug({message:`Advanced sink is configured to exclude background logs, skipping unified with mode ${e.mode}`,category:`AdvancedSink`}),null;this.#r?.debug({message:`Sending unified to advanced sink`,category:`AdvancedSink`});let r=this.createUnifiedS3(e,t,n?.ttl);try{return await this.send(r,n?.ttl)}catch(t){return this.#r?.error({message:`Failed to send unified to advanced sink`,error:t,code:`AdvancedUnifiedWriteError`,category:`AdvancedSink`,context:{requestId:e.requestId}}),null}}async sendProvider(e,t,n){if(!n?.enabled)return this.#r?.debug({message:`Advanced sink is disabled, skipping sending provider to advanced sink`,category:`AdvancedSink`}),null;this.#r?.debug({message:`Sending provider to advanced sink`,category:`AdvancedSink`});let r=this.createProviderS3(e,t,n?.ttl);try{return await this.send(r,n?.ttl)}catch(t){return this.#r?.error({message:`Failed to send provider to advanced sink`,error:t,code:`AdvancedProviderWriteError`,category:`AdvancedSink`,context:{requestId:e.requestId}}),null}}async getAction(e,t,n){if(!this.#e){this.#r?.warning({message:`No s3 client available, cannot get action log from advanced sink`,category:`AdvancedSink`});return}let r=this.requireBucket();try{let i=new l({Bucket:r,Key:`${e}/${t}/${n}/${n}.json`}),a=await this.#e.send(i);if(!a.Body){this.#r?.warning({message:`Received empty body when trying to get action log from S3 for actionRunId ${n}`,category:`AdvancedSink`});return}let o=await a.Body.transformToString();return this.#r?.debug({message:`Successfully retrieved advanced log from S3 for actionRunId ${n}`,category:`AdvancedSink`}),JSON.parse(o)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#r?.debug({message:`Advanced log not found in S3 for actionRunId ${n}`,category:`AdvancedSink`});return}throw this.#r?.error({message:`Error when getting advanced log from S3 for actionRunId ${n}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async getStep(e,t,n,r){if(!this.#e){this.#r?.warning({message:`No s3 client available, cannot get step log from advanced sink`,category:`AdvancedSink`});return}let i=this.requireBucket();try{let a=new l({Bucket:i,Key:`${e}/${t}/${n}/steps/${r}.json`}),o=await this.#e.send(a);if(!o.Body){this.#r?.warning({message:`Received empty body when trying to get step log from S3 for actionRunId ${n} stepIndex ${r}`,category:`AdvancedSink`});return}let s=await o.Body.transformToString();return this.#r?.debug({message:`Successfully retrieved step log from S3 for actionRunId ${n} stepIndex ${r}`,category:`AdvancedSink`}),JSON.parse(s)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#r?.debug({message:`Step log not found in S3 for actionRunId ${n} stepIndex ${r}`,category:`AdvancedSink`});return}throw this.#r?.error({message:`Error when getting step log from S3 for actionRunId ${n} stepIndex ${r}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async getUnified(e,t,n){if(!this.#e){this.#r?.warning({message:`No s3 client available, cannot get unified log from advanced sink`,category:`AdvancedSink`});return}let r=this.requireBucket();try{let i=new l({Bucket:r,Key:`${e}/${t}/${n}/${n}.json`}),a=await this.#e.send(i);if(!a.Body){this.#r?.warning({message:`Received empty body when trying to get unified log from S3 for requestId ${n}`,category:`AdvancedSink`});return}let o=await a.Body.transformToString();return this.#r?.debug({message:`Successfully retrieved advanced log from S3 for requestId ${n}`,category:`AdvancedSink`}),JSON.parse(o)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#r?.debug({message:`Advanced log not found in S3 for requestId ${n}`,category:`AdvancedSink`});return}throw this.#r?.error({message:`Error when getting advanced log from S3 for requestId ${n}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async getProvider(e,t,n,r){if(!this.#e){this.#r?.warning({message:`No s3 client available, cannot get provider log from advanced sink`,category:`AdvancedSink`});return}let i=this.requireBucket();try{let a=new l({Bucket:i,Key:`${e}/${t}/${n}/provider/${r}.json`}),o=await this.#e.send(a);if(!o.Body){this.#r?.warning({message:`Received empty body when trying to get provider log from S3 for requestId ${n} id ${r}`,category:`AdvancedSink`});return}let s=await o.Body.transformToString();return this.#r?.debug({message:`Successfully retrieved provider log from S3 for requestId ${n} id ${r}`,category:`AdvancedSink`}),JSON.parse(s)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#r?.debug({message:`Provider log not found in S3 for requestId ${n} id ${r}`,category:`AdvancedSink`});return}throw this.#r?.error({message:`Error when getting provider log from S3 for requestId ${n} id ${r}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async send(e,t){if(!this.#e)throw Error(`No s3 client available, cannot send to advanced sink`);let n=this.requireBucket(),r=`ttl=30d`;typeof t==`number`&&(t===1?r=`ttl=1d`:t===7&&(r=`ttl=7d`));let i=Math.floor(Date.now()/1e3)+(t??30)*24*60*60,a=new Date(i*1e3);this.#r?.debug({message:`Storing advanced log in S3 bucket ${n} with ttl of ${r}`,category:`AdvancedSink`,context:{bucket:n,key:e.Key,ttlTag:r,expiresAt:a.toISOString()}});try{return await this.#e.send(new d({Bucket:n,Key:e.Key,Body:e.Body,ContentType:e.ContentType,Expires:a,Tagging:r})),{expiresAt:a}}catch(t){throw this.#r?.error({message:`Failed to write advanced logs to S3 at ${e.Key}`,error:t,code:`AdvancedLogWriteError`,category:`AdvancedSink`}),t}}async getObjectExpiry(e){if(!this.#e)return this.#r?.warning({message:`No s3 client available, cannot check object expiry`,category:`AdvancedSink`}),{exists:!1};let t=this.requireBucket();try{return{exists:!0,expiresAt:(await this.#e.send(new u({Bucket:t,Key:e}))).Expires}}catch(t){let n=t;if(n.name===`NotFound`||n.$metadata?.httpStatusCode===404)return this.#r?.debug({message:`Object not found in S3 for key ${e}`,category:`AdvancedSink`}),{exists:!1};throw this.#r?.error({message:`Error when checking object expiry in S3 for key ${e}`,error:t,code:`AdvancedLogHeadError`,category:`AdvancedSink`}),t}}async hasAction(e,t,n){let r=`${e}/${t}/${n}/${n}.json`;return this.getObjectExpiry(r)}async hasUnified(e,t,n){let r=`${e}/${t}/${n}/${n}.json`;return this.getObjectExpiry(r)}createActionS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.actionRunId}/${e.actionRunId}.json`,i=Math.floor(Date.now()/1e3)+(n??30)*24*60*60;return{Key:r,Body:this.serializeActionResult(e,t,i,this.#n),ContentType:`application/json`,Expires:new Date(i*1e3)}}createStepS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.actionRunId}/steps/${e.stepIndex}.json`,i=Math.floor(Date.now()/1e3)+(n??30)*24*60*60;return{Key:r,Body:this.serializeStepResult(e,t,i,this.#n),ContentType:`application/json`,Expires:new Date(i*1e3)}}createUnifiedS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.requestId}/${e.requestId}.json`,i=Math.floor(Date.now()/1e3)+(n??30)*24*60*60;return{Key:r,Body:this.serializeUnifiedResult(e,t,i,this.#n),ContentType:`application/json`,Expires:new Date(i*1e3)}}createProviderS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.requestId}/provider/${e.id}.json`,i=Math.floor(Date.now()/1e3)+(n??30)*24*60*60;return{Key:r,Body:this.serializeProviderResult(e,t,i,this.#n),ContentType:`application/json`,Expires:new Date(i*1e3)}}serializeActionResult(e,t,n,r){let i=s({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},a.PARTIAL),l=i.req?.headers,u=i.res?.headers,d=o(e.body,a.PARTIAL,!0),f=o(t.body,a.PARTIAL,!0),p=this.processContent(l,d,`upload`),m=this.processContent(u,f,`download`),h=e.isBackground??isBackgroundLog(e.mode,e.sourceType),g=e.url,_={};if(e.url)try{g=c(e.url,a.PARTIAL);let t=new URL(g);_=Object.fromEntries(t.searchParams)}catch{this.#r?.warning({message:`Invalid URL in action request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{actionRunId:e.actionRunId,actionId:e.actionId}})}let v={data:{request:{actionRunId:e.actionRunId,actionId:e.actionId,method:e.httpMethod,headers:this.filterHeaders(l),url:{url:g,path:e.pathParams,queryParams:_},body:p},response:{statusCode:t.statusCode??500,headers:this.filterHeaders(u),body:m},...h?{isBackgroundLog:!0}:{}},metadata:{...h?{isBackgroundLog:!0}:{},expirationTime:n}};return this.serializeAndLimit(v,r)}serializeStepResult(e,t,n,r){let i={data:{actionRunId:e.actionRunId,stepIndex:e.stepIndex,stepId:e.stepId,input:e.inputs,outputs:t.outputs,errors:t.errors},metadata:{expirationTime:n}};return this.serializeAndLimit(i,r)}serializeUnifiedResult(e,t,n,r){let i=s({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},a.PARTIAL),l=i.req?.headers,u=i.res?.headers,d=o(e.body,a.PARTIAL,!0),f=o(t.body,a.PARTIAL,!0),p=this.processContent(l,d,`upload`),m=this.processContent(u,f,`download`),h=e.isBackground??isBackgroundLog(e.mode,e.sourceType),g=`/`,_=e.url,v={};if(e.url)try{_=c(e.url,a.PARTIAL);let t=new URL(_);g=t.pathname,v=Object.fromEntries(t.searchParams)}catch{this.#r?.warning({message:`Invalid URL in unified request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{requestId:e.requestId}})}let y={data:{request:{id:e.requestId,method:e.httpMethod,headers:this.filterHeaders(l),url:{url:_,path:g,queryParams:v},body:p},response:{statusCode:t.statusCode??500,headers:this.filterHeaders(u),body:m}},metadata:{...h?{isBackgroundLog:!0}:{},expirationTime:n}};return this.serializeAndLimit(y,r)}serializeProviderResult(e,t,n,r){let i=s({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},a.PARTIAL),l=i.req?.headers,u=i.res?.headers,d=o(e.body,a.PARTIAL,!0),f=o(t.body,a.PARTIAL,!0),p=this.processContent(l,d,`upload`),m=this.processContent(u,f,`download`),h,g=``,_=`/`,v={};if(e.url)try{h=c(e.url,a.PARTIAL);let t=new URL(h);g=t.hostname,_=t.pathname,v=Object.fromEntries(t.searchParams)}catch{this.#r?.warning({message:`Invalid URL in provider request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{requestId:e.requestId,id:e.id}})}let y={data:{request:{id:e.id,method:e.httpMethod,headers:this.filterHeaders(l),url:{url:h,hostname:g,path:_,queryParams:v},body:p},response:{statusCode:t.statusCode,headers:this.filterHeaders(u),body:m}},metadata:{expirationTime:n}};return this.serializeAndLimit(y,r)}serializeAndLimit(e,n){if(t(e,n)){let t={...e,data:{outputs:{error:`Error.TOO_LARGE`}}};return JSON.stringify(t)}return JSON.stringify(e)}filterHeaders(e){if(!e)return;let t={},n=F.map(e=>e.toLowerCase());for(let[r,i]of Object.entries(e))n.includes(r.toLowerCase())||(t[r]=i);return t}processContent(e,t,n){let r=this.getContentType(e);if(!r)return this.parseJsonSafely(t);let i=r.toLowerCase().split(`;`)[0].trim();return I.includes(i)||L.some(e=>i.startsWith(e))?{type:`binary`,action:n,contentType:r}:this.parseJsonSafely(t)}parseJsonSafely(e){if(!r(e)){if(!i(e))return e;try{return JSON.parse(e)}catch{return e}}}getContentType(e){if(!e)return;let t=[`content-type`,`contenttype`];return Object.entries(e).find(([e])=>t.includes(e.toLowerCase()))?.[1]?.toString()}};function defaultProviderFactory(e){let t=new p({url:`${e.baseUrl??`https://logfire-eu.pydantic.dev`}/v1/traces`,headers:{Authorization:`Bearer ${e.token}`}}),n={[_]:e.serviceName??`stackone-olap`};return e.environment&&(n[`deployment.environment.name`]=e.environment),e.region&&(n[`cloud.region`]=e.region),new h({resource:m(n),spanProcessors:[new g(t)]})}var LogfireEmitter=class{#e;#t;#n;#r;constructor(e,t,n=defaultProviderFactory){this.#e=e,this.#t=t,this.#n=n}configure(){if(this.#e.token)try{this.#r=this.#n(this.#e)}catch(e){this.#t?.warning({message:`Failed to configure Logfire`,error:e,code:`LogfireConfigureError`,category:`DatasetsSink`})}}emit(e,t){if(this.#r)try{let n=this.#r.getTracer(`stackone-olap`).startSpan(e);for(let[e,r]of Object.entries(t))r!=null&&(typeof r==`string`||typeof r==`number`||typeof r==`boolean`||Array.isArray(r)&&r.every(e=>typeof e==`string`)?n.setAttribute(e,r):n.setAttribute(e,JSON.stringify(r)));n.end()}catch(e){this.#t?.warning({message:`Failed to emit dataset log to Logfire`,error:e,code:`LogfireEmitError`,category:`DatasetsSink`})}}async flush(){if(this.#r)try{await this.#r.forceFlush()}catch(e){this.#t?.warning({message:`Failed to flush dataset logs to Logfire`,error:e,code:`LogfireFlushError`,category:`DatasetsSink`})}}},DatasetsSink=class{#e;#t;#n;#r;#i;constructor(e,t,n){this.#e=e?.logfire??{},this.#t=e?.logfire!==void 0,this.#n=e?.maxItemSizeBytes??1048576,this.#r=n??new LogfireEmitter(this.#e,t),this.#i=t}async initialize(){if(!this.#e.token){this.#t&&this.#i?.warning({message:`Logfire configured without a token, datasets sink will not emit`,category:`DatasetsSink`});return}this.#r.configure()}async sendAction(e,t,n){await this.sendActions([{input:e,result:t}],n)}async sendActions(e,n){if(!n?.enabled){this.#i?.debug({message:`Datasets sink is disabled, skipping sending actions to datasets sink`,category:`DatasetsSink`});return}let i=0;for(let{input:a,result:o}of e){if(this.#i?.debug({message:`Datasets sink called to send action`,category:`DatasetsSink`,context:{mode:a.mode,actionId:a.actionId,actionRunId:a.actionRunId,success:o.success,statusCode:o.statusCode,includeBackground:n.includeBackground}}),r(a.body)&&r(o.body)){this.#i?.debug({message:`No body in action result, skipping sending action to datasets sink`,category:`DatasetsSink`,context:{actionRunId:a.actionRunId}});continue}if(isBackgroundLog(a.mode,a.sourceType)&&!n.includeBackground){this.#i?.debug({message:`Datasets sink is configured to exclude background logs, skipping action with mode ${a.mode}`,category:`DatasetsSink`});continue}let e=this.createSchemaLog(a,o);if(r(e)){this.#i?.debug({message:`No schema extracted from action, skipping`,category:`DatasetsSink`,context:{actionRunId:a.actionRunId}});continue}if(t(e,this.#n)){this.#i?.debug({message:`Dataset schema log exceeds ${this.#n} bytes, skipping`,category:`DatasetsSink`,context:{actionRunId:a.actionRunId}});continue}this.send(a,e),i++}i>0&&(await this.#r.flush(),this.#i?.debug({message:`Sent ${i} schema log(s) to logfire`,category:`DatasetsSink`}))}send(e,t){this.#i?.debug({message:`Emitting schema log to Logfire`,category:`DatasetsSink`,context:{actionRunId:e.actionRunId,actionId:e.actionId}}),this.#r.emit(`dataset.schema`,t)}createSchemaLog(e,t){let i=r(e.body)?void 0:n(e.body),a=r(t.body)?void 0:n(t.body);if(!(r(i)&&r(a)))return{organizationId:e.organizationId,projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,connectorKey:e.connectorKey,connectorVersion:e.connectorVersion,actionId:e.actionId,schemas:{input:i,result:a}}}},DefenderSink=class{#e;#t;#n;#r;constructor(e,t,n){this.#e=e,this.#t=t?.bucket,this.#n=t?.ttlDays??365,this.#r=n}requireBucket(){if(!this.#t)throw Error(`Defender sink bucket is not configured`);return this.#t}async initialize(){if(!this.#e){this.#r?.warning({message:`No s3 client provided, defender sink will not function`,category:`DefenderSink`});return}}async sendAction(e,t,n){return(await this.sendActions([{input:e,result:t}],n))[0]??null}async sendActions(e,t){let n=[];for(let{input:i,result:a}of e){if(this.#r?.debug({message:`Defender sink called to send action`,category:`DefenderSink`,context:{mode:i.mode,actionId:i.actionId,actionRunId:i.actionRunId,success:a.success,statusCode:a.statusCode,options:{enabled:t?.enabled}}}),!t?.enabled){this.#r?.debug({message:`Defender sink is disabled, skipping sending action to defender sink`,category:`DefenderSink`}),n.push(null);continue}if(r(a.defenderContext)){this.#r?.debug({message:`No defender context in action result, skipping sending action to defender sink`,category:`DefenderSink`,context:{actionRunId:i.actionRunId}}),n.push(null);continue}let e=this.createDefenderS3(i,a),o=await this.send(e);n.push(o)}return n}async getAction(e,t,n){if(!this.#e){this.#r?.warning({message:`No s3 client available, cannot get action log from defender sink`,category:`DefenderSink`});return}let r=this.requireBucket();try{let i=new l({Bucket:r,Key:this.generateS3Key(e,t,n)}),a=await this.#e.send(i);if(!a.Body){this.#r?.warning({message:`Received empty body when trying to get action log from S3 for actionRunId ${n}`,category:`DefenderSink`});return}let o=await a.Body.transformToString();return this.#r?.debug({message:`Successfully retrieved defender log from S3 for actionRunId ${n}`,category:`DefenderSink`}),JSON.parse(o)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#r?.debug({message:`Defender log not found in S3 for actionRunId ${n}`,category:`DefenderSink`});return}throw this.#r?.error({message:`Error when getting defender log from S3 for actionRunId ${n}`,error:e,code:`DefenderLogReadError`,category:`DefenderSink`}),e}}async send(e){if(!this.#e)throw Error(`No s3 client available, cannot send to defender sink`);let t=this.requireBucket(),n=Math.floor(Date.now()/1e3)+this.#n*24*60*60,r=new Date(n*1e3),i=`ttl=${this.#n}d`;this.#r?.debug({message:`Storing defender log in S3 bucket ${t} with ${this.#n}-day TTL`,category:`DefenderSink`,context:{bucket:t,key:e.Key,ttlTag:i,expiresAt:r.toISOString()}});try{return await this.#e.send(new d({Bucket:t,Key:e.Key,Body:e.Body,ContentType:e.ContentType,Expires:r,Tagging:i})),{expiresAt:r}}catch(t){throw this.#r?.error({message:`Failed to write defender logs to S3 at ${e.Key}`,error:t,code:`DefenderLogWriteError`,category:`DefenderSink`}),t}}generateS3Key(e,t,n){return`${e}/${t}/${n}/defender.json`}createDefenderS3(e,t){let n=e.organizationId,r=e.projectSecureId;return{Key:this.generateS3Key(n,r,e.actionRunId),Body:JSON.stringify(t.defenderContext),ContentType:`application/json`}}};const hasTimezone=e=>/Z$|[+-]\d{2}:\d{2}$|[+-]\d{4}$/.test(e),utcDateTransform=e=>{if(hasTimezone(e))return e;let t=e.replace(` `,`T`);return new Date(t+`Z`).toISOString()},R=y.preprocess(e=>{if(e instanceof Date)return e;if(typeof e==`string`&&e.length>0)try{return new Date(utcDateTransform(e))}catch(e){throw new y.ZodError([{code:y.ZodIssueCode.custom,path:[],message:e instanceof Error?e.message:`Invalid date string`}])}return e},y.coerce.date()),z=y.object({logType:y.enum([`action`,`step`,`unified`,`provider`]),eventTime:R,startTime:R,endTime:R.optional().nullable().transform(e=>e??void 0),durationMs:y.coerce.number().optional().nullable().transform(e=>e??void 0),organizationId:y.coerce.string(),projectSecureId:y.coerce.string().optional().nullable().transform(e=>e??void 0),accountSecureId:y.coerce.string().optional().nullable().transform(e=>e??void 0)}),B=z.extend({logType:y.literal(`action`),actionRunId:y.coerce.string(),actionId:y.coerce.string(),connectorKey:y.coerce.string(),connectorVersion:y.coerce.string(),connectorOwner:y.coerce.string().optional().nullable().transform(e=>e??void 0),connectorProfileId:y.coerce.string().optional().nullable().transform(e=>e??void 0),projectSecureId:y.coerce.string(),accountSecureId:y.coerce.string(),actionType:y.coerce.string().optional().nullable().transform(e=>e??void 0),mode:y.coerce.string().optional().nullable().transform(e=>e??void 0),category:y.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerId:y.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:y.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:y.coerce.string().optional().nullable().transform(e=>e??void 0),url:y.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:y.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:y.coerce.string().optional().nullable().transform(e=>e??void 0),sourceValue:y.coerce.string().optional().nullable().transform(e=>e??void 0),authType:y.coerce.string().optional().nullable().transform(e=>e??void 0),authId:y.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:y.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:y.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:y.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:y.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:y.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:y.coerce.string().optional().nullable().transform(e=>e??void 0),success:y.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:y.coerce.number().optional().nullable().transform(e=>e??void 0),riskLevel:y.coerce.string().optional().nullable().transform(e=>e??void 0),tier2Score:y.coerce.number().optional().nullable().transform(e=>e??void 0),isBackground:y.coerce.boolean().optional().nullable().transform(e=>e??void 0),advancedExpiresAt:R.optional().nullable().transform(e=>e??void 0),defenderExpiresAt:R.optional().nullable().transform(e=>e??void 0)}),V=z.extend({logType:y.literal(`step`),actionRunId:y.coerce.string(),stepIndex:y.coerce.number(),stepId:y.coerce.string(),projectSecureId:y.coerce.string(),accountSecureId:y.coerce.string(),skipped:y.coerce.boolean().optional().nullable().transform(e=>e??void 0),success:y.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:y.coerce.number().optional().nullable().transform(e=>e??void 0),message:y.coerce.string().optional().nullable().transform(e=>e??void 0),stepFunctionName:y.coerce.string().optional().nullable().transform(e=>e??void 0),stepFunctionVersion:y.coerce.string().optional().nullable().transform(e=>e??void 0),stepIterations:y.coerce.number().optional().nullable().transform(e=>e??void 0)}),H=z.extend({logType:y.literal(`unified`),requestId:y.coerce.string(),connectorKey:y.coerce.string(),connectorVersion:y.coerce.string().optional().nullable().transform(e=>e??void 0),connectorOwner:y.coerce.string().optional().nullable().transform(e=>e??void 0),projectSecureId:y.coerce.string(),accountSecureId:y.coerce.string(),mode:y.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:y.coerce.string().optional().nullable().transform(e=>e??void 0),url:y.coerce.string().optional().nullable().transform(e=>e??void 0),path:y.coerce.string().optional().nullable().transform(e=>e??void 0),resource:y.coerce.string().optional().nullable().transform(e=>e??void 0),subResource:y.coerce.string().optional().nullable().transform(e=>e??void 0),childResource:y.coerce.string().optional().nullable().transform(e=>e??void 0),service:y.coerce.string().optional().nullable().transform(e=>e??void 0),action:y.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:y.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:y.coerce.string().optional().nullable().transform(e=>e??void 0),sourceValue:y.coerce.string().optional().nullable().transform(e=>e??void 0),authType:y.coerce.string().optional().nullable().transform(e=>e??void 0),authId:y.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:y.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:y.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:y.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:y.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:y.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:y.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerId:y.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:y.coerce.string().optional().nullable().transform(e=>e??void 0),statusCode:y.coerce.number().optional().nullable().transform(e=>e??void 0),success:y.coerce.boolean().optional().nullable().transform(e=>e??void 0),isWorker:y.coerce.boolean().optional().nullable().transform(e=>e??void 0),isBackground:y.coerce.boolean().optional().nullable().transform(e=>e??void 0),status:y.coerce.number().optional().nullable().transform(e=>e??void 0),provider:y.coerce.string().optional().nullable().transform(e=>e??void 0),eventDatetime:R.optional().nullable().transform(e=>e??void 0),duration:y.coerce.number().optional().nullable().transform(e=>e??void 0),advancedExpiresAt:R.optional().nullable().transform(e=>e??void 0)}),U=z.extend({logType:y.literal(`provider`),requestId:y.coerce.string(),id:y.coerce.string().optional().nullable().transform(e=>e??void 0),action:y.coerce.string(),mode:y.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:y.coerce.string(),originOwnerId:y.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:y.coerce.string().optional().nullable().transform(e=>e??void 0),url:y.coerce.string(),path:y.coerce.string().optional().nullable().transform(e=>e??void 0),connectorKey:y.coerce.string(),connectorVersion:y.coerce.string().optional().nullable().transform(e=>e??void 0),resource:y.coerce.string().optional().nullable().transform(e=>e??void 0),subResource:y.coerce.string().optional().nullable().transform(e=>e??void 0),childResource:y.coerce.string().optional().nullable().transform(e=>e??void 0),service:y.coerce.string().optional().nullable().transform(e=>e??void 0),success:y.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:y.coerce.number().optional().nullable().transform(e=>e??void 0),isWorker:y.coerce.boolean().optional().nullable().transform(e=>e??void 0),projectSecureId:y.coerce.string(),accountSecureId:y.coerce.string(),status:y.coerce.number().optional().nullable().transform(e=>e??void 0),provider:y.coerce.string().optional().nullable().transform(e=>e??void 0),eventDatetime:R.optional().nullable().transform(e=>e??void 0),duration:y.coerce.number().optional().nullable().transform(e=>e??void 0)}),W=y.discriminatedUnion(`logType`,[B,V,H,U]);var SchemaValidationError=class extends Error{constructor(e,t){super(e),this.name=`SchemaValidationError`,this.cause=t}},TinybirdClient=class{#e;#t;#n;constructor(e,t,n){this.#e=e,this.#t=t,this.#n=n}async query(e){try{let t=await this.#o(e.endpoint,e.params);return this.#a(t.data,e.schema)}catch(t){if(t instanceof SchemaValidationError)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error querying Tinybird endpoint ${e.endpoint}: ${n}`,category:`TinybirdClient`,code:`TinybirdQueryError`}),t}}async queryWithPagination(e){try{let t=await this.#o(e.endpoint,e.params),n=this.#a(t.data,e.schema);return{data:n,total:t.rows_before_limit_at_least??t.rows??n.length,pageNumber:e.pageNumber??1,pageSize:e.pageSize??n.length}}catch(t){if(t instanceof SchemaValidationError)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error querying Tinybird endpoint ${e.endpoint}: ${n}`,category:`TinybirdClient`,code:`TinybirdQueryError`}),t}}async queryRaw(e){try{let t=await this.#o(e.endpoint,e.params);return t.data=this.#a(t.data,e.schema),t}catch(t){if(t instanceof SchemaValidationError)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error querying Tinybird endpoint ${e.endpoint}: ${n}`,category:`TinybirdClient`,code:`TinybirdQueryError`}),t}}isReady(){return!!(this.#e&&this.#t?.token)}#r(){return new b.Agent({})}#i(){if(!this.#e)throw this.#n?.error({message:`HTTP client not initialized, cannot perform Tinybird query`,category:`TinybirdClient`,code:`HttpClientNotReady`}),Error(`HTTP client is not initialized`);if(!this.#t?.token)throw this.#n?.warning({message:`Missing OLAP token, cannot perform Tinybird query`,category:`TinybirdClient`}),Error(`TinybirdClient - Missing token`)}#a(e,t){if(!t)return e;try{let n=e.map(e=>t.parse(e));return this.#n?.debug({message:`Schema validation passed for ${n.length} rows`,category:`TinybirdClient`}),n}catch(e){let t=e instanceof Error?e.message:String(e);throw this.#n?.error({message:`Schema validation failed: ${t}`,category:`TinybirdClient`,code:`SchemaValidationError`,error:e}),new SchemaValidationError(t,e)}}async#o(e,t){this.#i();let n=this.#e,r=this.#t;if(!n||!r)throw Error(`Client validation failed`);let i=new URL(`/v0/pipes/${e}`,r.baseUrl);this.#n?.debug({message:`Querying Tinybird endpoint: ${e}`,category:`TinybirdClient`,context:{endpoint:e,params:t}});let a=await n.request({method:`post`,url:i.toString(),payload:t,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${r.token}`},...r.allowHttp&&{httpAgent:this.#r()}});return this.#n?.debug({message:`Tinybird query returned ${a.data.data.length} rows`,category:`TinybirdClient`,context:{endpoint:e,rows:a.data.rows,statistics:a.data.statistics}}),a.data}},LogsSink=class{#e;#t;#n;constructor(e,t,n,r){this.#e=e,this.#n=r,this.#t=new TinybirdClient(t,n,r)}async initialize(){if(!this.#e){this.#n?.warning({message:`No kafka producer provided, logs sink cannot be initialized`,category:`LogsSink`});return}this.#t?.isReady()||this.#n?.warning({message:`Tinybird client is not ready (missing HTTP client or Tinybird config/token), logs sink will not be able to query`,category:`LogsSink`}),this.#n?.info({message:`Logs sink kafka producer initialized`,category:`LogsSink`})}async sendAction(e,t,n,r){await this.sendActions([{input:e,result:t,metadata:n}],r)}async sendActions(e,t){if(!t?.enabled){this.#n?.debug({message:`Logs sink is disabled, skipping sending ${e.length} actions to log sink`,category:`LogsSink`});return}if(e.length===0)return;let n=e.map(({input:e,result:t,metadata:n})=>this.buildActionLog(e,t,n));await this.send(`actions`,n)}async sendStep(e,t,n){await this.sendSteps([{input:e,result:t}],n)}async sendSteps(e,t){if(!t?.enabled){this.#n?.debug({message:`Logs sink is disabled, skipping sending ${e.length} steps to log sink`,category:`LogsSink`});return}if(e.length===0)return;let n=e.map(({input:e,result:t})=>this.buildStepLog(e,t));await this.send(`steps`,n)}async sendUnified(e,t,n,r){if(!r?.enabled){this.#n?.debug({message:`Logs sink is disabled, skipping sending unified to log sink`,category:`LogsSink`});return}this.#n?.debug({message:`Sending unified to log sink (topic: unified_requests)`,category:`LogsSink`});let i=this.buildUnifiedLog(e,t,n);await this.send(`unified_requests`,[i])}async sendProvider(e,t,n){if(!n?.enabled){this.#n?.debug({message:`Logs sink is disabled, skipping sending provider to log sink`,category:`LogsSink`});return}this.#n?.debug({message:`Sending provider to log sink (topic: provider_requests)`,category:`LogsSink`});let r=this.buildProviderLog(e,t);await this.send(`provider_requests`,[r])}async getLogs(e){try{this.#n?.info({message:`Querying logs from Tinybird`,category:`LogsSink`,context:{query:e}});let t=await this.#t?.queryWithPagination({endpoint:`project_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return t?(this.#n?.info({message:`Successfully retrieved ${t.data.length} logs from Tinybird (${t.total} total)`,category:`LogsSink`}),{logs:this.validateLogs(t.data),total:t.total,pageNumber:t.pageNumber,pageSize:t.pageSize}):(this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`}),{logs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return this.#t?.isReady()?this.#n?.warning({message:`Failed to query Tinybird for logs, returning empty results`,category:`LogsSink`,error:t}):this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`,error:t}),{logs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getActions(e){try{this.#n?.info({message:`Querying action logs from Tinybird`,category:`LogsSink`,context:{query:e}});let t=await this.#t?.queryWithPagination({endpoint:`project_action_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return t?(this.#n?.info({message:`Successfully retrieved ${t.data.length} action logs from Tinybird (${t.total} total)`,category:`LogsSink`}),{actionLogs:this.validateLogsWithSchema(t.data,B),total:t.total,pageNumber:t.pageNumber,pageSize:t.pageSize}):(this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`}),{actionLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return this.#t?.isReady()?this.#n?.warning({message:`Failed to query Tinybird for action logs, returning empty results`,category:`LogsSink`,error:t}):this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`,error:t}),{actionLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getAction(e,t,n){return(await this.getActions({organizationId:e,projectSecureId:t,actionRunId:n})).actionLogs[0]}async getSteps(e){try{this.#n?.info({message:`Querying step logs from Tinybird`,category:`LogsSink`,context:{query:e}});let t=await this.#t?.queryWithPagination({endpoint:`project_step_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return t?(this.#n?.info({message:`Successfully retrieved ${t.data.length} step logs from Tinybird (${t.total} total)`,category:`LogsSink`}),{stepLogs:this.validateLogsWithSchema(t.data,V),total:t.total,pageNumber:t.pageNumber,pageSize:t.pageSize}):(this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`}),{stepLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`,error:t}),{stepLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getStep(e,t,n,r){return(await this.getSteps({organizationId:e,projectSecureId:t,actionRunId:n,stepIndex:r})).stepLogs[0]}async getUnifiedLogs(e){try{this.#n?.info({message:`Querying unified logs from Tinybird`,category:`LogsSink`,context:{query:e}});let t=await this.#t?.queryWithPagination({endpoint:`project_unified_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return t?(this.#n?.info({message:`Successfully retrieved ${t.data.length} unified logs from Tinybird (${t.total} total)`,category:`LogsSink`}),{unifiedLogs:this.validateLogsWithSchema(t.data,H),total:t.total,pageNumber:t.pageNumber,pageSize:t.pageSize}):(this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`}),{unifiedLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return this.#t?.isReady()?this.#n?.warning({message:`Failed to query Tinybird for unified logs, returning empty results`,category:`LogsSink`,error:t}):this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`,error:t}),{unifiedLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getUnifiedLog(e,t,n){return(await this.getUnifiedLogs({organizationId:e,projectSecureId:t,requestId:n})).unifiedLogs[0]}async getProviderLogs(e){try{this.#n?.info({message:`Querying provider logs from Tinybird`,category:`LogsSink`,context:{query:e}});let t=await this.#t?.queryWithPagination({endpoint:`project_provider_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return t?(this.#n?.info({message:`Successfully retrieved ${t.data.length} provider logs from Tinybird (${t.total} total)`,category:`LogsSink`}),{providerLogs:this.validateLogsWithSchema(t.data,U),total:t.total,pageNumber:t.pageNumber,pageSize:t.pageSize}):(this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`}),{providerLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return this.#t?.isReady()?this.#n?.warning({message:`Failed to query Tinybird for provider logs, returning empty results`,category:`LogsSink`,error:t}):this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`,error:t}),{providerLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getProviderLog(e,t,n,r){return(await this.getProviderLogs({organizationId:e,projectSecureId:t,requestId:n,id:r})).providerLogs[0]}async getAggregate(t,n,r){try{this.#n?.info({message:`Querying logs stats aggregate from Tinybird`,category:`LogsSink`,context:{query:r}});let{dimensions:i,startTime:a,endTime:o,...s}=r,c={organizationId:t,projectSecureId:n,...s,...i&&i.length>0&&{dimensions:i.join(`,`)},...a&&{startTime:a.toISOString()},...o&&{endTime:o.toISOString()}},l=await this.#t?.query({endpoint:`project_logs_aggregation.json`,params:c});if(!l)return this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`}),{data:[]};this.#n?.info({message:`Successfully retrieved ${l.length} aggregated data points from Tinybird`,category:`LogsSink`});let u=l.map(t=>e(t,!0)),d=[`success`,`isWorker`,`isBackground`,`skipped`];return{data:u.map(e=>{let t={...e};for(let e of d)e in t&&typeof t[e]==`number`&&(t[e]=t[e]===1);return t})}}catch(e){return this.#t?.isReady()?this.#n?.warning({message:`Failed to query Tinybird for logs stats aggregate, returning empty results`,category:`LogsSink`,error:e}):this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`,error:e}),{data:[]}}}async getDimensions(e,t,n){try{this.#n?.info({message:`Querying logs stats dimensions from Tinybird`,category:`LogsSink`,context:{query:n}});let{dimensions:r,startTime:i,endTime:a,maxValues:o,...s}=n,c={organizationId:e,projectSecureId:t,...s,dimensions:r.join(`,`),...i&&{startTime:i.toISOString()},...a&&{endTime:a.toISOString()},...o&&{maxValuesPerDim:o}},l=await this.#t?.query({endpoint:`project_logs_dimensions.json`,params:c});if(!l)return this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`}),{};this.#n?.info({message:`Successfully retrieved ${l.length} dimension facets from Tinybird`,category:`LogsSink`});let u=[`success`,`isWorker`,`isBackground`,`skipped`],d={};for(let e of l)u.includes(e.dimension)?d[e.dimension]=e.values.map(e=>({value:e.value===`1`?`true`:e.value===`0`?`false`:e.value,count:e.count})):d[e.dimension]=e.values;return d}catch(e){return this.#t?.isReady()?this.#n?.warning({message:`Failed to query Tinybird for logs stats dimensions, returning empty results`,category:`LogsSink`,error:e}):this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`,error:e}),{}}}async getSourceUsage(e,t,n){try{this.#n?.info({message:`Querying logs stats source usage from Tinybird`,category:`LogsSink`,context:{query:n}});let{startTime:r,endTime:i,sourceType:a}=n,o={organizationId:e,projectSecureId:t,...a&&{sourceType:Array.isArray(a)?a.join(`,`):a},...r&&{startTime:r.toISOString()},...i&&{endTime:i.toISOString()}},s=await this.#t?.query({endpoint:`project_source_usage.json`,params:o});return s?(this.#n?.info({message:`Successfully retrieved ${s.length} source usage records from Tinybird`,category:`LogsSink`}),s.map(e=>({sourceId:e.sourceId,sourceType:e.sourceType,requestCount:e.request_count,lastRequest:e.last_request}))):(this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`}),[])}catch(e){return this.#t?.isReady()?this.#n?.warning({message:`Failed to query Tinybird for logs stats source usage, returning empty results`,category:`LogsSink`,error:e}):this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`,error:e}),[]}}async send(e,t){if(!this.#e)throw this.#n?.error({message:`Kafka not initialized, dropping message for topic ${e}`,category:`KafkaSink`,code:`KafkaNotReady`}),Error(`Kafka producer is not initialized`);let n=this.validateLogsBeforeSend(t);if(n.length===0){this.#n?.warning({message:`All ${t.length} log(s) failed validation, nothing to send to topic ${e}`,category:`LogsSink`,code:`AllLogsInvalid`});return}n.length<t.length&&this.#n?.warning({message:`${t.length-n.length} of ${t.length} log(s) failed validation and were dropped`,category:`LogsSink`,code:`SomeLogsInvalid`});let r=Date.now(),i=n.map(t=>({topic:e,value:safeSerialize(t)}));this.#n?.debug({message:`Sending ${i.length} message(s) to topic ${e}`,category:`KafkaSink`});try{let t=await this.#e.send({messages:i,compression:`gzip`});this.#n?.debug({message:`Successfully sent ${i.length} message(s) to topic ${e}`,category:`KafkaSink`,context:{durationMs:Date.now()-r,topic:e,result:t}})}catch(t){throw this.#n?.error({message:`Error sending ${i.length} message(s) to topic ${e}: ${t.message}`,category:`KafkaSink`,error:t,code:`KafkaSendError`,context:{durationMs:Date.now()-r,topic:e,messageCount:i.length}}),t}}buildActionLog(e,t,n){let r=new Date,i=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`action`,organizationId:String(e.organizationId),projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,actionRunId:e.actionRunId,actionId:e.actionId,connectorKey:e.connectorKey,connectorVersion:e.connectorVersion,...e.connectorOwner&&{connectorOwner:e.connectorOwner},...e.connectorProfileId&&{connectorProfileId:e.connectorProfileId},...e.sourceType&&{sourceType:e.sourceType},...e.authType&&{authType:e.authType},...e.authId&&{authId:e.authId},...e.userAgent&&{userAgent:e.userAgent},...e.ipAddress&&{ipAddress:e.ipAddress},...e.sessionId&&{sessionId:e.sessionId},...e.agentId&&{agentId:e.agentId},...e.transportType&&{transportType:e.transportType},...e.streamType!==void 0&&{streamType:e.streamType},...i!==void 0&&{durationMs:i},...e.mode&&{mode:e.mode},...e.actionType&&{actionType:e.actionType},...e.category&&{category:e.category},...e.originOwnerId&&{originOwnerId:e.originOwnerId},...e.originOwnerName&&{originOwnerName:e.originOwnerName},...e.httpMethod&&{httpMethod:e.httpMethod},...e.url&&{url:e.url},...t.success!==void 0&&{success:t.success},...t.statusCode!==void 0&&{statusCode:t.statusCode},...t.defenderContext?.result?.riskLevel&&{riskLevel:t.defenderContext.result.riskLevel},...t.defenderContext?.result?.tier2Score!==void 0&&{tier2Score:t.defenderContext.result.tier2Score},startTime:e.startTime??r,...t.endTime&&{endTime:t.endTime},eventTime:r,isBackground:e.isBackground,...n?.advancedExpiresAt&&{advancedExpiresAt:n.advancedExpiresAt},...n?.defenderExpiresAt&&{defenderExpiresAt:n.defenderExpiresAt}}}buildStepLog(e,t){let n=new Date,r=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`step`,eventTime:n,startTime:e.startTime??n,organizationId:String(e.organizationId),projectSecureId:String(e.projectSecureId),accountSecureId:String(e.accountSecureId),actionRunId:e.actionRunId,stepIndex:e.stepIndex,stepId:e.stepId,...t.endTime&&{endTime:t.endTime},...r!==void 0&&{durationMs:r},...t.skipped!==void 0&&{skipped:t.skipped},...t.success!==void 0&&{success:t.success},...t.statusCode!==void 0&&{statusCode:t.statusCode},...t.message&&{message:t.message},...e.stepFunctionName&&{stepFunctionName:e.stepFunctionName},...e.stepFunctionVersion&&{stepFunctionVersion:e.stepFunctionVersion},...e.stepIterations!==void 0&&{stepIterations:e.stepIterations}}}buildUnifiedLog(e,t,n){let r=new Date,i=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`unified`,requestId:e.requestId,connectorKey:e.connectorKey,connectorVersion:e.connectorVersion??`2`,...e.connectorOwner&&{connectorOwner:e.connectorOwner},organizationId:e.organizationId,projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,...e.originOwnerId&&{originOwnerId:e.originOwnerId},...e.originOwnerName&&{originOwnerName:e.originOwnerName},...e.sourceType&&{sourceType:e.sourceType},...e.authType&&{authType:e.authType},...e.authId&&{authId:e.authId},...e.userAgent&&{userAgent:e.userAgent},...e.ipAddress&&{ipAddress:e.ipAddress},...e.transportType&&{transportType:e.transportType},...e.mode&&{mode:e.mode},...e.httpMethod&&{httpMethod:e.httpMethod},...e.url&&{url:e.url},...e.path&&{path:e.path},...e.resource&&{resource:e.resource},...e.subResource&&{subResource:e.subResource},...e.childResource&&{childResource:e.childResource},...e.service&&{service:e.service},...e.action&&{action:e.action},...t.statusCode!==void 0&&{statusCode:t.statusCode},...t.success!==void 0&&{success:t.success},isBackground:e.isBackground,durationMs:i,startTime:e.startTime??r,...t.endTime&&{endTime:t.endTime},eventTime:r,...t.statusCode!==void 0&&{status:t.statusCode},provider:e.connectorKey,eventDatetime:r,duration:i,...n?.advancedExpiresAt&&{advancedExpiresAt:n.advancedExpiresAt}}}buildProviderLog(e,t){let n=new Date,r=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`provider`,requestId:e.requestId,id:e.id,organizationId:e.organizationId,projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,...e.originOwnerId&&{originOwnerId:e.originOwnerId},...e.originOwnerName&&{originOwnerName:e.originOwnerName},action:e.action,...e.mode&&{mode:e.mode},httpMethod:e.httpMethod,url:e.url,...e.path&&{path:e.path},connectorKey:e.connectorKey,connectorVersion:`2`,...e.resource&&{resource:e.resource},...e.subResource&&{subResource:e.subResource},...e.childResource&&{childResource:e.childResource},...e.service&&{service:e.service},...t.success!==void 0&&{success:t.success},...t.statusCode!==void 0&&{statusCode:t.statusCode},durationMs:r,startTime:e.startTime??n,...t.endTime&&{endTime:t.endTime},eventTime:n,...t.statusCode!==void 0&&{status:t.statusCode},provider:e.connectorKey,eventDatetime:n,duration:r}}calculateDurationMs(e,t){if(!(e instanceof Date)||!(t instanceof Date))return;let n=e.getTime(),r=t.getTime();if(!(Number.isNaN(n)||Number.isNaN(r)||r<n))return r-n}validateLogsWithSchema(e,t){return e.map(e=>{try{return t.parse(e)}catch(t){if(t instanceof v){let n=`unknown`;if(typeof e==`object`&&e&&`logType`in e){let t=e;n=typeof t.logType==`string`?t.logType:`unknown`}throw this.#n?.error({message:`Failed to validate ${n} log from Tinybird`,category:`LogsSink`,code:`LogParsingTypeError`,context:{validationErrors:t.errors,log:safeSerialize(e)}}),Error(`Tinybird data validation failed for ${n} log: ${t.message}`)}throw t}})}validateLogs(e){return this.validateLogsWithSchema(e,W)}validateLogsBeforeSend(e){let t=[];for(let n of e)try{let e=this.getSchemaForLogType(n.logType).parse(n);t.push(e)}catch(e){e instanceof v?this.#n?.warning({message:`Log validation failed before sending to Tinybird, dropping ${n.logType} log`,category:`LogsSink`,code:`PreWriteValidationFailed`,context:{logType:n.logType,validationErrors:e.errors,log:safeSerialize(n)}}):this.#n?.warning({message:`Unexpected error validating ${n.logType} log before send, dropping log`,category:`LogsSink`,code:`PreWriteValidationError`,error:e})}return t}getSchemaForLogType(e){switch(e){case`action`:return B;case`step`:return V;case`unified`:return H;case`provider`:return U}}};const G={logs:{enabled:!0},advanced:{enabled:!1,ttl:7,errorsOnly:!1,includeBackground:!1},defender:{enabled:!0},datasets:{enabled:!0,includeBackground:!1}};function resolveOlapOptions(e){return{logs:{...G.logs,...e?.logs},advanced:{...G.advanced,...e?.advanced},defender:{...G.defender,...e?.defender},datasets:{...G.datasets,...e?.datasets}}}const buildHttpClient=e=>{try{return new x({logger:e})}catch(t){let n=t;e?.error({message:`Error building http client: ${n.message}`,error:n,code:`BuildHttpClientError`,category:`buildHttpClient`});return}},buildKafkaClient=async(e,t)=>{if(e)try{let{Producer:t,stringSerializers:n}=await import(`@platformatic/kafka`);return new t({...e,serializers:n})??void 0}catch(e){let n=e;t?.error({message:`Error building kafka producer: ${n.message}`,error:n,code:`BuildKafkaProducerError`,category:`buildKafkaClient`});return}},buildS3Client=(e,t)=>{try{return new f(e)??void 0}catch(e){let n=e;t?.error({message:`Error building s3 client: ${n.message}`,error:n,code:`BuildS3ClientError`,category:`buildS3Client`});return}};var K=class OlapClient{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;constructor({getKafkaClient:e=buildKafkaClient,getHttpClient:t=buildHttpClient,getS3Client:n=buildS3Client,kafkaClientConfig:r,s3ClientConfig:i,tinybirdConfig:a,sinkConfig:o,logger:s}={}){this.name=`OlapClient`,this.#c=e,this.#l=r,this.#u=a,this.#d=o,this.#t=t(s),this.#n=n(i,s),this.#r=s}static async create({getKafkaClient:e=buildKafkaClient,getHttpClient:t=buildHttpClient,getS3Client:n=buildS3Client,kafkaClientConfig:r,s3ClientConfig:i,tinybirdConfig:a,sinkConfig:o,logger:s}={}){let c=new OlapClient({getKafkaClient:e,getHttpClient:t,getS3Client:n,kafkaClientConfig:r,s3ClientConfig:i,tinybirdConfig:a,sinkConfig:o,logger:s});return await c.initialize(),c}async initialize(){this.#e=await this.#c(this.#l,this.#r),this.#i=new LogsSink(this.#e,this.#t,this.#u,this.#r),this.#a=new AdvancedSink(this.#n,this.#d?.advanced,this.#r),this.#o=new DefenderSink(this.#n,this.#d?.defender,this.#r),this.#s=new DatasetsSink(this.#d?.datasets,this.#r),await this.#i?.initialize(),await this.#a?.initialize(),await this.#s?.initialize(),await this.#o?.initialize()}async recordAction(e,t,n){await this.recordActions([{input:e,result:t}],n)}async recordActions(e,t){let{logs:n,advanced:i,defender:a,datasets:o}=resolveOlapOptions(t);this.#r?.debug({message:`Olap client called to record ${e.length} action(s)`,category:`OlapClient`,context:{options:t,resolvedOptions:{logs:n,advanced:i,defender:a,datasets:o}}});for(let t of e)r(t.input.isBackground)&&(t.input.isBackground=isBackgroundLog(t.input.mode,t.input.sourceType));let s=o?.enabled&&this.#s?this.#s.sendActions(e,o).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to datasets sink: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve(),[c,l]=await Promise.all([i?.enabled&&this.#a?this.#a.sendActions(e,i).catch(t=>(this.#r?.warning({message:`[OlapClient] Error sending to advanced logs s3: ${t.message}`,category:`OlapClient`,error:t}),e.map(()=>null))):Promise.resolve(e.map(()=>null)),a?.enabled&&this.#o?this.#o.sendActions(e,a).catch(t=>(this.#r?.warning({message:`[OlapClient] Error sending to defender logs s3: ${t.message}`,category:`OlapClient`,error:t}),e.map(()=>null))):Promise.resolve(e.map(()=>null))]),u=e.map((e,t)=>({...e,metadata:{advancedExpiresAt:c[t]?.expiresAt,defenderExpiresAt:l[t]?.expiresAt}})),d=n?.enabled&&this.#i?this.#i.sendActions(u,n).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve();await Promise.all([s,d])}async recordStep(e,t,n){await this.recordSteps([{input:e,result:t}],n)}async recordSteps(e,t){let{logs:n,advanced:r}=resolveOlapOptions(t),i=[];n?.enabled&&this.#i&&i.push(this.#i.sendSteps(e,n).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})),r?.enabled&&this.#a&&i.push(this.#a.sendSteps(e,r).then(()=>{}).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to s3: ${e.message}`,category:`OlapClient`,error:e})})),await Promise.all(i)}async recordUnified(e,t,n){let{logs:i,advanced:a}=resolveOlapOptions(n);this.#r?.debug({message:`Olap client called to record unified`,category:`OlapClient`,context:{mode:e.mode,requestId:e.requestId,success:t.success,options:n,resolvedOptions:{logs:i,advanced:a}}}),r(e.isBackground)&&(e.isBackground=isBackgroundLog(e.mode,e.sourceType));let o={advancedExpiresAt:(a?.enabled&&this.#a?await this.#a.sendUnified(e,t,a).catch(e=>(this.#r?.warning({message:`[OlapClient] Error sending to advanced logs s3: ${e.message}`,category:`OlapClient`,error:e}),null)):null)?.expiresAt};i?.enabled&&this.#i&&await this.#i.sendUnified(e,t,o,i).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})}async recordProvider(e,t,n){let{logs:r,advanced:i}=resolveOlapOptions(n),a=[];r?.enabled&&this.#i&&a.push(this.#i.sendProvider(e,t,r).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})),i?.enabled&&this.#a&&a.push(this.#a.sendProvider(e,t,i).then(()=>{}).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to s3: ${e.message}`,category:`OlapClient`,error:e})})),await Promise.all(a)}async getLogs(e,t,n){return this.#r?.debug({message:`Querying logs`,category:`OlapClient`,context:{query:n}}),await this.#i?.getLogs({...n,organizationId:e,projectSecureId:t})||(this.#r?.warning({message:`Failed to query logs, returning empty result`,category:`OlapClient`}),{logs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getActionLogs(e,t,n){return this.#r?.debug({message:`Querying action logs`,category:`OlapClient`,context:{query:n}}),await this.#i?.getActions({...n,organizationId:e,projectSecureId:t})||(this.#r?.warning({message:`Failed to query action logs, returning empty result`,category:`OlapClient`}),{actionLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getActionLog(e,t,n){let i=await this.#i?.getAction(e,t,n);if(r(i)){this.#r?.debug({message:`Failed to retrieve action log for actionRunId ${n}`,category:`OlapClient`});return}return i}async getLog(e,t,n){this.#r?.debug({message:`Querying log by logId`,category:`OlapClient`,context:{logId:n}});let r=await this.getLogs(e,t,{logId:n,pageSize:1});if(!r||r.logs.length===0){this.#r?.debug({message:`Failed to retrieve log for logId ${n}`,category:`OlapClient`});return}let i=r.logs[0];if(i.logType===`action`||i.logType===`unified`)return i}async getStepLogs(e,t,n){return this.#r?.debug({message:`Querying step logs`,category:`OlapClient`,context:{query:n}}),await this.#i?.getSteps({...n,organizationId:e,projectSecureId:t})||(this.#r?.warning({message:`Failed to query step logs, returning empty result`,category:`OlapClient`}),{stepLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getStepLog(e,t,n,i){let a=await this.#i?.getStep(e,t,n,i);if(r(a)){this.#r?.debug({message:`Failed to retrieve step log for actionRunId ${n} stepIndex ${i}`,category:`OlapClient`});return}return a}async getUnifiedLogs(e,t,n){return this.#r?.debug({message:`Querying unified logs`,category:`OlapClient`,context:{query:n}}),await this.#i?.getUnifiedLogs({...n,organizationId:e,projectSecureId:t})||(this.#r?.warning({message:`Failed to query unified logs, returning empty result`,category:`OlapClient`}),{unifiedLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getUnifiedLog(e,t,n){let i=await this.#i?.getUnifiedLog(e,t,n);if(r(i)){this.#r?.debug({message:`Failed to retrieve unified log for requestId ${n}`,category:`OlapClient`});return}return i}async getProviderLogs(e,t,n){return this.#r?.debug({message:`Querying provider logs`,category:`OlapClient`,context:{query:n}}),await this.#i?.getProviderLogs({...n,organizationId:e,projectSecureId:t})||(this.#r?.warning({message:`Failed to query provider logs, returning empty result`,category:`OlapClient`}),{providerLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getProviderLog(e,t,n,i){let a=await this.#i?.getProviderLog(e,t,n,i);if(r(a)){this.#r?.debug({message:`Failed to retrieve provider log for requestId ${n} id ${i}`,category:`OlapClient`});return}return a}async getActionAdvancedLog(e,t,n){let i=await this.#a?.getAction(e,t,n);if(r(i)){this.#r?.debug({message:`Failed to retrieve action advanced log for actionRunId ${n}`,category:`OlapClient`});return}return i}async getStepAdvancedLog(e,t,n,i){let a=await this.#a?.getStep(e,t,n,i);if(r(a)){this.#r?.debug({message:`Failed to retrieve step advanced log for actionRunId ${n} stepIndex ${i}`,category:`OlapClient`});return}return a}async getUnifiedAdvancedLog(e,t,n){let i=await this.#a?.getUnified(e,t,n);if(r(i)){this.#r?.debug({message:`Failed to retrieve unified advanced log for requestId ${n}`,category:`OlapClient`});return}return i}async getProviderAdvancedLog(e,t,n,i){let a=await this.#a?.getProvider(e,t,n,i);if(r(a)){this.#r?.debug({message:`Failed to retrieve provider advanced log for requestId ${n} id ${i}`,category:`OlapClient`});return}return a}async getDefenderLog(e,t,n){let i=await this.#o?.getAction(e,t,n);if(r(i)){this.#r?.debug({message:`Failed to retrieve defender log for actionRunId ${n}`,category:`OlapClient`});return}return i}async getLogsStatsAggregate(e,t,n){return this.#r?.debug({message:`Querying logs stats aggregate`,category:`OlapClient`,context:{query:n}}),await this.#i?.getAggregate(e,t,n)??{data:[]}}async getLogsStatsDimensions(e,t,n){return this.#r?.debug({message:`Querying logs stats dimensions`,category:`OlapClient`,context:{query:n}}),await this.#i?.getDimensions(e,t,n)??{}}async getSourceUsage(e,t,n){return this.#r?.debug({message:`Querying source usage`,category:`OlapClient`,context:{query:n}}),await this.#i?.getSourceUsage(e,t,n)??[]}};const buildOlapClientInstance=async({getKafkaClient:e=buildKafkaClient,getHttpClient:t=buildHttpClient,getS3Client:n=buildS3Client,kafkaClientConfig:r,s3ClientConfig:i,tinybirdConfig:a,sinkConfig:o,logger:s}={})=>K.create({getKafkaClient:e,getHttpClient:t,getS3Client:n,kafkaClientConfig:r,s3ClientConfig:i,tinybirdConfig:a,sinkConfig:o,logger:s});var OlapClientManager=class{static{this.olapClientPromise=null}static getInstance({getKafkaClient:e,getHttpClient:t,getS3Client:n,kafkaClientConfig:r,s3ClientConfig:i,tinybirdConfig:a,sinkConfig:o,logger:s,getOlapClient:c=buildOlapClientInstance}={}){return this.olapClientPromise||=c({getKafkaClient:e,getHttpClient:t,getS3Client:n,kafkaClientConfig:r,s3ClientConfig:i,tinybirdConfig:a,sinkConfig:o,logger:s}),this.olapClientPromise}static resetInstance(){this.olapClientPromise=null}};export{A as AuthType,E as Dimension,T as IntervalType,S as LogType,K as OlapClient,OlapClientManager,C as OrderBy,w as OrderDirection,D as SourceType,k as StreamType,O as TransportType};
|
|
1
|
+
import{t as e}from"./chunk-BhWHdk3m.mjs";import{createClient as t}from"@clickhouse/client";import n from"node:http";import{convertKeysToCamelCase as r,exceedsSize as i,extractSchema as a,isMissing as o,isString as s}from"@stackone/utils";import{CensorType as c,redactFields as l,redactObject as u,redactUrl as d}from"@stackone/redaction";import{GetObjectCommand as f,HeadObjectCommand as p,PutObjectCommand as m,S3Client as h}from"@aws-sdk/client-s3";import{OTLPTraceExporter as g}from"@opentelemetry/exporter-trace-otlp-proto";import{resourceFromAttributes as _}from"@opentelemetry/resources";import{BasicTracerProvider as v,BatchSpanProcessor as y}from"@opentelemetry/sdk-trace-base";import{ATTR_SERVICE_NAME as ee}from"@opentelemetry/semantic-conventions";import{ZodError as b,z as x}from"zod";import{HttpClient as te}from"@stackone/transport";const S=new Map;function registerQuery(e){S.set(e.id,e)}function getQueryDefinition(e){return S.get(e)}function toArray(e){return e==null?[]:Array.isArray(e)?e:[e]}function toClickHouseDate(e){return e?e.toISOString().replace(`T`,` `).replace(`Z`,``):null}function buildPaginationParams(e,t){let n=Math.min(t??100,1e3);return{limit:n,offset:(Math.max(e??1,1)-1)*n}}function sanitizeOrderDirection(e){return e?.toLowerCase()===`asc`?`ASC`:`DESC`}function sanitizeOrderBy(e,t,n){return e?t[e]??n:n}const C={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`};function buildActionLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
|
|
2
|
+
SELECT
|
|
3
|
+
eventTime,
|
|
4
|
+
startTime,
|
|
5
|
+
endTime,
|
|
6
|
+
durationMs,
|
|
7
|
+
organizationId,
|
|
8
|
+
projectSecureId,
|
|
9
|
+
accountSecureId,
|
|
10
|
+
actionRunId,
|
|
11
|
+
actionId,
|
|
12
|
+
connectorKey,
|
|
13
|
+
connectorVersion,
|
|
14
|
+
connectorOwner,
|
|
15
|
+
connectorProfileId,
|
|
16
|
+
actionType,
|
|
17
|
+
mode,
|
|
18
|
+
category,
|
|
19
|
+
originOwnerId,
|
|
20
|
+
originOwnerName,
|
|
21
|
+
httpMethod,
|
|
22
|
+
url,
|
|
23
|
+
sourceType,
|
|
24
|
+
sourceId,
|
|
25
|
+
sourceValue,
|
|
26
|
+
authType,
|
|
27
|
+
authId,
|
|
28
|
+
userAgent,
|
|
29
|
+
ipAddress,
|
|
30
|
+
sessionId,
|
|
31
|
+
agentId,
|
|
32
|
+
transportType,
|
|
33
|
+
streamType,
|
|
34
|
+
isBackground,
|
|
35
|
+
success,
|
|
36
|
+
statusCode,
|
|
37
|
+
riskLevel,
|
|
38
|
+
tier2Score,
|
|
39
|
+
advancedExpiresAt,
|
|
40
|
+
defenderExpiresAt,
|
|
41
|
+
message,
|
|
42
|
+
'action' as logType
|
|
43
|
+
FROM actions
|
|
44
|
+
WHERE 1=1
|
|
45
|
+
AND ({organizationId:Array(String)} = [] OR organizationId IN {organizationId:Array(String)})
|
|
46
|
+
AND ({projectSecureId:Array(String)} = [] OR projectSecureId IN {projectSecureId:Array(String)})
|
|
47
|
+
AND ({actionRunId:Array(String)} = [] OR actionRunId IN {actionRunId:Array(String)})
|
|
48
|
+
AND ({accountSecureId:Array(String)} = [] OR accountSecureId IN {accountSecureId:Array(String)})
|
|
49
|
+
AND ({actionId:Array(String)} = [] OR actionId IN {actionId:Array(String)})
|
|
50
|
+
AND ({connectorKey:Array(String)} = [] OR connectorKey IN {connectorKey:Array(String)})
|
|
51
|
+
AND ({connectorVersion:Array(String)} = [] OR connectorVersion IN {connectorVersion:Array(String)})
|
|
52
|
+
AND ({connectorOwner:Array(String)} = [] OR connectorOwner IN {connectorOwner:Array(String)})
|
|
53
|
+
AND ({connectorProfileId:Array(String)} = [] OR connectorProfileId IN {connectorProfileId:Array(String)})
|
|
54
|
+
AND ({actionType:Array(String)} = [] OR actionType IN {actionType:Array(String)})
|
|
55
|
+
AND ({mode:Array(String)} = [] OR mode IN {mode:Array(String)})
|
|
56
|
+
AND ({category:Array(String)} = [] OR category IN {category:Array(String)})
|
|
57
|
+
AND ({originOwnerId:Array(String)} = [] OR originOwnerId IN {originOwnerId:Array(String)})
|
|
58
|
+
AND ({originOwnerName:Array(String)} = [] OR originOwnerName IN {originOwnerName:Array(String)})
|
|
59
|
+
AND ({httpMethod:Array(String)} = [] OR httpMethod IN {httpMethod:Array(String)})
|
|
60
|
+
AND ({sourceType:Array(String)} = [] OR sourceType IN {sourceType:Array(String)})
|
|
61
|
+
AND ({sourceId:Array(String)} = [] OR sourceId IN {sourceId:Array(String)})
|
|
62
|
+
AND ({sourceValue:Array(String)} = [] OR sourceValue IN {sourceValue:Array(String)})
|
|
63
|
+
AND ({authType:Array(String)} = [] OR authType IN {authType:Array(String)})
|
|
64
|
+
AND ({authId:Array(String)} = [] OR authId IN {authId:Array(String)})
|
|
65
|
+
AND ({userAgent:Array(String)} = [] OR userAgent IN {userAgent:Array(String)})
|
|
66
|
+
AND ({ipAddress:Array(String)} = [] OR ipAddress IN {ipAddress:Array(String)})
|
|
67
|
+
AND ({sessionId:Array(String)} = [] OR sessionId IN {sessionId:Array(String)})
|
|
68
|
+
AND ({agentId:Array(String)} = [] OR agentId IN {agentId:Array(String)})
|
|
69
|
+
AND ({transportType:Array(String)} = [] OR transportType IN {transportType:Array(String)})
|
|
70
|
+
AND ({streamType:Array(String)} = [] OR streamType IN {streamType:Array(String)})
|
|
71
|
+
AND ({statusCode:Array(Int16)} = [] OR statusCode IN {statusCode:Array(Int16)})
|
|
72
|
+
AND ({isBackground:Nullable(UInt8)} IS NULL OR isBackground = {isBackground:Nullable(UInt8)})
|
|
73
|
+
AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
|
|
74
|
+
AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventTime >= {startTime:Nullable(DateTime64(3))})
|
|
75
|
+
AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventTime <= {endTime:Nullable(DateTime64(3))})
|
|
76
|
+
ORDER BY ${sanitizeOrderBy(e.orderBy,C,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
|
|
77
|
+
LIMIT {limit:UInt32}
|
|
78
|
+
OFFSET {offset:UInt32}
|
|
79
|
+
`,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),actionRunId:toArray(e.actionRunId),accountSecureId:toArray(e.accountSecureId),actionId:toArray(e.actionId),connectorKey:toArray(e.connectorKey),connectorVersion:toArray(e.connectorVersion),connectorOwner:toArray(e.connectorOwner),connectorProfileId:toArray(e.connectorProfileId),actionType:toArray(e.actionType),mode:toArray(e.mode),category:toArray(e.category),originOwnerId:toArray(e.originOwnerId),originOwnerName:toArray(e.originOwnerName),httpMethod:toArray(e.httpMethod),sourceType:toArray(e.sourceType),sourceId:toArray(e.sourceId),sourceValue:toArray(e.sourceValue),authType:toArray(e.authType),authId:toArray(e.authId),userAgent:toArray(e.userAgent),ipAddress:toArray(e.ipAddress),sessionId:toArray(e.sessionId),agentId:toArray(e.agentId),transportType:toArray(e.transportType),streamType:toArray(e.streamType),statusCode:toArray(e.statusCode).map(e=>typeof e==`string`?Number.parseInt(e,10):e),isBackground:e.isBackground===void 0?null:+!!e.isBackground,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime),limit:t,offset:n}}}function buildActionLogsCountQuery(e){return{sql:`
|
|
80
|
+
SELECT count() as total
|
|
81
|
+
FROM actions
|
|
82
|
+
WHERE 1=1
|
|
83
|
+
AND ({organizationId:Array(String)} = [] OR organizationId IN {organizationId:Array(String)})
|
|
84
|
+
AND ({projectSecureId:Array(String)} = [] OR projectSecureId IN {projectSecureId:Array(String)})
|
|
85
|
+
AND ({actionRunId:Array(String)} = [] OR actionRunId IN {actionRunId:Array(String)})
|
|
86
|
+
AND ({accountSecureId:Array(String)} = [] OR accountSecureId IN {accountSecureId:Array(String)})
|
|
87
|
+
AND ({actionId:Array(String)} = [] OR actionId IN {actionId:Array(String)})
|
|
88
|
+
AND ({connectorKey:Array(String)} = [] OR connectorKey IN {connectorKey:Array(String)})
|
|
89
|
+
AND ({connectorVersion:Array(String)} = [] OR connectorVersion IN {connectorVersion:Array(String)})
|
|
90
|
+
AND ({connectorOwner:Array(String)} = [] OR connectorOwner IN {connectorOwner:Array(String)})
|
|
91
|
+
AND ({connectorProfileId:Array(String)} = [] OR connectorProfileId IN {connectorProfileId:Array(String)})
|
|
92
|
+
AND ({actionType:Array(String)} = [] OR actionType IN {actionType:Array(String)})
|
|
93
|
+
AND ({mode:Array(String)} = [] OR mode IN {mode:Array(String)})
|
|
94
|
+
AND ({category:Array(String)} = [] OR category IN {category:Array(String)})
|
|
95
|
+
AND ({originOwnerId:Array(String)} = [] OR originOwnerId IN {originOwnerId:Array(String)})
|
|
96
|
+
AND ({originOwnerName:Array(String)} = [] OR originOwnerName IN {originOwnerName:Array(String)})
|
|
97
|
+
AND ({httpMethod:Array(String)} = [] OR httpMethod IN {httpMethod:Array(String)})
|
|
98
|
+
AND ({sourceType:Array(String)} = [] OR sourceType IN {sourceType:Array(String)})
|
|
99
|
+
AND ({sourceId:Array(String)} = [] OR sourceId IN {sourceId:Array(String)})
|
|
100
|
+
AND ({sourceValue:Array(String)} = [] OR sourceValue IN {sourceValue:Array(String)})
|
|
101
|
+
AND ({authType:Array(String)} = [] OR authType IN {authType:Array(String)})
|
|
102
|
+
AND ({authId:Array(String)} = [] OR authId IN {authId:Array(String)})
|
|
103
|
+
AND ({userAgent:Array(String)} = [] OR userAgent IN {userAgent:Array(String)})
|
|
104
|
+
AND ({ipAddress:Array(String)} = [] OR ipAddress IN {ipAddress:Array(String)})
|
|
105
|
+
AND ({sessionId:Array(String)} = [] OR sessionId IN {sessionId:Array(String)})
|
|
106
|
+
AND ({agentId:Array(String)} = [] OR agentId IN {agentId:Array(String)})
|
|
107
|
+
AND ({transportType:Array(String)} = [] OR transportType IN {transportType:Array(String)})
|
|
108
|
+
AND ({streamType:Array(String)} = [] OR streamType IN {streamType:Array(String)})
|
|
109
|
+
AND ({statusCode:Array(Int16)} = [] OR statusCode IN {statusCode:Array(Int16)})
|
|
110
|
+
AND ({isBackground:Nullable(UInt8)} IS NULL OR isBackground = {isBackground:Nullable(UInt8)})
|
|
111
|
+
AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
|
|
112
|
+
AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventTime >= {startTime:Nullable(DateTime64(3))})
|
|
113
|
+
AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventTime <= {endTime:Nullable(DateTime64(3))})
|
|
114
|
+
`,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),actionRunId:toArray(e.actionRunId),accountSecureId:toArray(e.accountSecureId),actionId:toArray(e.actionId),connectorKey:toArray(e.connectorKey),connectorVersion:toArray(e.connectorVersion),connectorOwner:toArray(e.connectorOwner),connectorProfileId:toArray(e.connectorProfileId),actionType:toArray(e.actionType),mode:toArray(e.mode),category:toArray(e.category),originOwnerId:toArray(e.originOwnerId),originOwnerName:toArray(e.originOwnerName),httpMethod:toArray(e.httpMethod),sourceType:toArray(e.sourceType),sourceId:toArray(e.sourceId),sourceValue:toArray(e.sourceValue),authType:toArray(e.authType),authId:toArray(e.authId),userAgent:toArray(e.userAgent),ipAddress:toArray(e.ipAddress),sessionId:toArray(e.sessionId),agentId:toArray(e.agentId),transportType:toArray(e.transportType),streamType:toArray(e.streamType),statusCode:toArray(e.statusCode).map(e=>typeof e==`string`?Number.parseInt(e,10):e),isBackground:e.isBackground===void 0?null:+!!e.isBackground,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}registerQuery({id:`project_action_logs.json`,buildQuery:buildActionLogsQuery,buildCountQuery:buildActionLogsCountQuery});const w={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`};function buildStepLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
|
|
115
|
+
SELECT
|
|
116
|
+
eventTime,
|
|
117
|
+
startTime,
|
|
118
|
+
endTime,
|
|
119
|
+
durationMs,
|
|
120
|
+
organizationId,
|
|
121
|
+
projectSecureId,
|
|
122
|
+
accountSecureId,
|
|
123
|
+
actionRunId,
|
|
124
|
+
stepIndex,
|
|
125
|
+
stepId,
|
|
126
|
+
stepFunctionName,
|
|
127
|
+
stepFunctionVersion,
|
|
128
|
+
stepIterations,
|
|
129
|
+
skipped,
|
|
130
|
+
success,
|
|
131
|
+
statusCode,
|
|
132
|
+
message,
|
|
133
|
+
'step' as logType
|
|
134
|
+
FROM steps
|
|
135
|
+
WHERE 1=1
|
|
136
|
+
AND ({organizationId:Array(String)} = [] OR organizationId IN {organizationId:Array(String)})
|
|
137
|
+
AND ({projectSecureId:Array(String)} = [] OR projectSecureId IN {projectSecureId:Array(String)})
|
|
138
|
+
AND ({accountSecureId:Array(String)} = [] OR accountSecureId IN {accountSecureId:Array(String)})
|
|
139
|
+
AND ({actionRunId:Array(String)} = [] OR actionRunId IN {actionRunId:Array(String)})
|
|
140
|
+
AND ({stepId:Array(String)} = [] OR stepId IN {stepId:Array(String)})
|
|
141
|
+
AND ({stepIndex:Array(Int32)} = [] OR stepIndex IN {stepIndex:Array(Int32)})
|
|
142
|
+
AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
|
|
143
|
+
AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventTime >= {startTime:Nullable(DateTime64(3))})
|
|
144
|
+
AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventTime <= {endTime:Nullable(DateTime64(3))})
|
|
145
|
+
ORDER BY ${sanitizeOrderBy(e.orderBy,w,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
|
|
146
|
+
LIMIT {limit:UInt32}
|
|
147
|
+
OFFSET {offset:UInt32}
|
|
148
|
+
`,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),actionRunId:toArray(e.actionRunId),stepId:toArray(e.stepId),stepIndex:toArray(e.stepIndex),success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime),limit:t,offset:n}}}function buildStepLogsCountQuery(e){return{sql:`
|
|
149
|
+
SELECT count() as total
|
|
150
|
+
FROM steps
|
|
151
|
+
WHERE 1=1
|
|
152
|
+
AND ({organizationId:Array(String)} = [] OR organizationId IN {organizationId:Array(String)})
|
|
153
|
+
AND ({projectSecureId:Array(String)} = [] OR projectSecureId IN {projectSecureId:Array(String)})
|
|
154
|
+
AND ({accountSecureId:Array(String)} = [] OR accountSecureId IN {accountSecureId:Array(String)})
|
|
155
|
+
AND ({actionRunId:Array(String)} = [] OR actionRunId IN {actionRunId:Array(String)})
|
|
156
|
+
AND ({stepId:Array(String)} = [] OR stepId IN {stepId:Array(String)})
|
|
157
|
+
AND ({stepIndex:Array(Int32)} = [] OR stepIndex IN {stepIndex:Array(Int32)})
|
|
158
|
+
AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
|
|
159
|
+
AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventTime >= {startTime:Nullable(DateTime64(3))})
|
|
160
|
+
AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventTime <= {endTime:Nullable(DateTime64(3))})
|
|
161
|
+
`,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),actionRunId:toArray(e.actionRunId),stepId:toArray(e.stepId),stepIndex:toArray(e.stepIndex),success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}registerQuery({id:`project_step_logs.json`,buildQuery:buildStepLogsQuery,buildCountQuery:buildStepLogsCountQuery});const T={startTime:`startTime`,endTime:`endTime`,eventTime:`eventDatetime`,durationMs:`duration`};function buildUnifiedLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
|
|
162
|
+
SELECT
|
|
163
|
+
eventDatetime as eventTime,
|
|
164
|
+
startTime,
|
|
165
|
+
endTime,
|
|
166
|
+
duration as durationMs,
|
|
167
|
+
organizationId,
|
|
168
|
+
projectSecureId,
|
|
169
|
+
accountSecureId,
|
|
170
|
+
requestId,
|
|
171
|
+
provider as connectorKey,
|
|
172
|
+
connectorVersion,
|
|
173
|
+
connectorOwner,
|
|
174
|
+
connectorProfileId,
|
|
175
|
+
mode,
|
|
176
|
+
httpMethod,
|
|
177
|
+
url,
|
|
178
|
+
path,
|
|
179
|
+
resource,
|
|
180
|
+
subResource,
|
|
181
|
+
childResource,
|
|
182
|
+
service,
|
|
183
|
+
action,
|
|
184
|
+
sourceId,
|
|
185
|
+
sourceType,
|
|
186
|
+
sourceValue,
|
|
187
|
+
authType,
|
|
188
|
+
authId,
|
|
189
|
+
userAgent,
|
|
190
|
+
ipAddress,
|
|
191
|
+
sessionId,
|
|
192
|
+
agentId,
|
|
193
|
+
transportType,
|
|
194
|
+
streamType,
|
|
195
|
+
isBackground,
|
|
196
|
+
originOwnerId,
|
|
197
|
+
originOwnerName,
|
|
198
|
+
statusCode,
|
|
199
|
+
status,
|
|
200
|
+
success,
|
|
201
|
+
isWorker,
|
|
202
|
+
advancedExpiresAt,
|
|
203
|
+
'unified' as logType
|
|
204
|
+
FROM unified_requests
|
|
205
|
+
WHERE 1=1
|
|
206
|
+
AND ({organizationId:Array(String)} = [] OR organizationId IN {organizationId:Array(String)})
|
|
207
|
+
AND ({projectSecureId:Array(String)} = [] OR projectSecureId IN {projectSecureId:Array(String)})
|
|
208
|
+
AND ({accountSecureId:Array(String)} = [] OR accountSecureId IN {accountSecureId:Array(String)})
|
|
209
|
+
AND ({requestId:Array(String)} = [] OR requestId IN {requestId:Array(String)})
|
|
210
|
+
AND ({connectorKey:Array(String)} = [] OR provider IN {connectorKey:Array(String)})
|
|
211
|
+
AND ({connectorVersion:Array(String)} = [] OR connectorVersion IN {connectorVersion:Array(String)})
|
|
212
|
+
AND ({mode:Array(String)} = [] OR mode IN {mode:Array(String)})
|
|
213
|
+
AND ({httpMethod:Array(String)} = [] OR httpMethod IN {httpMethod:Array(String)})
|
|
214
|
+
AND ({resource:Array(String)} = [] OR resource IN {resource:Array(String)})
|
|
215
|
+
AND ({subResource:Array(String)} = [] OR subResource IN {subResource:Array(String)})
|
|
216
|
+
AND ({childResource:Array(String)} = [] OR childResource IN {childResource:Array(String)})
|
|
217
|
+
AND ({service:Array(String)} = [] OR service IN {service:Array(String)})
|
|
218
|
+
AND ({action:Array(String)} = [] OR action IN {action:Array(String)})
|
|
219
|
+
AND ({sourceType:Array(String)} = [] OR sourceType IN {sourceType:Array(String)})
|
|
220
|
+
AND ({sourceId:Array(String)} = [] OR sourceId IN {sourceId:Array(String)})
|
|
221
|
+
AND ({sourceValue:Array(String)} = [] OR sourceValue IN {sourceValue:Array(String)})
|
|
222
|
+
AND ({authType:Array(String)} = [] OR authType IN {authType:Array(String)})
|
|
223
|
+
AND ({authId:Array(String)} = [] OR authId IN {authId:Array(String)})
|
|
224
|
+
AND ({userAgent:Array(String)} = [] OR userAgent IN {userAgent:Array(String)})
|
|
225
|
+
AND ({ipAddress:Array(String)} = [] OR ipAddress IN {ipAddress:Array(String)})
|
|
226
|
+
AND ({sessionId:Array(String)} = [] OR sessionId IN {sessionId:Array(String)})
|
|
227
|
+
AND ({agentId:Array(String)} = [] OR agentId IN {agentId:Array(String)})
|
|
228
|
+
AND ({transportType:Array(String)} = [] OR transportType IN {transportType:Array(String)})
|
|
229
|
+
AND ({streamType:Array(String)} = [] OR streamType IN {streamType:Array(String)})
|
|
230
|
+
AND ({originOwnerId:Array(String)} = [] OR originOwnerId IN {originOwnerId:Array(String)})
|
|
231
|
+
AND ({originOwnerName:Array(String)} = [] OR originOwnerName IN {originOwnerName:Array(String)})
|
|
232
|
+
AND ({statusCode:Array(Int16)} = [] OR statusCode IN {statusCode:Array(Int16)})
|
|
233
|
+
AND ({isBackground:Nullable(UInt8)} IS NULL OR isBackground = {isBackground:Nullable(UInt8)})
|
|
234
|
+
AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
|
|
235
|
+
AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventDatetime >= {startTime:Nullable(DateTime64(3))})
|
|
236
|
+
AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventDatetime <= {endTime:Nullable(DateTime64(3))})
|
|
237
|
+
ORDER BY ${sanitizeOrderBy(e.orderBy,T,`eventDatetime`)} ${sanitizeOrderDirection(e.orderDirection)}
|
|
238
|
+
LIMIT {limit:UInt32}
|
|
239
|
+
OFFSET {offset:UInt32}
|
|
240
|
+
`,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),requestId:toArray(e.requestId),connectorKey:toArray(e.connectorKey),connectorVersion:toArray(e.connectorVersion),mode:toArray(e.mode),httpMethod:toArray(e.httpMethod),resource:toArray(e.resource),subResource:toArray(e.subResource),childResource:toArray(e.childResource),service:toArray(e.service),action:toArray(e.action),sourceType:toArray(e.sourceType),sourceId:toArray(e.sourceId),sourceValue:toArray(e.sourceValue),authType:toArray(e.authType),authId:toArray(e.authId),userAgent:toArray(e.userAgent),ipAddress:toArray(e.ipAddress),sessionId:toArray(e.sessionId),agentId:toArray(e.agentId),transportType:toArray(e.transportType),streamType:toArray(e.streamType),originOwnerId:toArray(e.originOwnerId),originOwnerName:toArray(e.originOwnerName),statusCode:toArray(e.statusCode).map(e=>typeof e==`string`?Number.parseInt(e,10):e),isBackground:e.isBackground===void 0?null:+!!e.isBackground,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime),limit:t,offset:n}}}function buildUnifiedLogsCountQuery(e){return{sql:`
|
|
241
|
+
SELECT count() as total
|
|
242
|
+
FROM unified_requests
|
|
243
|
+
WHERE 1=1
|
|
244
|
+
AND ({organizationId:Array(String)} = [] OR organizationId IN {organizationId:Array(String)})
|
|
245
|
+
AND ({projectSecureId:Array(String)} = [] OR projectSecureId IN {projectSecureId:Array(String)})
|
|
246
|
+
AND ({accountSecureId:Array(String)} = [] OR accountSecureId IN {accountSecureId:Array(String)})
|
|
247
|
+
AND ({requestId:Array(String)} = [] OR requestId IN {requestId:Array(String)})
|
|
248
|
+
AND ({connectorKey:Array(String)} = [] OR provider IN {connectorKey:Array(String)})
|
|
249
|
+
AND ({connectorVersion:Array(String)} = [] OR connectorVersion IN {connectorVersion:Array(String)})
|
|
250
|
+
AND ({mode:Array(String)} = [] OR mode IN {mode:Array(String)})
|
|
251
|
+
AND ({httpMethod:Array(String)} = [] OR httpMethod IN {httpMethod:Array(String)})
|
|
252
|
+
AND ({resource:Array(String)} = [] OR resource IN {resource:Array(String)})
|
|
253
|
+
AND ({subResource:Array(String)} = [] OR subResource IN {subResource:Array(String)})
|
|
254
|
+
AND ({childResource:Array(String)} = [] OR childResource IN {childResource:Array(String)})
|
|
255
|
+
AND ({service:Array(String)} = [] OR service IN {service:Array(String)})
|
|
256
|
+
AND ({action:Array(String)} = [] OR action IN {action:Array(String)})
|
|
257
|
+
AND ({sourceType:Array(String)} = [] OR sourceType IN {sourceType:Array(String)})
|
|
258
|
+
AND ({sourceId:Array(String)} = [] OR sourceId IN {sourceId:Array(String)})
|
|
259
|
+
AND ({sourceValue:Array(String)} = [] OR sourceValue IN {sourceValue:Array(String)})
|
|
260
|
+
AND ({authType:Array(String)} = [] OR authType IN {authType:Array(String)})
|
|
261
|
+
AND ({authId:Array(String)} = [] OR authId IN {authId:Array(String)})
|
|
262
|
+
AND ({userAgent:Array(String)} = [] OR userAgent IN {userAgent:Array(String)})
|
|
263
|
+
AND ({ipAddress:Array(String)} = [] OR ipAddress IN {ipAddress:Array(String)})
|
|
264
|
+
AND ({sessionId:Array(String)} = [] OR sessionId IN {sessionId:Array(String)})
|
|
265
|
+
AND ({agentId:Array(String)} = [] OR agentId IN {agentId:Array(String)})
|
|
266
|
+
AND ({transportType:Array(String)} = [] OR transportType IN {transportType:Array(String)})
|
|
267
|
+
AND ({streamType:Array(String)} = [] OR streamType IN {streamType:Array(String)})
|
|
268
|
+
AND ({originOwnerId:Array(String)} = [] OR originOwnerId IN {originOwnerId:Array(String)})
|
|
269
|
+
AND ({originOwnerName:Array(String)} = [] OR originOwnerName IN {originOwnerName:Array(String)})
|
|
270
|
+
AND ({statusCode:Array(Int16)} = [] OR statusCode IN {statusCode:Array(Int16)})
|
|
271
|
+
AND ({isBackground:Nullable(UInt8)} IS NULL OR isBackground = {isBackground:Nullable(UInt8)})
|
|
272
|
+
AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
|
|
273
|
+
AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventDatetime >= {startTime:Nullable(DateTime64(3))})
|
|
274
|
+
AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventDatetime <= {endTime:Nullable(DateTime64(3))})
|
|
275
|
+
`,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),requestId:toArray(e.requestId),connectorKey:toArray(e.connectorKey),connectorVersion:toArray(e.connectorVersion),mode:toArray(e.mode),httpMethod:toArray(e.httpMethod),resource:toArray(e.resource),subResource:toArray(e.subResource),childResource:toArray(e.childResource),service:toArray(e.service),action:toArray(e.action),sourceType:toArray(e.sourceType),sourceId:toArray(e.sourceId),sourceValue:toArray(e.sourceValue),authType:toArray(e.authType),authId:toArray(e.authId),userAgent:toArray(e.userAgent),ipAddress:toArray(e.ipAddress),sessionId:toArray(e.sessionId),agentId:toArray(e.agentId),transportType:toArray(e.transportType),streamType:toArray(e.streamType),originOwnerId:toArray(e.originOwnerId),originOwnerName:toArray(e.originOwnerName),statusCode:toArray(e.statusCode).map(e=>typeof e==`string`?Number.parseInt(e,10):e),isBackground:e.isBackground===void 0?null:+!!e.isBackground,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}registerQuery({id:`project_unified_logs.json`,buildQuery:buildUnifiedLogsQuery,buildCountQuery:buildUnifiedLogsCountQuery});const ne={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`},re=[`requestId`,`resource`,`service`,`subResource`,`childResource`,`action`,`path`,`accountId`,`status`],ie=[`actionRunId`,`actionId`,`actionType`,`category`,`riskLevel`];function shouldIncludeUnified(e){let t=toArray(e.logType);if(t.length>0&&!t.includes(`unified`))return!1;let n=e;for(let e of ie)if(n[e]!==void 0)return!1;return!0}function shouldIncludeActions(e){let t=toArray(e.logType);if(t.length>0&&!t.includes(`action`))return!1;let n=e;for(let e of re)if(n[e]!==void 0)return!1;return!0}function buildUnifiedFilters(){return`AND ({organizationId:Array(String)} = [] OR organizationId IN {organizationId:Array(String)})
|
|
276
|
+
AND ({projectSecureId:Array(String)} = [] OR projectSecureId IN {projectSecureId:Array(String)})
|
|
277
|
+
AND ({accountSecureId:Array(String)} = [] OR accountSecureId IN {accountSecureId:Array(String)})
|
|
278
|
+
AND ({connectorKey:Array(String)} = [] OR provider IN {connectorKey:Array(String)})
|
|
279
|
+
AND ({connectorVersion:Array(String)} = [] OR connectorVersion IN {connectorVersion:Array(String)})
|
|
280
|
+
AND ({connectorOwner:Array(String)} = [] OR connectorOwner IN {connectorOwner:Array(String)})
|
|
281
|
+
AND ({connectorProfileId:Array(String)} = [] OR connectorProfileId IN {connectorProfileId:Array(String)})
|
|
282
|
+
AND ({sourceType:Array(String)} = [] OR sourceType IN {sourceType:Array(String)})
|
|
283
|
+
AND ({sourceId:Array(String)} = [] OR sourceId IN {sourceId:Array(String)})
|
|
284
|
+
AND ({sourceValue:Array(String)} = [] OR sourceValue IN {sourceValue:Array(String)})
|
|
285
|
+
AND ({mode:Array(String)} = [] OR mode IN {mode:Array(String)})
|
|
286
|
+
AND ({httpMethod:Array(String)} = [] OR httpMethod IN {httpMethod:Array(String)})
|
|
287
|
+
AND ({originOwnerId:Array(String)} = [] OR originOwnerId IN {originOwnerId:Array(String)})
|
|
288
|
+
AND ({originOwnerName:Array(String)} = [] OR originOwnerName IN {originOwnerName:Array(String)})
|
|
289
|
+
AND ({statusCode:Array(Int16)} = [] OR statusCode IN {statusCode:Array(Int16)})
|
|
290
|
+
AND ({isBackground:Nullable(UInt8)} IS NULL OR isBackground = {isBackground:Nullable(UInt8)})
|
|
291
|
+
AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})`}function buildActionsFilters(){return`AND ({organizationId:Array(String)} = [] OR organizationId IN {organizationId:Array(String)})
|
|
292
|
+
AND ({projectSecureId:Array(String)} = [] OR projectSecureId IN {projectSecureId:Array(String)})
|
|
293
|
+
AND ({accountSecureId:Array(String)} = [] OR accountSecureId IN {accountSecureId:Array(String)})
|
|
294
|
+
AND ({connectorKey:Array(String)} = [] OR connectorKey IN {connectorKey:Array(String)})
|
|
295
|
+
AND ({connectorVersion:Array(String)} = [] OR connectorVersion IN {connectorVersion:Array(String)})
|
|
296
|
+
AND ({connectorOwner:Array(String)} = [] OR connectorOwner IN {connectorOwner:Array(String)})
|
|
297
|
+
AND ({connectorProfileId:Array(String)} = [] OR connectorProfileId IN {connectorProfileId:Array(String)})
|
|
298
|
+
AND ({sourceType:Array(String)} = [] OR sourceType IN {sourceType:Array(String)})
|
|
299
|
+
AND ({sourceId:Array(String)} = [] OR sourceId IN {sourceId:Array(String)})
|
|
300
|
+
AND ({sourceValue:Array(String)} = [] OR sourceValue IN {sourceValue:Array(String)})
|
|
301
|
+
AND ({mode:Array(String)} = [] OR mode IN {mode:Array(String)})
|
|
302
|
+
AND ({httpMethod:Array(String)} = [] OR httpMethod IN {httpMethod:Array(String)})
|
|
303
|
+
AND ({originOwnerId:Array(String)} = [] OR originOwnerId IN {originOwnerId:Array(String)})
|
|
304
|
+
AND ({originOwnerName:Array(String)} = [] OR originOwnerName IN {originOwnerName:Array(String)})
|
|
305
|
+
AND ({statusCode:Array(Int16)} = [] OR statusCode IN {statusCode:Array(Int16)})
|
|
306
|
+
AND ({isBackground:Nullable(UInt8)} IS NULL OR isBackground = {isBackground:Nullable(UInt8)})
|
|
307
|
+
AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})`}function buildUnifiedSelect(){return`
|
|
308
|
+
SELECT
|
|
309
|
+
eventDatetime as eventTime,
|
|
310
|
+
startTime,
|
|
311
|
+
toNullable(endTime) as endTime,
|
|
312
|
+
toNullable(duration) as durationMs,
|
|
313
|
+
organizationId,
|
|
314
|
+
projectSecureId,
|
|
315
|
+
accountSecureId,
|
|
316
|
+
provider as connectorKey,
|
|
317
|
+
connectorVersion,
|
|
318
|
+
connectorOwner,
|
|
319
|
+
connectorProfileId,
|
|
320
|
+
toLowCardinality(sourceType) as sourceType,
|
|
321
|
+
toLowCardinality(sourceId) as sourceId,
|
|
322
|
+
authType,
|
|
323
|
+
authId,
|
|
324
|
+
sessionId,
|
|
325
|
+
agentId,
|
|
326
|
+
userAgent,
|
|
327
|
+
ipAddress,
|
|
328
|
+
transportType,
|
|
329
|
+
streamType,
|
|
330
|
+
sourceValue,
|
|
331
|
+
originOwnerId,
|
|
332
|
+
originOwnerName,
|
|
333
|
+
toLowCardinality(mode) as mode,
|
|
334
|
+
toLowCardinality(toNullable(httpMethod)) as httpMethod,
|
|
335
|
+
toNullable(url) as url,
|
|
336
|
+
toUInt8(success) as success,
|
|
337
|
+
requestId as logId,
|
|
338
|
+
advancedExpiresAt,
|
|
339
|
+
CAST(NULL AS Nullable(DateTime64(3))) as defenderExpiresAt,
|
|
340
|
+
-- non-common fields
|
|
341
|
+
requestId,
|
|
342
|
+
path,
|
|
343
|
+
resource,
|
|
344
|
+
subResource,
|
|
345
|
+
childResource,
|
|
346
|
+
service,
|
|
347
|
+
action,
|
|
348
|
+
toInt16(status) as status,
|
|
349
|
+
accountId,
|
|
350
|
+
provider,
|
|
351
|
+
isWorker,
|
|
352
|
+
isBackground,
|
|
353
|
+
CAST(NULL AS Nullable(String)) as actionRunId,
|
|
354
|
+
CAST(NULL AS Nullable(String)) as actionId,
|
|
355
|
+
CAST(NULL AS Nullable(String)) as actionType,
|
|
356
|
+
CAST(NULL AS Nullable(String)) as category,
|
|
357
|
+
statusCode,
|
|
358
|
+
CAST(NULL AS Nullable(String)) as message,
|
|
359
|
+
CAST(NULL AS Nullable(String)) as riskLevel,
|
|
360
|
+
CAST(NULL AS Nullable(Float32)) as tier2Score,
|
|
361
|
+
'unified' as logType
|
|
362
|
+
FROM unified_requests
|
|
363
|
+
WHERE 1=1
|
|
364
|
+
${buildUnifiedFilters()}
|
|
365
|
+
AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventDatetime >= {startTime:Nullable(DateTime64(3))})
|
|
366
|
+
AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventDatetime <= {endTime:Nullable(DateTime64(3))})
|
|
367
|
+
`}function buildActionsSelect(){return`
|
|
368
|
+
SELECT
|
|
369
|
+
eventTime,
|
|
370
|
+
startTime,
|
|
371
|
+
endTime,
|
|
372
|
+
durationMs,
|
|
373
|
+
organizationId,
|
|
374
|
+
projectSecureId,
|
|
375
|
+
accountSecureId,
|
|
376
|
+
connectorKey,
|
|
377
|
+
connectorVersion,
|
|
378
|
+
connectorOwner,
|
|
379
|
+
connectorProfileId,
|
|
380
|
+
toLowCardinality(sourceType) as sourceType,
|
|
381
|
+
toLowCardinality(sourceId) as sourceId,
|
|
382
|
+
authType,
|
|
383
|
+
authId,
|
|
384
|
+
sessionId,
|
|
385
|
+
agentId,
|
|
386
|
+
userAgent,
|
|
387
|
+
ipAddress,
|
|
388
|
+
transportType,
|
|
389
|
+
streamType,
|
|
390
|
+
sourceValue,
|
|
391
|
+
originOwnerId,
|
|
392
|
+
originOwnerName,
|
|
393
|
+
toLowCardinality(mode) as mode,
|
|
394
|
+
toLowCardinality(httpMethod) as httpMethod,
|
|
395
|
+
url,
|
|
396
|
+
success,
|
|
397
|
+
actionRunId as logId,
|
|
398
|
+
advancedExpiresAt,
|
|
399
|
+
defenderExpiresAt,
|
|
400
|
+
-- non-common fields
|
|
401
|
+
CAST(NULL AS Nullable(String)) as requestId,
|
|
402
|
+
CAST(NULL AS Nullable(String)) as path,
|
|
403
|
+
CAST(NULL AS Nullable(String)) as resource,
|
|
404
|
+
CAST(NULL AS Nullable(String)) as subResource,
|
|
405
|
+
CAST(NULL AS Nullable(String)) as childResource,
|
|
406
|
+
CAST(NULL AS Nullable(String)) as service,
|
|
407
|
+
CAST(NULL AS Nullable(String)) as action,
|
|
408
|
+
CAST(NULL AS Nullable(Int16)) as status,
|
|
409
|
+
CAST(NULL AS Nullable(String)) as accountId,
|
|
410
|
+
CAST(NULL AS Nullable(String)) as provider,
|
|
411
|
+
CAST(NULL AS Nullable(UInt8)) as isWorker,
|
|
412
|
+
isBackground,
|
|
413
|
+
actionRunId,
|
|
414
|
+
actionId,
|
|
415
|
+
actionType,
|
|
416
|
+
category,
|
|
417
|
+
statusCode,
|
|
418
|
+
message,
|
|
419
|
+
riskLevel,
|
|
420
|
+
tier2Score,
|
|
421
|
+
'action' as logType
|
|
422
|
+
FROM actions
|
|
423
|
+
WHERE 1=1
|
|
424
|
+
${buildActionsFilters()}
|
|
425
|
+
AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventTime >= {startTime:Nullable(DateTime64(3))})
|
|
426
|
+
AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventTime <= {endTime:Nullable(DateTime64(3))})
|
|
427
|
+
`}function buildCombinedLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize),r=sanitizeOrderBy(e.orderBy,ne,`eventTime`),i=sanitizeOrderDirection(e.orderDirection),a=shouldIncludeUnified(e),o=shouldIncludeActions(e),s;return s=a&&o?`${buildUnifiedSelect()} UNION ALL ${buildActionsSelect()}`:a?buildUnifiedSelect():o?buildActionsSelect():`${buildUnifiedSelect()} AND 1 = 0`,{sql:`
|
|
428
|
+
WITH combined AS (
|
|
429
|
+
${s}
|
|
430
|
+
)
|
|
431
|
+
SELECT * FROM combined
|
|
432
|
+
ORDER BY ${r} ${i}
|
|
433
|
+
LIMIT {limit:UInt32}
|
|
434
|
+
OFFSET {offset:UInt32}
|
|
435
|
+
`,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),connectorKey:toArray(e.connectorKey),connectorVersion:toArray(e.connectorVersion),connectorOwner:toArray(e.connectorOwner),connectorProfileId:toArray(e.connectorProfileId),sourceType:toArray(e.sourceType),sourceId:toArray(e.sourceId),sourceValue:toArray(e.sourceValue),mode:toArray(e.mode),httpMethod:toArray(e.httpMethod),originOwnerId:toArray(e.originOwnerId),originOwnerName:toArray(e.originOwnerName),statusCode:toArray(e.statusCode).map(e=>typeof e==`string`?Number.parseInt(e,10):e),isBackground:e.isBackground===void 0?null:+!!e.isBackground,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime),limit:t,offset:n}}}function buildCombinedLogsCountQuery(e){let t=shouldIncludeUnified(e),n=shouldIncludeActions(e),r=[];return t&&r.push(`
|
|
436
|
+
SELECT count() as cnt
|
|
437
|
+
FROM unified_requests
|
|
438
|
+
WHERE 1=1
|
|
439
|
+
${buildUnifiedFilters()}
|
|
440
|
+
AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventDatetime >= {startTime:Nullable(DateTime64(3))})
|
|
441
|
+
AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventDatetime <= {endTime:Nullable(DateTime64(3))})
|
|
442
|
+
`),n&&r.push(`
|
|
443
|
+
SELECT count() as cnt
|
|
444
|
+
FROM actions
|
|
445
|
+
WHERE 1=1
|
|
446
|
+
${buildActionsFilters()}
|
|
447
|
+
AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventTime >= {startTime:Nullable(DateTime64(3))})
|
|
448
|
+
AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventTime <= {endTime:Nullable(DateTime64(3))})
|
|
449
|
+
`),{sql:r.length>0?`SELECT sum(cnt) as total FROM (${r.join(` UNION ALL `)})`:`SELECT 0 as total`,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),connectorKey:toArray(e.connectorKey),connectorVersion:toArray(e.connectorVersion),connectorOwner:toArray(e.connectorOwner),connectorProfileId:toArray(e.connectorProfileId),sourceType:toArray(e.sourceType),sourceId:toArray(e.sourceId),sourceValue:toArray(e.sourceValue),mode:toArray(e.mode),httpMethod:toArray(e.httpMethod),originOwnerId:toArray(e.originOwnerId),originOwnerName:toArray(e.originOwnerName),statusCode:toArray(e.statusCode).map(e=>typeof e==`string`?Number.parseInt(e,10):e),isBackground:e.isBackground===void 0?null:+!!e.isBackground,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}registerQuery({id:`project_logs.json`,buildQuery:buildCombinedLogsQuery,buildCountQuery:buildCombinedLogsCountQuery});const E={connectorKey:`connectorKey`,success:`success`,actionType:`actionType`,mode:`mode`,service:`service`,resource:`resource`,actionId:`actionId`,httpMethod:`httpMethod`,accountSecureId:`accountSecureId`,sourceType:`sourceType`,statusCode:`statusCode`,originOwnerId:`originOwnerId`,sourceId:`sourceId`,isBackground:`isBackground`},ae={minute:`toStartOfMinute`,hour:`toStartOfHour`,day:`toStartOfDay`,week:`toStartOfWeek`,month:`toStartOfMonth`},oe={minute:60,hour:3600,day:86400,week:604800,month:2592e3};function buildAggregationQuery(e){let t=toArray(e.dimensions),n=e.intervalType??`hour`,r=e.intervalPeriod??1,i=t.filter(e=>E[e]).map(e=>E[e]),a=i.length>0?`, ${i.join(`, `)}`:``,o=i.length>0?`, ${i.join(`, `)}`:``,s=ae[n]??`toStartOfHour`,c=r*(oe[n]??3600);return{sql:`
|
|
450
|
+
SELECT
|
|
451
|
+
${r>1?`toDateTime(intDiv(toUnixTimestamp(${s}(eventTime)), ${c}) * ${c})`:`${s}(eventTime)`} as startTime,
|
|
452
|
+
count() as count
|
|
453
|
+
${a}
|
|
454
|
+
FROM actions
|
|
455
|
+
WHERE 1=1
|
|
456
|
+
AND ({organizationId:Array(String)} = [] OR organizationId IN {organizationId:Array(String)})
|
|
457
|
+
AND ({projectSecureId:Array(String)} = [] OR projectSecureId IN {projectSecureId:Array(String)})
|
|
458
|
+
AND ({accountSecureId:Array(String)} = [] OR accountSecureId IN {accountSecureId:Array(String)})
|
|
459
|
+
AND ({connectorKey:Array(String)} = [] OR connectorKey IN {connectorKey:Array(String)})
|
|
460
|
+
AND ({actionType:Array(String)} = [] OR actionType IN {actionType:Array(String)})
|
|
461
|
+
AND ({mode:Array(String)} = [] OR mode IN {mode:Array(String)})
|
|
462
|
+
AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
|
|
463
|
+
AND ({isBackground:Nullable(UInt8)} IS NULL OR isBackground = {isBackground:Nullable(UInt8)})
|
|
464
|
+
AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventTime >= {startTime:Nullable(DateTime64(3))})
|
|
465
|
+
AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventTime <= {endTime:Nullable(DateTime64(3))})
|
|
466
|
+
GROUP BY startTime ${o}
|
|
467
|
+
ORDER BY startTime ASC
|
|
468
|
+
`,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),connectorKey:toArray(e.connectorKey),actionType:toArray(e.actionType),mode:toArray(e.mode),success:e.success===void 0?null:+!!e.success,isBackground:e.isBackground===void 0?null:+!!e.isBackground,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}registerQuery({id:`project_logs_aggregation.json`,buildQuery:buildAggregationQuery});const D={connectorKey:`connectorKey`,success:`success`,actionType:`actionType`,mode:`mode`,service:`service`,resource:`resource`,actionId:`actionId`,httpMethod:`httpMethod`,accountSecureId:`accountSecureId`,sourceType:`sourceType`,statusCode:`statusCode`,originOwnerId:`originOwnerId`,sourceId:`sourceId`,isBackground:`isBackground`},O=new Set([`connectorKey`,`actionType`,`mode`,`service`,`resource`,`actionId`,`httpMethod`,`accountSecureId`,`sourceType`,`originOwnerId`,`sourceId`]);function buildDimensionsQuery(e){let t=toArray(e.dimensions),n=e.maxValues??100;if(t.length===0)return{sql:`SELECT 1 WHERE 0`,params:{}};let r=t.filter(e=>D[e]).map(e=>{let t=D[e];return`
|
|
469
|
+
SELECT
|
|
470
|
+
'${e}' as dimension,
|
|
471
|
+
toString(${t}) as value,
|
|
472
|
+
count() as count
|
|
473
|
+
FROM actions
|
|
474
|
+
WHERE 1=1
|
|
475
|
+
AND ({organizationId:Array(String)} = [] OR organizationId IN {organizationId:Array(String)})
|
|
476
|
+
AND ({projectSecureId:Array(String)} = [] OR projectSecureId IN {projectSecureId:Array(String)})
|
|
477
|
+
AND ({accountSecureId:Array(String)} = [] OR accountSecureId IN {accountSecureId:Array(String)})
|
|
478
|
+
AND ({connectorKey:Array(String)} = [] OR connectorKey IN {connectorKey:Array(String)})
|
|
479
|
+
AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
|
|
480
|
+
AND ({isBackground:Nullable(UInt8)} IS NULL OR isBackground = {isBackground:Nullable(UInt8)})
|
|
481
|
+
AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventTime >= {startTime:Nullable(DateTime64(3))})
|
|
482
|
+
AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventTime <= {endTime:Nullable(DateTime64(3))})
|
|
483
|
+
AND ${t} IS NOT NULL
|
|
484
|
+
${O.has(e)?`AND ${t} != ''`:``}
|
|
485
|
+
GROUP BY ${t}
|
|
486
|
+
ORDER BY count DESC
|
|
487
|
+
LIMIT {maxValues:UInt32}
|
|
488
|
+
`});return{sql:r.length>0?r.join(`
|
|
489
|
+
UNION ALL
|
|
490
|
+
`):`SELECT 1 WHERE 0`,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),connectorKey:toArray(e.connectorKey),success:e.success===void 0?null:+!!e.success,isBackground:e.isBackground===void 0?null:+!!e.isBackground,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime),maxValues:n}}}registerQuery({id:`project_logs_dimensions.json`,buildQuery:buildDimensionsQuery});const k={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`};function buildProviderLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
|
|
491
|
+
SELECT
|
|
492
|
+
eventDatetime as eventTime,
|
|
493
|
+
startTime,
|
|
494
|
+
endTime,
|
|
495
|
+
duration as durationMs,
|
|
496
|
+
organizationId,
|
|
497
|
+
projectSecureId,
|
|
498
|
+
accountSecureId,
|
|
499
|
+
requestId,
|
|
500
|
+
id,
|
|
501
|
+
provider as connectorKey,
|
|
502
|
+
connectorVersion,
|
|
503
|
+
action,
|
|
504
|
+
mode,
|
|
505
|
+
httpMethod,
|
|
506
|
+
originOwnerId,
|
|
507
|
+
originOwnerName,
|
|
508
|
+
url,
|
|
509
|
+
path,
|
|
510
|
+
resource,
|
|
511
|
+
subResource,
|
|
512
|
+
childResource,
|
|
513
|
+
service,
|
|
514
|
+
success,
|
|
515
|
+
statusCode,
|
|
516
|
+
isWorker,
|
|
517
|
+
status,
|
|
518
|
+
provider,
|
|
519
|
+
'provider' as logType
|
|
520
|
+
FROM provider_requests
|
|
521
|
+
WHERE 1=1
|
|
522
|
+
AND ({organizationId:Array(String)} = [] OR organizationId IN {organizationId:Array(String)})
|
|
523
|
+
AND ({projectSecureId:Array(String)} = [] OR projectSecureId IN {projectSecureId:Array(String)})
|
|
524
|
+
AND ({accountSecureId:Array(String)} = [] OR accountSecureId IN {accountSecureId:Array(String)})
|
|
525
|
+
AND ({requestId:Array(String)} = [] OR requestId IN {requestId:Array(String)})
|
|
526
|
+
AND ({id:Array(String)} = [] OR id IN {id:Array(String)})
|
|
527
|
+
AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
|
|
528
|
+
AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventDatetime >= {startTime:Nullable(DateTime64(3))})
|
|
529
|
+
AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventDatetime <= {endTime:Nullable(DateTime64(3))})
|
|
530
|
+
ORDER BY ${sanitizeOrderBy(e.orderBy,k,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
|
|
531
|
+
LIMIT {limit:UInt32}
|
|
532
|
+
OFFSET {offset:UInt32}
|
|
533
|
+
`,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),requestId:toArray(e.requestId),id:toArray(e.id),success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime),limit:t,offset:n}}}function buildProviderLogsCountQuery(e){return{sql:`
|
|
534
|
+
SELECT count() as total
|
|
535
|
+
FROM provider_requests
|
|
536
|
+
WHERE 1=1
|
|
537
|
+
AND ({organizationId:Array(String)} = [] OR organizationId IN {organizationId:Array(String)})
|
|
538
|
+
AND ({projectSecureId:Array(String)} = [] OR projectSecureId IN {projectSecureId:Array(String)})
|
|
539
|
+
AND ({accountSecureId:Array(String)} = [] OR accountSecureId IN {accountSecureId:Array(String)})
|
|
540
|
+
AND ({requestId:Array(String)} = [] OR requestId IN {requestId:Array(String)})
|
|
541
|
+
AND ({id:Array(String)} = [] OR id IN {id:Array(String)})
|
|
542
|
+
AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
|
|
543
|
+
AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventDatetime >= {startTime:Nullable(DateTime64(3))})
|
|
544
|
+
AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventDatetime <= {endTime:Nullable(DateTime64(3))})
|
|
545
|
+
`,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),requestId:toArray(e.requestId),id:toArray(e.id),success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}registerQuery({id:`project_provider_logs.json`,buildQuery:buildProviderLogsQuery,buildCountQuery:buildProviderLogsCountQuery});function buildSourceUsageQuery(e){return{sql:`
|
|
546
|
+
SELECT
|
|
547
|
+
sourceId,
|
|
548
|
+
sourceType,
|
|
549
|
+
count() as request_count,
|
|
550
|
+
max(eventDatetime) as last_request
|
|
551
|
+
FROM unified_requests
|
|
552
|
+
WHERE 1=1
|
|
553
|
+
AND ({organizationId:Array(String)} = [] OR organizationId IN {organizationId:Array(String)})
|
|
554
|
+
AND ({projectSecureId:Array(String)} = [] OR projectSecureId IN {projectSecureId:Array(String)})
|
|
555
|
+
AND ({sourceType:Array(String)} = [] OR sourceType IN {sourceType:Array(String)})
|
|
556
|
+
AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventDatetime >= {startTime:Nullable(DateTime64(3))})
|
|
557
|
+
AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventDatetime <= {endTime:Nullable(DateTime64(3))})
|
|
558
|
+
AND sourceId IS NOT NULL
|
|
559
|
+
AND sourceId != ''
|
|
560
|
+
GROUP BY sourceId, sourceType
|
|
561
|
+
ORDER BY request_count DESC
|
|
562
|
+
`,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),sourceType:toArray(e.sourceType),startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}registerQuery({id:`project_source_usage.json`,buildQuery:buildSourceUsageQuery});var SchemaValidationError$1=class extends Error{static{e(this,`SchemaValidationError`)}constructor(e,t){super(e),this.name=`SchemaValidationError`,this.cause=t}},ClickHouseClient=class{#e;#t;#n;constructor(e,n){this.#t=e,this.#n=n,e?.url&&(this.#e=t({url:e.url,username:e.username,password:e.password,database:e.database,request_timeout:e.requestTimeout??3e4,compression:{request:!0,response:!0}}))}async query(e){try{let t=await this.#a(e.endpoint,e.params);return this.#i(t.data,e.schema)}catch(t){if(t instanceof SchemaValidationError$1)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error Querying clickhouse endpoint ${e.endpoint}: ${n}`,category:`ClickHouseClient`,code:`ClickHouseQueryError`}),t}}async queryWithPagination(e){try{let t=await this.#a(e.endpoint,e.params),n=this.#i(t.data,e.schema);return{data:n,total:t.rows_before_limit_at_least??t.rows??n.length,pageNumber:e.pageNumber??1,pageSize:e.pageSize??n.length}}catch(t){if(t instanceof SchemaValidationError$1)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error Querying clickhouse endpoint ${e.endpoint}: ${n}`,category:`ClickHouseClient`,code:`ClickHouseQueryError`}),t}}async queryRaw(e){try{let t=await this.#a(e.endpoint,e.params);return t.data=this.#i(t.data,e.schema),t}catch(t){if(t instanceof SchemaValidationError$1)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error Querying clickhouse endpoint ${e.endpoint}: ${n}`,category:`ClickHouseClient`,code:`ClickHouseQueryError`}),t}}isReady(){return!!(this.#e&&this.#t?.url)}async close(){await this.#e?.close()}#r(){if(!this.#e)throw this.#n?.error({message:`ClickHouse client not initialized`,category:`ClickHouseClient`,code:`ClientNotReady`}),Error(`ClickHouse client is not initialized`);if(!this.#t?.url)throw this.#n?.warning({message:`Missing ClickHouse URL`,category:`ClickHouseClient`}),Error(`ClickHouseClient - Missing URL`);return this.#e}#i(e,t){if(!t)return e;try{let n=e.map(e=>t.parse(e));return this.#n?.debug({message:`Schema validation passed for ${n.length} rows`,category:`ClickHouseClient`}),n}catch(e){let t=e instanceof Error?e.message:String(e);throw this.#n?.error({message:`Schema validation failed: ${t}`,category:`ClickHouseClient`,code:`SchemaValidationError`,error:e}),new SchemaValidationError$1(t,e)}}async#a(e,t){let n=this.#r(),r=getQueryDefinition(e);if(!r)throw Error(`Unknown endpoint: ${e}. No query definition registered.`);let{sql:i,params:a}=r.buildQuery(t??{});this.#n?.debug({message:`Querying clickhouse endpoint: ${e}`,category:`ClickHouseClient`,context:{endpoint:e,params:t}});let o=Date.now(),s=await(await n.query({query:i,query_params:a,format:`JSONEachRow`})).json(),c=(Date.now()-o)/1e3,l;if(r.buildCountQuery){let{sql:e,params:i}=r.buildCountQuery(t??{});l=(await(await n.query({query:e,query_params:i,format:`JSONEachRow`})).json())[0]?.total}return this.#n?.debug({message:`ClickHouse query returned ${s.length} rows`,category:`ClickHouseClient`,context:{endpoint:e,rows:s.length,elapsed:c}}),{meta:[],data:s,rows:s.length,rows_before_limit_at_least:l,statistics:{elapsed:c,rows_read:s.length,bytes_read:0}}}},SchemaValidationError=class extends Error{constructor(e,t){super(e),this.name=`SchemaValidationError`,this.cause=t}},TinybirdClient=class{#e;#t;#n;constructor(e,t,n){this.#e=e,this.#t=t,this.#n=n}async query(e){try{let t=await this.#o(e.endpoint,e.params);return this.#a(t.data,e.schema)}catch(t){if(t instanceof SchemaValidationError)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error Querying tinybird endpoint ${e.endpoint}: ${n}`,category:`TinybirdClient`,code:`TinybirdQueryError`}),t}}async queryWithPagination(e){try{let t=await this.#o(e.endpoint,e.params),n=this.#a(t.data,e.schema);return{data:n,total:t.rows_before_limit_at_least??t.rows??n.length,pageNumber:e.pageNumber??1,pageSize:e.pageSize??n.length}}catch(t){if(t instanceof SchemaValidationError)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error Querying tinybird endpoint ${e.endpoint}: ${n}`,category:`TinybirdClient`,code:`TinybirdQueryError`}),t}}async queryRaw(e){try{let t=await this.#o(e.endpoint,e.params);return t.data=this.#a(t.data,e.schema),t}catch(t){if(t instanceof SchemaValidationError)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error Querying tinybird endpoint ${e.endpoint}: ${n}`,category:`TinybirdClient`,code:`TinybirdQueryError`}),t}}isReady(){return!!(this.#e&&this.#t?.token)}#r(){return new n.Agent({})}#i(){if(!this.#e)throw this.#n?.error({message:`HTTP client not initialized, cannot perform Tinybird query`,category:`TinybirdClient`,code:`HttpClientNotReady`}),Error(`HTTP client is not initialized`);if(!this.#t?.token)throw this.#n?.warning({message:`Missing OLAP token, cannot perform Tinybird query`,category:`TinybirdClient`}),Error(`TinybirdClient - Missing token`)}#a(e,t){if(!t)return e;try{let n=e.map(e=>t.parse(e));return this.#n?.debug({message:`Schema validation passed for ${n.length} rows`,category:`TinybirdClient`}),n}catch(e){let t=e instanceof Error?e.message:String(e);throw this.#n?.error({message:`Schema validation failed: ${t}`,category:`TinybirdClient`,code:`SchemaValidationError`,error:e}),new SchemaValidationError(t,e)}}async#o(e,t){this.#i();let n=this.#e,r=this.#t;if(!n||!r)throw Error(`Client validation failed`);let i=new URL(`/v0/pipes/${e}`,r.baseUrl);this.#n?.debug({message:`Querying tinybird endpoint: ${e}`,category:`TinybirdClient`,context:{endpoint:e,params:t}});let a=await n.request({method:`post`,url:i.toString(),payload:t,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${r.token}`},...r.allowHttp&&{httpAgent:this.#r()}});return this.#n?.debug({message:`Tinybird query returned ${a.data.data.length} rows`,category:`TinybirdClient`,context:{endpoint:e,rows:a.data.rows,statistics:a.data.statistics}}),a.data}};function createOlapQueryClient(e,t,n){switch(e.type){case`clickhouse`:if(!e.clickhouse)throw Error(`ClickHouse config required when type is "clickhouse"`);return new ClickHouseClient(e.clickhouse,n);default:return new TinybirdClient(t,e.tinybird,n)}}function createConfigFromEnv(){let e=process.env.TINYBIRD_BASE_URL,t=process.env.TINYBIRD_TOKEN,n=e&&t?{baseUrl:e,token:t,allowHttp:process.env.TINYBIRD_ALLOW_HTTP===`true`}:void 0,r=process.env.CLICKHOUSE_URL,i=r?{url:r,username:process.env.CLICKHOUSE_USER,password:process.env.CLICKHOUSE_PASSWORD,database:process.env.CLICKHOUSE_DATABASE??`olap`,requestTimeout:(()=>{if(!process.env.CLICKHOUSE_TIMEOUT)return;let e=Number.parseInt(process.env.CLICKHOUSE_TIMEOUT,10);return Number.isFinite(e)?e:void 0})()}:void 0;return{type:n?`tinybird`:i?`clickhouse`:`tinybird`,tinybird:n,clickhouse:i}}const A={Action:`action`,Step:`step`,Unified:`unified`,Provider:`provider`},j={StartTime:`startTime`,EndTime:`endTime`,EventTime:`eventTime`,DurationMs:`durationMs`},M={Asc:`asc`,Desc:`desc`},N={Minute:`minute`,Hour:`hour`,Day:`day`,Week:`week`,Month:`month`},P={ConnectorKey:`connectorKey`,Success:`success`,ActionType:`actionType`,Mode:`mode`,Service:`service`,Resource:`resource`,ActionId:`actionId`,HttpMethod:`httpMethod`,AccountSecureId:`accountSecureId`,SourceType:`sourceType`,StatusCode:`statusCode`,OriginOwnerId:`originOwnerId`,SourceId:`sourceId`,IsBackground:`isBackground`},F={RequestTester:`REQUEST_TESTER`,ActionTester:`ACTION_TESTER`,Discode:`DISCODE`,Dashboard:`DASHBOARD`,Playground:`PLAYGROUND`,SDK:`SDK`,API:`API`,Scheduler:`SCHEDULER`,Webhook:`WEBHOOK`,Agent:`AGENT`,Application:`APPLICATION`,DataSync:`DATA_SYNC`,Internal:`INTERNAL`},I={HTTP:`HTTP`,MCP:`MCP`,ActionRPC:`ACTION_RPC`,WebSocket:`WEBSOCKET`},L={HTTP:`HTTP`,WebSocket:`WEBSOCKET`,SSE:`SSE`},R={APIKey:`API_KEY`,SessionToken:`SESSION_TOKEN`,UserSession:`USER_SESSION`,Cookie:`COOKIE`,Webhook:`WEBHOOK`,Signature:`SIGNATURE`},z=[`refresh_authentication`,`data_sync`,`test_action`,`webhook_setup`],B=[F.Scheduler,F.DataSync,F.Internal],V=[`data_sync`],H=[F.DataSync];function isBackgroundLog(e,t){return!!(e&&z.includes(e)||t&&B.includes(t))}function isDataSync(e,t){return!!(e&&V.includes(e)||t&&H.includes(t))}const safeSerialize=e=>{try{return JSON.stringify(e)}catch{return`[Unserializable payload]`}},U=[`x-datadog-parent-id`,`x-datadog-sampling-priority`,`x-datadog-tags`,`x-datadog-trace-id`,`x-forwarded-proto`,`x-forwarded-port`,`x-forwarded-for`,`x-amzn-trace-id`,`traceparent`,`tracestate`,`x-request-nonce`,`x-signing-method`,`x-signature`,`host`,`via`],W=[`application/octet-stream`,`application/pdf`,`application/msword`,`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,`application/vnd.ms-excel`,`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,`application/zip`,`application/x-zip-compressed`],G=[`image/`,`audio/`,`video/`,`application/vnd.`,`binary`];var AdvancedSink=class{#e;#t;#n;#r;constructor(e,t,n){this.#e=e,this.#t=t?.bucket,this.#n=t?.maxItemSizeBytes??10485760,this.#r=n}async initialize(){if(!this.#e){this.#r?.warning({message:`No s3 client provided, advanced sink will not function`,category:`AdvancedSink`});return}}requireBucket(){if(!this.#t)throw Error(`Advanced sink bucket is not configured`);return this.#t}async sendAction(e,t,n){return(await this.sendActions([{input:e,result:t}],n))[0]??null}async sendActions(e,t){let n=[];for(let{input:r,result:i}of e){if(this.#r?.debug({message:`Advanced sink called to send action`,category:`AdvancedSink`,context:{mode:r.mode,actionId:r.actionId,actionRunId:r.actionRunId,success:i.success,statusCode:i.statusCode,options:{enabled:t?.enabled,errorsOnly:t?.errorsOnly,includeBackground:t?.includeBackground,ttl:t?.ttl}}}),!t?.enabled){this.#r?.debug({message:`Advanced sink is disabled, skipping sending action to advanced sink`,category:`AdvancedSink`}),n.push(null);continue}if(isDataSync(r.mode,r.sourceType)){this.#r?.debug({message:`Advanced sink does not record data sync, skipping sending action to advanced sink`,category:`AdvancedSink`}),n.push(null);continue}if(t.errorsOnly&&i.success){this.#r?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful action for ${r.mode||`action`}`,category:`AdvancedSink`}),n.push(null);continue}if(isBackgroundLog(r.mode,r.sourceType)&&!t.includeBackground){this.#r?.debug({message:`Advanced sink is configured to exclude background logs, skipping action with mode ${r.mode}`,category:`AdvancedSink`}),n.push(null);continue}let e=this.createActionS3(r,i,t?.ttl),a=await this.send(e,t?.ttl);n.push(a)}return n}async sendStep(e,t,n){if(this.#r?.debug({message:`Advanced sink called to send step`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,success:t.success,options:{enabled:n?.enabled,errorsOnly:n?.errorsOnly,includeBackground:n?.includeBackground,ttl:n?.ttl}}}),!n?.enabled)return this.#r?.debug({message:`Advanced sink is disabled, skipping sending step to advanced sink`,category:`AdvancedSink`}),null;if(isDataSync(e.actionMode))return this.#r?.debug({message:`Advanced sink does not record data sync, skipping sending step to advanced sink`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,stepIndex:e.stepIndex}}),null;if(n.errorsOnly&&e.actionSuccess===!0)return this.#r?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful action for ${e.actionMode||`action`}`,category:`AdvancedSink`}),null;if(isBackgroundLog(e.actionMode)&&!n.includeBackground)return this.#r?.debug({message:`Advanced sink is configured to exclude background logs, skipping action with mode ${e.actionMode}`,category:`AdvancedSink`}),null;let r=this.createStepS3(e,t,n?.ttl);try{return await this.send(r,n?.ttl)}catch(t){return this.#r?.error({message:`Failed to send step to advanced sink`,error:t,code:`AdvancedStepWriteError`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,stepIndex:e.stepIndex}}),null}}async sendSteps(e,t){let n=[];for(let{input:r,result:i}of e){let e=await this.sendStep(r,i,t);n.push(e)}return n}async sendUnified(e,t,n){if(!n?.enabled)return this.#r?.debug({message:`Advanced sink is disabled, skipping sending unified to advanced sink`,category:`AdvancedSink`}),null;if(n.errorsOnly&&t.success)return this.#r?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful unified request`,category:`AdvancedSink`}),null;if(isBackgroundLog(e.mode,e.sourceType)&&!n.includeBackground)return this.#r?.debug({message:`Advanced sink is configured to exclude background logs, skipping unified with mode ${e.mode}`,category:`AdvancedSink`}),null;this.#r?.debug({message:`Sending unified to advanced sink`,category:`AdvancedSink`});let r=this.createUnifiedS3(e,t,n?.ttl);try{return await this.send(r,n?.ttl)}catch(t){return this.#r?.error({message:`Failed to send unified to advanced sink`,error:t,code:`AdvancedUnifiedWriteError`,category:`AdvancedSink`,context:{requestId:e.requestId}}),null}}async sendProvider(e,t,n){if(!n?.enabled)return this.#r?.debug({message:`Advanced sink is disabled, skipping sending provider to advanced sink`,category:`AdvancedSink`}),null;this.#r?.debug({message:`Sending provider to advanced sink`,category:`AdvancedSink`});let r=this.createProviderS3(e,t,n?.ttl);try{return await this.send(r,n?.ttl)}catch(t){return this.#r?.error({message:`Failed to send provider to advanced sink`,error:t,code:`AdvancedProviderWriteError`,category:`AdvancedSink`,context:{requestId:e.requestId}}),null}}async getAction(e,t,n){if(!this.#e){this.#r?.warning({message:`No s3 client available, cannot get action log from advanced sink`,category:`AdvancedSink`});return}let r=this.requireBucket();try{let i=new f({Bucket:r,Key:`${e}/${t}/${n}/${n}.json`}),a=await this.#e.send(i);if(!a.Body){this.#r?.warning({message:`Received empty body when trying to get action log from S3 for actionRunId ${n}`,category:`AdvancedSink`});return}let o=await a.Body.transformToString();return this.#r?.debug({message:`Successfully retrieved advanced log from S3 for actionRunId ${n}`,category:`AdvancedSink`}),JSON.parse(o)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#r?.debug({message:`Advanced log not found in S3 for actionRunId ${n}`,category:`AdvancedSink`});return}throw this.#r?.error({message:`Error when getting advanced log from S3 for actionRunId ${n}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async getStep(e,t,n,r){if(!this.#e){this.#r?.warning({message:`No s3 client available, cannot get step log from advanced sink`,category:`AdvancedSink`});return}let i=this.requireBucket();try{let a=new f({Bucket:i,Key:`${e}/${t}/${n}/steps/${r}.json`}),o=await this.#e.send(a);if(!o.Body){this.#r?.warning({message:`Received empty body when trying to get step log from S3 for actionRunId ${n} stepIndex ${r}`,category:`AdvancedSink`});return}let s=await o.Body.transformToString();return this.#r?.debug({message:`Successfully retrieved step log from S3 for actionRunId ${n} stepIndex ${r}`,category:`AdvancedSink`}),JSON.parse(s)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#r?.debug({message:`Step log not found in S3 for actionRunId ${n} stepIndex ${r}`,category:`AdvancedSink`});return}throw this.#r?.error({message:`Error when getting step log from S3 for actionRunId ${n} stepIndex ${r}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async getUnified(e,t,n){if(!this.#e){this.#r?.warning({message:`No s3 client available, cannot get unified log from advanced sink`,category:`AdvancedSink`});return}let r=this.requireBucket();try{let i=new f({Bucket:r,Key:`${e}/${t}/${n}/${n}.json`}),a=await this.#e.send(i);if(!a.Body){this.#r?.warning({message:`Received empty body when trying to get unified log from S3 for requestId ${n}`,category:`AdvancedSink`});return}let o=await a.Body.transformToString();return this.#r?.debug({message:`Successfully retrieved advanced log from S3 for requestId ${n}`,category:`AdvancedSink`}),JSON.parse(o)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#r?.debug({message:`Advanced log not found in S3 for requestId ${n}`,category:`AdvancedSink`});return}throw this.#r?.error({message:`Error when getting advanced log from S3 for requestId ${n}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async getProvider(e,t,n,r){if(!this.#e){this.#r?.warning({message:`No s3 client available, cannot get provider log from advanced sink`,category:`AdvancedSink`});return}let i=this.requireBucket();try{let a=new f({Bucket:i,Key:`${e}/${t}/${n}/provider/${r}.json`}),o=await this.#e.send(a);if(!o.Body){this.#r?.warning({message:`Received empty body when trying to get provider log from S3 for requestId ${n} id ${r}`,category:`AdvancedSink`});return}let s=await o.Body.transformToString();return this.#r?.debug({message:`Successfully retrieved provider log from S3 for requestId ${n} id ${r}`,category:`AdvancedSink`}),JSON.parse(s)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#r?.debug({message:`Provider log not found in S3 for requestId ${n} id ${r}`,category:`AdvancedSink`});return}throw this.#r?.error({message:`Error when getting provider log from S3 for requestId ${n} id ${r}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async send(e,t){if(!this.#e)throw Error(`No s3 client available, cannot send to advanced sink`);let n=this.requireBucket(),r=`ttl=30d`;typeof t==`number`&&(t===1?r=`ttl=1d`:t===7&&(r=`ttl=7d`));let i=Math.floor(Date.now()/1e3)+(t??30)*24*60*60,a=new Date(i*1e3);this.#r?.debug({message:`Storing advanced log in S3 bucket ${n} with ttl of ${r}`,category:`AdvancedSink`,context:{bucket:n,key:e.Key,ttlTag:r,expiresAt:a.toISOString()}});try{return await this.#e.send(new m({Bucket:n,Key:e.Key,Body:e.Body,ContentType:e.ContentType,Expires:a,Tagging:r})),{expiresAt:a}}catch(t){throw this.#r?.error({message:`Failed to write advanced logs to S3 at ${e.Key}`,error:t,code:`AdvancedLogWriteError`,category:`AdvancedSink`}),t}}async getObjectExpiry(e){if(!this.#e)return this.#r?.warning({message:`No s3 client available, cannot check object expiry`,category:`AdvancedSink`}),{exists:!1};let t=this.requireBucket();try{return{exists:!0,expiresAt:(await this.#e.send(new p({Bucket:t,Key:e}))).Expires}}catch(t){let n=t;if(n.name===`NotFound`||n.$metadata?.httpStatusCode===404)return this.#r?.debug({message:`Object not found in S3 for key ${e}`,category:`AdvancedSink`}),{exists:!1};throw this.#r?.error({message:`Error when checking object expiry in S3 for key ${e}`,error:t,code:`AdvancedLogHeadError`,category:`AdvancedSink`}),t}}async hasAction(e,t,n){let r=`${e}/${t}/${n}/${n}.json`;return this.getObjectExpiry(r)}async hasUnified(e,t,n){let r=`${e}/${t}/${n}/${n}.json`;return this.getObjectExpiry(r)}createActionS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.actionRunId}/${e.actionRunId}.json`,i=Math.floor(Date.now()/1e3)+(n??30)*24*60*60;return{Key:r,Body:this.serializeActionResult(e,t,i,this.#n),ContentType:`application/json`,Expires:new Date(i*1e3)}}createStepS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.actionRunId}/steps/${e.stepIndex}.json`,i=Math.floor(Date.now()/1e3)+(n??30)*24*60*60;return{Key:r,Body:this.serializeStepResult(e,t,i,this.#n),ContentType:`application/json`,Expires:new Date(i*1e3)}}createUnifiedS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.requestId}/${e.requestId}.json`,i=Math.floor(Date.now()/1e3)+(n??30)*24*60*60;return{Key:r,Body:this.serializeUnifiedResult(e,t,i,this.#n),ContentType:`application/json`,Expires:new Date(i*1e3)}}createProviderS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.requestId}/provider/${e.id}.json`,i=Math.floor(Date.now()/1e3)+(n??30)*24*60*60;return{Key:r,Body:this.serializeProviderResult(e,t,i,this.#n),ContentType:`application/json`,Expires:new Date(i*1e3)}}serializeActionResult(e,t,n,r){let i=u({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},c.PARTIAL),a=i.req?.headers,o=i.res?.headers,s=l(e.body,c.PARTIAL,!0),f=l(t.body,c.PARTIAL,!0),p=this.processContent(a,s,`upload`),m=this.processContent(o,f,`download`),h=e.isBackground??isBackgroundLog(e.mode,e.sourceType),g=e.url,_={};if(e.url)try{g=d(e.url,c.PARTIAL);let t=new URL(g);_=Object.fromEntries(t.searchParams)}catch{this.#r?.warning({message:`Invalid URL in action request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{actionRunId:e.actionRunId,actionId:e.actionId}})}let v={data:{request:{actionRunId:e.actionRunId,actionId:e.actionId,method:e.httpMethod,headers:this.filterHeaders(a),url:{url:g,path:e.pathParams,queryParams:_},body:p},response:{statusCode:t.statusCode??500,headers:this.filterHeaders(o),body:m},...h?{isBackgroundLog:!0}:{}},metadata:{...h?{isBackgroundLog:!0}:{},expirationTime:n}};return this.serializeAndLimit(v,r)}serializeStepResult(e,t,n,r){let i={data:{actionRunId:e.actionRunId,stepIndex:e.stepIndex,stepId:e.stepId,input:e.inputs,outputs:t.outputs,errors:t.errors},metadata:{expirationTime:n}};return this.serializeAndLimit(i,r)}serializeUnifiedResult(e,t,n,r){let i=u({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},c.PARTIAL),a=i.req?.headers,o=i.res?.headers,s=l(e.body,c.PARTIAL,!0),f=l(t.body,c.PARTIAL,!0),p=this.processContent(a,s,`upload`),m=this.processContent(o,f,`download`),h=e.isBackground??isBackgroundLog(e.mode,e.sourceType),g=`/`,_=e.url,v={};if(e.url)try{_=d(e.url,c.PARTIAL);let t=new URL(_);g=t.pathname,v=Object.fromEntries(t.searchParams)}catch{this.#r?.warning({message:`Invalid URL in unified request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{requestId:e.requestId}})}let y={data:{request:{id:e.requestId,method:e.httpMethod,headers:this.filterHeaders(a),url:{url:_,path:g,queryParams:v},body:p},response:{statusCode:t.statusCode??500,headers:this.filterHeaders(o),body:m}},metadata:{...h?{isBackgroundLog:!0}:{},expirationTime:n}};return this.serializeAndLimit(y,r)}serializeProviderResult(e,t,n,r){let i=u({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},c.PARTIAL),a=i.req?.headers,o=i.res?.headers,s=l(e.body,c.PARTIAL,!0),f=l(t.body,c.PARTIAL,!0),p=this.processContent(a,s,`upload`),m=this.processContent(o,f,`download`),h,g=``,_=`/`,v={};if(e.url)try{h=d(e.url,c.PARTIAL);let t=new URL(h);g=t.hostname,_=t.pathname,v=Object.fromEntries(t.searchParams)}catch{this.#r?.warning({message:`Invalid URL in provider request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{requestId:e.requestId,id:e.id}})}let y={data:{request:{id:e.id,method:e.httpMethod,headers:this.filterHeaders(a),url:{url:h,hostname:g,path:_,queryParams:v},body:p},response:{statusCode:t.statusCode,headers:this.filterHeaders(o),body:m}},metadata:{expirationTime:n}};return this.serializeAndLimit(y,r)}serializeAndLimit(e,t){if(i(e,t)){let t={...e,data:{outputs:{error:`Error.TOO_LARGE`}}};return JSON.stringify(t)}return JSON.stringify(e)}filterHeaders(e){if(!e)return;let t={},n=U.map(e=>e.toLowerCase());for(let[r,i]of Object.entries(e))n.includes(r.toLowerCase())||(t[r]=i);return t}processContent(e,t,n){let r=this.getContentType(e);if(!r)return this.parseJsonSafely(t);let i=r.toLowerCase().split(`;`)[0].trim();return W.includes(i)||G.some(e=>i.startsWith(e))?{type:`binary`,action:n,contentType:r}:this.parseJsonSafely(t)}parseJsonSafely(e){if(!o(e)){if(!s(e))return e;try{return JSON.parse(e)}catch{return e}}}getContentType(e){if(!e)return;let t=[`content-type`,`contenttype`];return Object.entries(e).find(([e])=>t.includes(e.toLowerCase()))?.[1]?.toString()}};function defaultProviderFactory(e){let t=new g({url:`${e.baseUrl??`https://logfire-eu.pydantic.dev`}/v1/traces`,headers:{Authorization:`Bearer ${e.token}`}}),n={[ee]:e.serviceName??`stackone-olap`};return e.environment&&(n[`deployment.environment.name`]=e.environment),e.region&&(n[`cloud.region`]=e.region),new v({resource:_(n),spanProcessors:[new y(t)]})}var LogfireEmitter=class{#e;#t;#n;#r;constructor(e,t,n=defaultProviderFactory){this.#e=e,this.#t=t,this.#n=n}configure(){if(this.#e.token)try{this.#r=this.#n(this.#e)}catch(e){this.#t?.warning({message:`Failed to configure Logfire`,error:e,code:`LogfireConfigureError`,category:`DatasetsSink`})}}emit(e,t){if(this.#r)try{let n=this.#r.getTracer(`stackone-olap`).startSpan(e);for(let[e,r]of Object.entries(t))r!=null&&(typeof r==`string`||typeof r==`number`||typeof r==`boolean`||Array.isArray(r)&&r.every(e=>typeof e==`string`)?n.setAttribute(e,r):n.setAttribute(e,JSON.stringify(r)));n.end()}catch(e){this.#t?.warning({message:`Failed to emit dataset log to Logfire`,error:e,code:`LogfireEmitError`,category:`DatasetsSink`})}}async flush(){if(this.#r)try{await this.#r.forceFlush()}catch(e){this.#t?.warning({message:`Failed to flush dataset logs to Logfire`,error:e,code:`LogfireFlushError`,category:`DatasetsSink`})}}},DatasetsSink=class{#e;#t;#n;#r;#i;constructor(e,t,n){this.#e=e?.logfire??{},this.#t=e?.logfire!==void 0,this.#n=e?.maxItemSizeBytes??1048576,this.#r=n??new LogfireEmitter(this.#e,t),this.#i=t}async initialize(){if(!this.#e.token){this.#t&&this.#i?.warning({message:`Logfire configured without a token, datasets sink will not emit`,category:`DatasetsSink`});return}this.#r.configure()}async sendAction(e,t,n){await this.sendActions([{input:e,result:t}],n)}async sendActions(e,t){if(!t?.enabled){this.#i?.debug({message:`Datasets sink is disabled, skipping sending actions to datasets sink`,category:`DatasetsSink`});return}let n=0;for(let{input:r,result:a}of e){if(this.#i?.debug({message:`Datasets sink called to send action`,category:`DatasetsSink`,context:{mode:r.mode,actionId:r.actionId,actionRunId:r.actionRunId,success:a.success,statusCode:a.statusCode,includeBackground:t.includeBackground}}),o(r.body)&&o(a.body)){this.#i?.debug({message:`No body in action result, skipping sending action to datasets sink`,category:`DatasetsSink`,context:{actionRunId:r.actionRunId}});continue}if(isBackgroundLog(r.mode,r.sourceType)&&!t.includeBackground){this.#i?.debug({message:`Datasets sink is configured to exclude background logs, skipping action with mode ${r.mode}`,category:`DatasetsSink`});continue}let e=this.createSchemaLog(r,a);if(o(e)){this.#i?.debug({message:`No schema extracted from action, skipping`,category:`DatasetsSink`,context:{actionRunId:r.actionRunId}});continue}if(i(e,this.#n)){this.#i?.debug({message:`Dataset schema log exceeds ${this.#n} bytes, skipping`,category:`DatasetsSink`,context:{actionRunId:r.actionRunId}});continue}this.send(r,e),n++}n>0&&(await this.#r.flush(),this.#i?.debug({message:`Sent ${n} schema log(s) to logfire`,category:`DatasetsSink`}))}send(e,t){this.#i?.debug({message:`Emitting schema log to Logfire`,category:`DatasetsSink`,context:{actionRunId:e.actionRunId,actionId:e.actionId}}),this.#r.emit(`dataset.schema`,t)}createSchemaLog(e,t){let n=o(e.body)?void 0:a(e.body),r=o(t.body)?void 0:a(t.body);if(!(o(n)&&o(r)))return{organizationId:e.organizationId,projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,connectorKey:e.connectorKey,connectorVersion:e.connectorVersion,actionId:e.actionId,schemas:{input:n,result:r}}}},DefenderSink=class{#e;#t;#n;#r;constructor(e,t,n){this.#e=e,this.#t=t?.bucket,this.#n=t?.ttlDays??365,this.#r=n}requireBucket(){if(!this.#t)throw Error(`Defender sink bucket is not configured`);return this.#t}async initialize(){if(!this.#e){this.#r?.warning({message:`No s3 client provided, defender sink will not function`,category:`DefenderSink`});return}}async sendAction(e,t,n){return(await this.sendActions([{input:e,result:t}],n))[0]??null}async sendActions(e,t){let n=[];for(let{input:r,result:i}of e){if(this.#r?.debug({message:`Defender sink called to send action`,category:`DefenderSink`,context:{mode:r.mode,actionId:r.actionId,actionRunId:r.actionRunId,success:i.success,statusCode:i.statusCode,options:{enabled:t?.enabled}}}),!t?.enabled){this.#r?.debug({message:`Defender sink is disabled, skipping sending action to defender sink`,category:`DefenderSink`}),n.push(null);continue}if(o(i.defenderContext)){this.#r?.debug({message:`No defender context in action result, skipping sending action to defender sink`,category:`DefenderSink`,context:{actionRunId:r.actionRunId}}),n.push(null);continue}let e=this.createDefenderS3(r,i),a=await this.send(e);n.push(a)}return n}async getAction(e,t,n){if(!this.#e){this.#r?.warning({message:`No s3 client available, cannot get action log from defender sink`,category:`DefenderSink`});return}let r=this.requireBucket();try{let i=new f({Bucket:r,Key:this.generateS3Key(e,t,n)}),a=await this.#e.send(i);if(!a.Body){this.#r?.warning({message:`Received empty body when trying to get action log from S3 for actionRunId ${n}`,category:`DefenderSink`});return}let o=await a.Body.transformToString();return this.#r?.debug({message:`Successfully retrieved defender log from S3 for actionRunId ${n}`,category:`DefenderSink`}),JSON.parse(o)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#r?.debug({message:`Defender log not found in S3 for actionRunId ${n}`,category:`DefenderSink`});return}throw this.#r?.error({message:`Error when getting defender log from S3 for actionRunId ${n}`,error:e,code:`DefenderLogReadError`,category:`DefenderSink`}),e}}async send(e){if(!this.#e)throw Error(`No s3 client available, cannot send to defender sink`);let t=this.requireBucket(),n=Math.floor(Date.now()/1e3)+this.#n*24*60*60,r=new Date(n*1e3),i=`ttl=${this.#n}d`;this.#r?.debug({message:`Storing defender log in S3 bucket ${t} with ${this.#n}-day TTL`,category:`DefenderSink`,context:{bucket:t,key:e.Key,ttlTag:i,expiresAt:r.toISOString()}});try{return await this.#e.send(new m({Bucket:t,Key:e.Key,Body:e.Body,ContentType:e.ContentType,Expires:r,Tagging:i})),{expiresAt:r}}catch(t){throw this.#r?.error({message:`Failed to write defender logs to S3 at ${e.Key}`,error:t,code:`DefenderLogWriteError`,category:`DefenderSink`}),t}}generateS3Key(e,t,n){return`${e}/${t}/${n}/defender.json`}createDefenderS3(e,t){let n=e.organizationId,r=e.projectSecureId;return{Key:this.generateS3Key(n,r,e.actionRunId),Body:JSON.stringify(t.defenderContext),ContentType:`application/json`}}};const hasTimezone=e=>/Z$|[+-]\d{2}:\d{2}$|[+-]\d{4}$/.test(e),utcDateTransform=e=>{if(hasTimezone(e))return e;let t=e.replace(` `,`T`);return new Date(t+`Z`).toISOString()},K=x.preprocess(e=>{if(e instanceof Date)return e;if(typeof e==`string`&&e.length>0)try{return new Date(utcDateTransform(e))}catch(e){throw new x.ZodError([{code:x.ZodIssueCode.custom,path:[],message:e instanceof Error?e.message:`Invalid date string`}])}return e},x.coerce.date()),q=x.object({logType:x.enum([`action`,`step`,`unified`,`provider`]),eventTime:K,startTime:K,endTime:K.optional().nullable().transform(e=>e??void 0),durationMs:x.coerce.number().optional().nullable().transform(e=>e??void 0),organizationId:x.coerce.string(),projectSecureId:x.coerce.string().optional().nullable().transform(e=>e??void 0),accountSecureId:x.coerce.string().optional().nullable().transform(e=>e??void 0)}),J=q.extend({logType:x.literal(`action`),actionRunId:x.coerce.string(),actionId:x.coerce.string(),connectorKey:x.coerce.string(),connectorVersion:x.coerce.string(),connectorOwner:x.coerce.string().optional().nullable().transform(e=>e??void 0),connectorProfileId:x.coerce.string().optional().nullable().transform(e=>e??void 0),projectSecureId:x.coerce.string(),accountSecureId:x.coerce.string(),actionType:x.coerce.string().optional().nullable().transform(e=>e??void 0),mode:x.coerce.string().optional().nullable().transform(e=>e??void 0),category:x.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerId:x.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:x.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:x.coerce.string().optional().nullable().transform(e=>e??void 0),url:x.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:x.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:x.coerce.string().optional().nullable().transform(e=>e??void 0),sourceValue:x.coerce.string().optional().nullable().transform(e=>e??void 0),authType:x.coerce.string().optional().nullable().transform(e=>e??void 0),authId:x.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:x.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:x.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:x.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:x.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:x.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:x.coerce.string().optional().nullable().transform(e=>e??void 0),success:x.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:x.coerce.number().optional().nullable().transform(e=>e??void 0),riskLevel:x.coerce.string().optional().nullable().transform(e=>e??void 0),tier2Score:x.coerce.number().optional().nullable().transform(e=>e??void 0),isBackground:x.coerce.boolean().optional().nullable().transform(e=>e??void 0),advancedExpiresAt:K.optional().nullable().transform(e=>e??void 0),defenderExpiresAt:K.optional().nullable().transform(e=>e??void 0)}),Y=q.extend({logType:x.literal(`step`),actionRunId:x.coerce.string(),stepIndex:x.coerce.number(),stepId:x.coerce.string(),projectSecureId:x.coerce.string(),accountSecureId:x.coerce.string(),skipped:x.coerce.boolean().optional().nullable().transform(e=>e??void 0),success:x.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:x.coerce.number().optional().nullable().transform(e=>e??void 0),message:x.coerce.string().optional().nullable().transform(e=>e??void 0),stepFunctionName:x.coerce.string().optional().nullable().transform(e=>e??void 0),stepFunctionVersion:x.coerce.string().optional().nullable().transform(e=>e??void 0),stepIterations:x.coerce.number().optional().nullable().transform(e=>e??void 0)}),X=q.extend({logType:x.literal(`unified`),requestId:x.coerce.string(),connectorKey:x.coerce.string(),connectorVersion:x.coerce.string().optional().nullable().transform(e=>e??void 0),connectorOwner:x.coerce.string().optional().nullable().transform(e=>e??void 0),projectSecureId:x.coerce.string(),accountSecureId:x.coerce.string(),mode:x.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:x.coerce.string().optional().nullable().transform(e=>e??void 0),url:x.coerce.string().optional().nullable().transform(e=>e??void 0),path:x.coerce.string().optional().nullable().transform(e=>e??void 0),resource:x.coerce.string().optional().nullable().transform(e=>e??void 0),subResource:x.coerce.string().optional().nullable().transform(e=>e??void 0),childResource:x.coerce.string().optional().nullable().transform(e=>e??void 0),service:x.coerce.string().optional().nullable().transform(e=>e??void 0),action:x.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:x.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:x.coerce.string().optional().nullable().transform(e=>e??void 0),sourceValue:x.coerce.string().optional().nullable().transform(e=>e??void 0),authType:x.coerce.string().optional().nullable().transform(e=>e??void 0),authId:x.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:x.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:x.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:x.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:x.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:x.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:x.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerId:x.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:x.coerce.string().optional().nullable().transform(e=>e??void 0),statusCode:x.coerce.number().optional().nullable().transform(e=>e??void 0),success:x.coerce.boolean().optional().nullable().transform(e=>e??void 0),isWorker:x.coerce.boolean().optional().nullable().transform(e=>e??void 0),isBackground:x.coerce.boolean().optional().nullable().transform(e=>e??void 0),status:x.coerce.number().optional().nullable().transform(e=>e??void 0),provider:x.coerce.string().optional().nullable().transform(e=>e??void 0),eventDatetime:K.optional().nullable().transform(e=>e??void 0),duration:x.coerce.number().optional().nullable().transform(e=>e??void 0),advancedExpiresAt:K.optional().nullable().transform(e=>e??void 0)}),Z=q.extend({logType:x.literal(`provider`),requestId:x.coerce.string(),id:x.coerce.string().optional().nullable().transform(e=>e??void 0),action:x.coerce.string(),mode:x.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:x.coerce.string(),originOwnerId:x.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:x.coerce.string().optional().nullable().transform(e=>e??void 0),url:x.coerce.string(),path:x.coerce.string().optional().nullable().transform(e=>e??void 0),connectorKey:x.coerce.string(),connectorVersion:x.coerce.string().optional().nullable().transform(e=>e??void 0),resource:x.coerce.string().optional().nullable().transform(e=>e??void 0),subResource:x.coerce.string().optional().nullable().transform(e=>e??void 0),childResource:x.coerce.string().optional().nullable().transform(e=>e??void 0),service:x.coerce.string().optional().nullable().transform(e=>e??void 0),success:x.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:x.coerce.number().optional().nullable().transform(e=>e??void 0),isWorker:x.coerce.boolean().optional().nullable().transform(e=>e??void 0),projectSecureId:x.coerce.string(),accountSecureId:x.coerce.string(),status:x.coerce.number().optional().nullable().transform(e=>e??void 0),provider:x.coerce.string().optional().nullable().transform(e=>e??void 0),eventDatetime:K.optional().nullable().transform(e=>e??void 0),duration:x.coerce.number().optional().nullable().transform(e=>e??void 0)}),se=x.discriminatedUnion(`logType`,[J,Y,X,Z]);var LogsSink=class{#e;#t;#n;#r;#i(e){if(e===`clickhouse`&&this.#n?.isReady())return this.#n;if(this.#t?.isReady())return this.#t;if(this.#n?.isReady())return this.#n}constructor(e,t,n,r,i){this.#e=e,this.#r=r,n&&(this.#t=new TinybirdClient(t,n,r)),i&&(this.#n=new ClickHouseClient(i,r));let a=[];this.#t&&a.push(`tinybird`),this.#n&&a.push(`clickhouse`),a.length>0&&this.#r?.debug({message:`LogsSink initialized with query clients: ${a.join(`, `)}`,category:`LogsSink`})}async initialize(){if(!this.#e){this.#r?.warning({message:`No kafka producer provided, logs sink cannot be initialized`,category:`LogsSink`});return}let e=this.#t?.isReady()??!1,t=this.#n?.isReady()??!1;!e&&!t?this.#r?.warning({message:`No query client is ready (missing config), logs sink will not be able to query`,category:`LogsSink`}):this.#r?.info({message:`Logs sink query clients ready: tinybird=${e}, clickhouse=${t}`,category:`LogsSink`}),this.#r?.info({message:`Logs sink kafka producer initialized`,category:`LogsSink`})}async sendAction(e,t,n,r){await this.sendActions([{input:e,result:t,metadata:n}],r)}async sendActions(e,t){if(!t?.enabled){this.#r?.debug({message:`Logs sink is disabled, skipping sending ${e.length} actions to log sink`,category:`LogsSink`});return}if(e.length===0)return;let n=e.map(({input:e,result:t,metadata:n})=>this.buildActionLog(e,t,n));await this.send(`actions`,n)}async sendStep(e,t,n){await this.sendSteps([{input:e,result:t}],n)}async sendSteps(e,t){if(!t?.enabled){this.#r?.debug({message:`Logs sink is disabled, skipping sending ${e.length} steps to log sink`,category:`LogsSink`});return}if(e.length===0)return;let n=e.map(({input:e,result:t})=>this.buildStepLog(e,t));await this.send(`steps`,n)}async sendUnified(e,t,n,r){if(!r?.enabled){this.#r?.debug({message:`Logs sink is disabled, skipping sending unified to log sink`,category:`LogsSink`});return}this.#r?.debug({message:`Sending unified to log sink (topic: unified_requests)`,category:`LogsSink`});let i=this.buildUnifiedLog(e,t,n);await this.send(`unified_requests`,[i])}async sendProvider(e,t,n){if(!n?.enabled){this.#r?.debug({message:`Logs sink is disabled, skipping sending provider to log sink`,category:`LogsSink`});return}this.#r?.debug({message:`Sending provider to log sink (topic: provider_requests)`,category:`LogsSink`});let r=this.buildProviderLog(e,t);await this.send(`provider_requests`,[r])}async getLogs(e,t){let n=this.#i(t);try{this.#r?.info({message:`Querying logs`,category:`LogsSink`,context:{query:e,engine:t}});let r=await n?.queryWithPagination({endpoint:`project_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return r?(this.#r?.info({message:`Successfully retrieved ${r.data.length} logs (${r.total} total)`,category:`LogsSink`}),{logs:this.validateLogs(r.data),total:r.total,pageNumber:r.pageNumber,pageSize:r.pageSize}):(this.#r?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{logs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return n?.isReady()?this.#r?.warning({message:`Failed to query for logs, returning empty results`,category:`LogsSink`,error:t}):this.#r?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:t}),{logs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getActions(e,t){let n=this.#i(t);try{this.#r?.info({message:`Querying action logs`,category:`LogsSink`,context:{query:e,engine:t}});let r=await n?.queryWithPagination({endpoint:`project_action_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return r?(this.#r?.info({message:`Successfully retrieved ${r.data.length} action logs (${r.total} total)`,category:`LogsSink`}),{actionLogs:this.validateLogsWithSchema(r.data,J),total:r.total,pageNumber:r.pageNumber,pageSize:r.pageSize}):(this.#r?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{actionLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return n?.isReady()?this.#r?.warning({message:`Failed to query for action logs, returning empty results`,category:`LogsSink`,error:t}):this.#r?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:t}),{actionLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getAction(e,t,n,r){return(await this.getActions({organizationId:e,projectSecureId:t,actionRunId:n},r)).actionLogs[0]}async getSteps(e,t){let n=this.#i(t);try{this.#r?.info({message:`Querying step logs`,category:`LogsSink`,context:{query:e,engine:t}});let r=await n?.queryWithPagination({endpoint:`project_step_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return r?(this.#r?.info({message:`Successfully retrieved ${r.data.length} step logs (${r.total} total)`,category:`LogsSink`}),{stepLogs:this.validateLogsWithSchema(r.data,Y),total:r.total,pageNumber:r.pageNumber,pageSize:r.pageSize}):(this.#r?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{stepLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return this.#r?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:t}),{stepLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getStep(e,t,n,r,i){return(await this.getSteps({organizationId:e,projectSecureId:t,actionRunId:n,stepIndex:r},i)).stepLogs[0]}async getUnifiedLogs(e,t){let n=this.#i(t);try{this.#r?.info({message:`Querying unified logs`,category:`LogsSink`,context:{query:e,engine:t}});let r=await n?.queryWithPagination({endpoint:`project_unified_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return r?(this.#r?.info({message:`Successfully retrieved ${r.data.length} unified logs (${r.total} total)`,category:`LogsSink`}),{unifiedLogs:this.validateLogsWithSchema(r.data,X),total:r.total,pageNumber:r.pageNumber,pageSize:r.pageSize}):(this.#r?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{unifiedLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return n?.isReady()?this.#r?.warning({message:`Failed to query for unified logs, returning empty results`,category:`LogsSink`,error:t}):this.#r?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:t}),{unifiedLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getUnifiedLog(e,t,n,r){return(await this.getUnifiedLogs({organizationId:e,projectSecureId:t,requestId:n},r)).unifiedLogs[0]}async getProviderLogs(e,t){let n=this.#i(t);try{this.#r?.info({message:`Querying provider logs`,category:`LogsSink`,context:{query:e,engine:t}});let r=await n?.queryWithPagination({endpoint:`project_provider_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return r?(this.#r?.info({message:`Successfully retrieved ${r.data.length} provider logs (${r.total} total)`,category:`LogsSink`}),{providerLogs:this.validateLogsWithSchema(r.data,Z),total:r.total,pageNumber:r.pageNumber,pageSize:r.pageSize}):(this.#r?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{providerLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return n?.isReady()?this.#r?.warning({message:`Failed to query for provider logs, returning empty results`,category:`LogsSink`,error:t}):this.#r?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:t}),{providerLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getProviderLog(e,t,n,r,i){return(await this.getProviderLogs({organizationId:e,projectSecureId:t,requestId:n,id:r},i)).providerLogs[0]}async getAggregate(e,t,n,i){let a=this.#i(i);try{this.#r?.info({message:`Querying logs stats aggregate`,category:`LogsSink`,context:{query:n,engine:i}});let{dimensions:o,startTime:s,endTime:c,...l}=n,u={organizationId:e,projectSecureId:t,...l,...o&&o.length>0&&{dimensions:o.join(`,`)},...s&&{startTime:s.toISOString()},...c&&{endTime:c.toISOString()}},d=await a?.query({endpoint:`project_logs_aggregation.json`,params:u});if(!d)return this.#r?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{data:[]};this.#r?.info({message:`Successfully retrieved ${d.length} aggregated data points`,category:`LogsSink`});let f=d.map(e=>r(e,!0)),p=[`success`,`isWorker`,`isBackground`,`skipped`];return{data:f.map(e=>{let t={...e};for(let e of p)e in t&&typeof t[e]==`number`&&(t[e]=t[e]===1);return t})}}catch(e){return a?.isReady()?this.#r?.warning({message:`Failed to query for logs stats aggregate, returning empty results`,category:`LogsSink`,error:e}):this.#r?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:e}),{data:[]}}}async getDimensions(e,t,n,r){let i=this.#i(r);try{this.#r?.info({message:`Querying logs stats dimensions`,category:`LogsSink`,context:{query:n,engine:r}});let{dimensions:a,startTime:o,endTime:s,maxValues:c,...l}=n,u={organizationId:e,projectSecureId:t,...l,dimensions:a.join(`,`),...o&&{startTime:o.toISOString()},...s&&{endTime:s.toISOString()},...c&&{maxValuesPerDim:c}},d=await i?.query({endpoint:`project_logs_dimensions.json`,params:u});if(!d)return this.#r?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{};this.#r?.info({message:`Successfully retrieved ${d.length} dimension facets`,category:`LogsSink`});let f=[`success`,`isWorker`,`isBackground`,`skipped`],p={};for(let e of d)f.includes(e.dimension)?p[e.dimension]=e.values.map(e=>({value:e.value===`1`?`true`:e.value===`0`?`false`:e.value,count:e.count})):p[e.dimension]=e.values;return p}catch(e){return i?.isReady()?this.#r?.warning({message:`Failed to query for logs stats dimensions, returning empty results`,category:`LogsSink`,error:e}):this.#r?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:e}),{}}}async getSourceUsage(e,t,n,r){let i=this.#i(r);try{this.#r?.info({message:`Querying logs stats source usage`,category:`LogsSink`,context:{query:n,engine:r}});let{startTime:a,endTime:o,sourceType:s}=n,c={organizationId:e,projectSecureId:t,...s&&{sourceType:Array.isArray(s)?s.join(`,`):s},...a&&{startTime:a.toISOString()},...o&&{endTime:o.toISOString()}},l=await i?.query({endpoint:`project_source_usage.json`,params:c});return l?(this.#r?.info({message:`Successfully retrieved ${l.length} source usage records`,category:`LogsSink`}),l.map(e=>({sourceId:e.sourceId,sourceType:e.sourceType,requestCount:e.request_count,lastRequest:e.last_request}))):(this.#r?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),[])}catch(e){return i?.isReady()?this.#r?.warning({message:`Failed to query for logs stats source usage, returning empty results`,category:`LogsSink`,error:e}):this.#r?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:e}),[]}}async send(e,t){if(!this.#e)throw this.#r?.error({message:`Kafka not initialized, dropping message for topic ${e}`,category:`KafkaSink`,code:`KafkaNotReady`}),Error(`Kafka producer is not initialized`);let n=this.validateLogsBeforeSend(t);if(n.length===0){this.#r?.warning({message:`All ${t.length} log(s) failed validation, nothing to send to topic ${e}`,category:`LogsSink`,code:`AllLogsInvalid`});return}n.length<t.length&&this.#r?.warning({message:`${t.length-n.length} of ${t.length} log(s) failed validation and were dropped`,category:`LogsSink`,code:`SomeLogsInvalid`});let r=Date.now(),i=n.map(t=>({topic:e,value:safeSerialize(t)}));this.#r?.debug({message:`Sending ${i.length} message(s) to topic ${e}`,category:`KafkaSink`});try{let t=await this.#e.send({messages:i,compression:`gzip`});this.#r?.debug({message:`Successfully sent ${i.length} message(s) to topic ${e}`,category:`KafkaSink`,context:{durationMs:Date.now()-r,topic:e,result:t}})}catch(t){throw this.#r?.error({message:`Error sending ${i.length} message(s) to topic ${e}: ${t.message}`,category:`KafkaSink`,error:t,code:`KafkaSendError`,context:{durationMs:Date.now()-r,topic:e,messageCount:i.length}}),t}}buildActionLog(e,t,n){let r=new Date,i=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`action`,organizationId:String(e.organizationId),projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,actionRunId:e.actionRunId,actionId:e.actionId,connectorKey:e.connectorKey,connectorVersion:e.connectorVersion,...e.connectorOwner&&{connectorOwner:e.connectorOwner},...e.connectorProfileId&&{connectorProfileId:e.connectorProfileId},...e.sourceType&&{sourceType:e.sourceType},...e.authType&&{authType:e.authType},...e.authId&&{authId:e.authId},...e.userAgent&&{userAgent:e.userAgent},...e.ipAddress&&{ipAddress:e.ipAddress},...e.sessionId&&{sessionId:e.sessionId},...e.agentId&&{agentId:e.agentId},...e.transportType&&{transportType:e.transportType},...e.streamType!==void 0&&{streamType:e.streamType},...i!==void 0&&{durationMs:i},...e.mode&&{mode:e.mode},...e.actionType&&{actionType:e.actionType},...e.category&&{category:e.category},...e.originOwnerId&&{originOwnerId:e.originOwnerId},...e.originOwnerName&&{originOwnerName:e.originOwnerName},...e.httpMethod&&{httpMethod:e.httpMethod},...e.url&&{url:e.url},...t.success!==void 0&&{success:t.success},...t.statusCode!==void 0&&{statusCode:t.statusCode},...t.defenderContext?.result?.riskLevel&&{riskLevel:t.defenderContext.result.riskLevel},...t.defenderContext?.result?.tier2Score!==void 0&&{tier2Score:t.defenderContext.result.tier2Score},startTime:e.startTime??r,...t.endTime&&{endTime:t.endTime},eventTime:r,isBackground:e.isBackground,...n?.advancedExpiresAt&&{advancedExpiresAt:n.advancedExpiresAt},...n?.defenderExpiresAt&&{defenderExpiresAt:n.defenderExpiresAt}}}buildStepLog(e,t){let n=new Date,r=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`step`,eventTime:n,startTime:e.startTime??n,organizationId:String(e.organizationId),projectSecureId:String(e.projectSecureId),accountSecureId:String(e.accountSecureId),actionRunId:e.actionRunId,stepIndex:e.stepIndex,stepId:e.stepId,...t.endTime&&{endTime:t.endTime},...r!==void 0&&{durationMs:r},...t.skipped!==void 0&&{skipped:t.skipped},...t.success!==void 0&&{success:t.success},...t.statusCode!==void 0&&{statusCode:t.statusCode},...t.message&&{message:t.message},...e.stepFunctionName&&{stepFunctionName:e.stepFunctionName},...e.stepFunctionVersion&&{stepFunctionVersion:e.stepFunctionVersion},...e.stepIterations!==void 0&&{stepIterations:e.stepIterations}}}buildUnifiedLog(e,t,n){let r=new Date,i=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`unified`,requestId:e.requestId,connectorKey:e.connectorKey,connectorVersion:e.connectorVersion??`2`,...e.connectorOwner&&{connectorOwner:e.connectorOwner},organizationId:e.organizationId,projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,...e.originOwnerId&&{originOwnerId:e.originOwnerId},...e.originOwnerName&&{originOwnerName:e.originOwnerName},...e.sourceType&&{sourceType:e.sourceType},...e.authType&&{authType:e.authType},...e.authId&&{authId:e.authId},...e.userAgent&&{userAgent:e.userAgent},...e.ipAddress&&{ipAddress:e.ipAddress},...e.transportType&&{transportType:e.transportType},...e.mode&&{mode:e.mode},...e.httpMethod&&{httpMethod:e.httpMethod},...e.url&&{url:e.url},...e.path&&{path:e.path},...e.resource&&{resource:e.resource},...e.subResource&&{subResource:e.subResource},...e.childResource&&{childResource:e.childResource},...e.service&&{service:e.service},...e.action&&{action:e.action},...t.statusCode!==void 0&&{statusCode:t.statusCode},...t.success!==void 0&&{success:t.success},isBackground:e.isBackground,durationMs:i,startTime:e.startTime??r,...t.endTime&&{endTime:t.endTime},eventTime:r,...t.statusCode!==void 0&&{status:t.statusCode},provider:e.connectorKey,eventDatetime:r,duration:i,...n?.advancedExpiresAt&&{advancedExpiresAt:n.advancedExpiresAt}}}buildProviderLog(e,t){let n=new Date,r=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`provider`,requestId:e.requestId,id:e.id,organizationId:e.organizationId,projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,...e.originOwnerId&&{originOwnerId:e.originOwnerId},...e.originOwnerName&&{originOwnerName:e.originOwnerName},action:e.action,...e.mode&&{mode:e.mode},httpMethod:e.httpMethod,url:e.url,...e.path&&{path:e.path},connectorKey:e.connectorKey,connectorVersion:`2`,...e.resource&&{resource:e.resource},...e.subResource&&{subResource:e.subResource},...e.childResource&&{childResource:e.childResource},...e.service&&{service:e.service},...t.success!==void 0&&{success:t.success},...t.statusCode!==void 0&&{statusCode:t.statusCode},durationMs:r,startTime:e.startTime??n,...t.endTime&&{endTime:t.endTime},eventTime:n,...t.statusCode!==void 0&&{status:t.statusCode},provider:e.connectorKey,eventDatetime:n,duration:r}}calculateDurationMs(e,t){if(!(e instanceof Date)||!(t instanceof Date))return;let n=e.getTime(),r=t.getTime();if(!(Number.isNaN(n)||Number.isNaN(r)||r<n))return r-n}validateLogsWithSchema(e,t){return e.map(e=>{try{return t.parse(e)}catch(t){if(t instanceof b){let n=`unknown`;if(typeof e==`object`&&e&&`logType`in e){let t=e;n=typeof t.logType==`string`?t.logType:`unknown`}throw this.#r?.error({message:`Failed to validate ${n} log from Tinybird`,category:`LogsSink`,code:`LogParsingTypeError`,context:{validationErrors:t.errors,log:safeSerialize(e)}}),Error(`Tinybird data validation failed for ${n} log: ${t.message}`)}throw t}})}validateLogs(e){return this.validateLogsWithSchema(e,se)}validateLogsBeforeSend(e){let t=[];for(let n of e)try{let e=this.getSchemaForLogType(n.logType).parse(n);t.push(e)}catch(e){e instanceof b?this.#r?.warning({message:`Log validation failed before sending to Tinybird, dropping ${n.logType} log`,category:`LogsSink`,code:`PreWriteValidationFailed`,context:{logType:n.logType,validationErrors:e.errors,log:safeSerialize(n)}}):this.#r?.warning({message:`Unexpected error validating ${n.logType} log before send, dropping log`,category:`LogsSink`,code:`PreWriteValidationError`,error:e})}return t}getSchemaForLogType(e){switch(e){case`action`:return J;case`step`:return Y;case`unified`:return X;case`provider`:return Z}}};const Q={logs:{enabled:!0},advanced:{enabled:!1,ttl:7,errorsOnly:!1,includeBackground:!1},defender:{enabled:!0},datasets:{enabled:!0,includeBackground:!1}};function resolveOlapOptions(e){return{logs:{...Q.logs,...e?.logs},advanced:{...Q.advanced,...e?.advanced},defender:{...Q.defender,...e?.defender},datasets:{...Q.datasets,...e?.datasets}}}const buildHttpClient=e=>{try{return new te({logger:e})}catch(t){let n=t;e?.error({message:`Error building http client: ${n.message}`,error:n,code:`BuildHttpClientError`,category:`buildHttpClient`});return}},buildKafkaClient=async(e,t)=>{if(e)try{let{Producer:t,stringSerializers:n}=await import(`@platformatic/kafka`);return new t({...e,serializers:n})??void 0}catch(e){let n=e;t?.error({message:`Error building kafka producer: ${n.message}`,error:n,code:`BuildKafkaProducerError`,category:`buildKafkaClient`});return}},buildS3Client=(e,t)=>{try{return new h(e)??void 0}catch(e){let n=e;t?.error({message:`Error building s3 client: ${n.message}`,error:n,code:`BuildS3ClientError`,category:`buildS3Client`});return}};var $=class OlapClient{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;constructor({getKafkaClient:e=buildKafkaClient,getHttpClient:t=buildHttpClient,getS3Client:n=buildS3Client,kafkaClientConfig:r,s3ClientConfig:i,tinybirdConfig:a,clickhouseConfig:o,sinkConfig:s,logger:c}={}){this.name=`OlapClient`,this.#c=e,this.#l=r,this.#u=a,this.#d=o,this.#f=s,this.#t=t(c),this.#n=n(i,c),this.#r=c}static async create({getKafkaClient:e=buildKafkaClient,getHttpClient:t=buildHttpClient,getS3Client:n=buildS3Client,kafkaClientConfig:r,s3ClientConfig:i,tinybirdConfig:a,clickhouseConfig:o,sinkConfig:s,logger:c}={}){let l=new OlapClient({getKafkaClient:e,getHttpClient:t,getS3Client:n,kafkaClientConfig:r,s3ClientConfig:i,tinybirdConfig:a,clickhouseConfig:o,sinkConfig:s,logger:c});return await l.initialize(),l}async initialize(){this.#e=await this.#c(this.#l,this.#r),this.#i=new LogsSink(this.#e,this.#t,this.#u,this.#r,this.#d),this.#a=new AdvancedSink(this.#n,this.#f?.advanced,this.#r),this.#o=new DefenderSink(this.#n,this.#f?.defender,this.#r),this.#s=new DatasetsSink(this.#f?.datasets,this.#r),await this.#i?.initialize(),await this.#a?.initialize(),await this.#s?.initialize(),await this.#o?.initialize()}async recordAction(e,t,n){await this.recordActions([{input:e,result:t}],n)}async recordActions(e,t){let{logs:n,advanced:r,defender:i,datasets:a}=resolveOlapOptions(t);this.#r?.debug({message:`Olap client called to record ${e.length} action(s)`,category:`OlapClient`,context:{options:t,resolvedOptions:{logs:n,advanced:r,defender:i,datasets:a}}});for(let t of e)o(t.input.isBackground)&&(t.input.isBackground=isBackgroundLog(t.input.mode,t.input.sourceType));let s=a?.enabled&&this.#s?this.#s.sendActions(e,a).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to datasets sink: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve(),[c,l]=await Promise.all([r?.enabled&&this.#a?this.#a.sendActions(e,r).catch(t=>(this.#r?.warning({message:`[OlapClient] Error sending to advanced logs s3: ${t.message}`,category:`OlapClient`,error:t}),e.map(()=>null))):Promise.resolve(e.map(()=>null)),i?.enabled&&this.#o?this.#o.sendActions(e,i).catch(t=>(this.#r?.warning({message:`[OlapClient] Error sending to defender logs s3: ${t.message}`,category:`OlapClient`,error:t}),e.map(()=>null))):Promise.resolve(e.map(()=>null))]),u=e.map((e,t)=>({...e,metadata:{advancedExpiresAt:c[t]?.expiresAt,defenderExpiresAt:l[t]?.expiresAt}})),d=n?.enabled&&this.#i?this.#i.sendActions(u,n).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve();await Promise.all([s,d])}async recordStep(e,t,n){await this.recordSteps([{input:e,result:t}],n)}async recordSteps(e,t){let{logs:n,advanced:r}=resolveOlapOptions(t),i=[];n?.enabled&&this.#i&&i.push(this.#i.sendSteps(e,n).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})),r?.enabled&&this.#a&&i.push(this.#a.sendSteps(e,r).then(()=>{}).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to s3: ${e.message}`,category:`OlapClient`,error:e})})),await Promise.all(i)}async recordUnified(e,t,n){let{logs:r,advanced:i}=resolveOlapOptions(n);this.#r?.debug({message:`Olap client called to record unified`,category:`OlapClient`,context:{mode:e.mode,requestId:e.requestId,success:t.success,options:n,resolvedOptions:{logs:r,advanced:i}}}),o(e.isBackground)&&(e.isBackground=isBackgroundLog(e.mode,e.sourceType));let a={advancedExpiresAt:(i?.enabled&&this.#a?await this.#a.sendUnified(e,t,i).catch(e=>(this.#r?.warning({message:`[OlapClient] Error sending to advanced logs s3: ${e.message}`,category:`OlapClient`,error:e}),null)):null)?.expiresAt};r?.enabled&&this.#i&&await this.#i.sendUnified(e,t,a,r).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})}async recordProvider(e,t,n){let{logs:r,advanced:i}=resolveOlapOptions(n),a=[];r?.enabled&&this.#i&&a.push(this.#i.sendProvider(e,t,r).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})),i?.enabled&&this.#a&&a.push(this.#a.sendProvider(e,t,i).then(()=>{}).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to s3: ${e.message}`,category:`OlapClient`,error:e})})),await Promise.all(a)}async getLogs(e,t,n,r){return this.#r?.debug({message:`Querying logs`,category:`OlapClient`,context:{query:n,engine:r}}),await this.#i?.getLogs({...n,organizationId:e,projectSecureId:t},r)||(this.#r?.warning({message:`Failed to query logs, returning empty result`,category:`OlapClient`}),{logs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getActionLogs(e,t,n,r){return this.#r?.debug({message:`Querying action logs`,category:`OlapClient`,context:{query:n,engine:r}}),await this.#i?.getActions({...n,organizationId:e,projectSecureId:t},r)||(this.#r?.warning({message:`Failed to query action logs, returning empty result`,category:`OlapClient`}),{actionLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getActionLog(e,t,n){let r=await this.#i?.getAction(e,t,n);if(o(r)){this.#r?.debug({message:`Failed to retrieve action log for actionRunId ${n}`,category:`OlapClient`});return}return r}async getLog(e,t,n){this.#r?.debug({message:`Querying log by logId`,category:`OlapClient`,context:{logId:n}});let r=await this.getLogs(e,t,{logId:n,pageSize:1});if(!r||r.logs.length===0){this.#r?.debug({message:`Failed to retrieve log for logId ${n}`,category:`OlapClient`});return}let i=r.logs[0];if(i.logType===`action`||i.logType===`unified`)return i}async getStepLogs(e,t,n){return this.#r?.debug({message:`Querying step logs`,category:`OlapClient`,context:{query:n}}),await this.#i?.getSteps({...n,organizationId:e,projectSecureId:t})||(this.#r?.warning({message:`Failed to query step logs, returning empty result`,category:`OlapClient`}),{stepLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getStepLog(e,t,n,r){let i=await this.#i?.getStep(e,t,n,r);if(o(i)){this.#r?.debug({message:`Failed to retrieve step log for actionRunId ${n} stepIndex ${r}`,category:`OlapClient`});return}return i}async getUnifiedLogs(e,t,n){return this.#r?.debug({message:`Querying unified logs`,category:`OlapClient`,context:{query:n}}),await this.#i?.getUnifiedLogs({...n,organizationId:e,projectSecureId:t})||(this.#r?.warning({message:`Failed to query unified logs, returning empty result`,category:`OlapClient`}),{unifiedLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getUnifiedLog(e,t,n){let r=await this.#i?.getUnifiedLog(e,t,n);if(o(r)){this.#r?.debug({message:`Failed to retrieve unified log for requestId ${n}`,category:`OlapClient`});return}return r}async getProviderLogs(e,t,n){return this.#r?.debug({message:`Querying provider logs`,category:`OlapClient`,context:{query:n}}),await this.#i?.getProviderLogs({...n,organizationId:e,projectSecureId:t})||(this.#r?.warning({message:`Failed to query provider logs, returning empty result`,category:`OlapClient`}),{providerLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getProviderLog(e,t,n,r){let i=await this.#i?.getProviderLog(e,t,n,r);if(o(i)){this.#r?.debug({message:`Failed to retrieve provider log for requestId ${n} id ${r}`,category:`OlapClient`});return}return i}async getActionAdvancedLog(e,t,n){let r=await this.#a?.getAction(e,t,n);if(o(r)){this.#r?.debug({message:`Failed to retrieve action advanced log for actionRunId ${n}`,category:`OlapClient`});return}return r}async getStepAdvancedLog(e,t,n,r){let i=await this.#a?.getStep(e,t,n,r);if(o(i)){this.#r?.debug({message:`Failed to retrieve step advanced log for actionRunId ${n} stepIndex ${r}`,category:`OlapClient`});return}return i}async getUnifiedAdvancedLog(e,t,n){let r=await this.#a?.getUnified(e,t,n);if(o(r)){this.#r?.debug({message:`Failed to retrieve unified advanced log for requestId ${n}`,category:`OlapClient`});return}return r}async getProviderAdvancedLog(e,t,n,r){let i=await this.#a?.getProvider(e,t,n,r);if(o(i)){this.#r?.debug({message:`Failed to retrieve provider advanced log for requestId ${n} id ${r}`,category:`OlapClient`});return}return i}async getDefenderLog(e,t,n){let r=await this.#o?.getAction(e,t,n);if(o(r)){this.#r?.debug({message:`Failed to retrieve defender log for actionRunId ${n}`,category:`OlapClient`});return}return r}async getLogsStatsAggregate(e,t,n){return this.#r?.debug({message:`Querying logs stats aggregate`,category:`OlapClient`,context:{query:n}}),await this.#i?.getAggregate(e,t,n)??{data:[]}}async getLogsStatsDimensions(e,t,n){return this.#r?.debug({message:`Querying logs stats dimensions`,category:`OlapClient`,context:{query:n}}),await this.#i?.getDimensions(e,t,n)??{}}async getSourceUsage(e,t,n){return this.#r?.debug({message:`Querying source usage`,category:`OlapClient`,context:{query:n}}),await this.#i?.getSourceUsage(e,t,n)??[]}};const buildOlapClientInstance=async({getKafkaClient:e=buildKafkaClient,getHttpClient:t=buildHttpClient,getS3Client:n=buildS3Client,kafkaClientConfig:r,s3ClientConfig:i,tinybirdConfig:a,clickhouseConfig:o,sinkConfig:s,logger:c}={})=>$.create({getKafkaClient:e,getHttpClient:t,getS3Client:n,kafkaClientConfig:r,s3ClientConfig:i,tinybirdConfig:a,clickhouseConfig:o,sinkConfig:s,logger:c});var OlapClientManager=class{static{this.olapClientPromise=null}static getInstance({getKafkaClient:e,getHttpClient:t,getS3Client:n,kafkaClientConfig:r,s3ClientConfig:i,tinybirdConfig:a,clickhouseConfig:o,sinkConfig:s,logger:c,getOlapClient:l=buildOlapClientInstance}={}){return this.olapClientPromise||=l({getKafkaClient:e,getHttpClient:t,getS3Client:n,kafkaClientConfig:r,s3ClientConfig:i,tinybirdConfig:a,clickhouseConfig:o,sinkConfig:s,logger:c}),this.olapClientPromise}static resetInstance(){this.olapClientPromise=null}};export{R as AuthType,ClickHouseClient,P as Dimension,N as IntervalType,A as LogType,$ as OlapClient,OlapClientManager,j as OrderBy,M as OrderDirection,F as SourceType,L as StreamType,I as TransportType,createConfigFromEnv,createOlapQueryClient};
|