Edits history of script submission #23118 for ' Query Workers Observability (cloudflare)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    export type DynSelect_worker_name = string
    
    // Dropdown of the account's Worker scripts.
    export async function worker_name(auth: RT.Cloudflare) {
      const response = await fetch(
        `https://api.cloudflare.com/client/v4/accounts/${auth.account_id}/workers/scripts`,
        {
          headers: {
            Authorization: `Bearer ${auth.token}`,
            Accept: "application/json",
          },
        }
      )
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
      const { result } = (await response.json()) as { result: { id: string }[] }
      return result.map((s) => ({ value: s.id, label: s.id }))
    }
    
    /**
     * Query Workers Observability
     * Query Workers Logs telemetry (events, invocations or aggregate calculations) for the account or one Worker over the last 7 days. Needs Workers Observability permission on the token.
     */
    export async function main(
      auth: RT.Cloudflare,
      view: "events" | "invocations" | "calculations",
      worker_name: DynSelect_worker_name | undefined,
      from: string | undefined,
      to: string | undefined,
      search: string | undefined,
      filters:
        | {
            key: string
            operation: string
            type: "string" | "number" | "boolean"
            value?: string | number | boolean
          }[]
        | undefined,
      calculations:
        | {
            operator: string
            key?: string
            keyType?: "string" | "number" | "boolean"
            alias?: string
          }[]
        | undefined,
      group_by: string[] | undefined,
      limit: number | undefined
    ) {
      const toMs = to ? Date.parse(to) : Date.now()
      const fromMs = from ? Date.parse(from) : toMs - 60 * 60 * 1000
    
      const allFilters: { [key: string]: any }[] = (filters ?? []).map((f) => ({
        kind: "filter",
        ...f,
      }))
      if (worker_name) {
        allFilters.unshift({
          kind: "filter",
          key: "$metadata.service",
          operation: "eq",
          type: "string",
          value: worker_name,
        })
      }
    
      const response = await fetch(
        `https://api.cloudflare.com/client/v4/accounts/${auth.account_id}/workers/observability/telemetry/query`,
        {
          method: "POST",
          headers: {
            Authorization: `Bearer ${auth.token}`,
            "Content-Type": "application/json",
            Accept: "application/json",
          },
          body: JSON.stringify({
            queryId: `windmill-${view}`,
            view,
            // dry keeps the query out of the account's saved-query history
            dry: true,
            timeframe: { from: fromMs, to: toMs },
            limit: limit ?? 50,
            parameters: {
              datasets: ["cloudflare-workers"],
              filterCombination: "and",
              filters: allFilters,
              needle: search ? { value: search } : undefined,
              calculations:
                calculations ??
                (view === "calculations" ? [{ operator: "count" }] : undefined),
              groupBys: group_by?.map((value) => ({ value, type: "string" })),
              limit: limit ?? 50,
            },
          }),
        }
      )
    
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
    
      return await response.json()
    }
    

    Submitted by hugo989 4 hours ago