athena.ts 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. import {
  2. AthenaClient as AwsAthenaClient,
  3. GetQueryExecutionCommand,
  4. GetQueryResultsCommand,
  5. StartQueryExecutionCommand,
  6. type Row,
  7. } from "@aws-sdk/client-athena"
  8. import { Effect, Layer, Schema } from "effect"
  9. import * as Context from "effect/Context"
  10. import { Resource } from "sst/resource"
  11. const ATHENA_MAX_POLL_ATTEMPTS = 60
  12. const ATHENA_PAGE_SIZE = 1000
  13. export type AthenaData = Record<string, string>
  14. export class AthenaQueryError extends Schema.TaggedErrorClass<AthenaQueryError>()("AthenaQueryError", {
  15. message: Schema.String,
  16. queryExecutionId: Schema.optional(Schema.String),
  17. cause: Schema.optional(Schema.Defect),
  18. }) {}
  19. export class AthenaQueryTimeoutError extends Schema.TaggedErrorClass<AthenaQueryTimeoutError>()(
  20. "AthenaQueryTimeoutError",
  21. {
  22. message: Schema.String,
  23. queryExecutionId: Schema.String,
  24. },
  25. ) {}
  26. export declare namespace Athena {
  27. export interface Service {
  28. readonly query: (query: string) => Effect.Effect<AthenaData[], AthenaQueryError | AthenaQueryTimeoutError>
  29. }
  30. }
  31. export class Athena extends Context.Service<Athena, Athena.Service>()("@opencode/stats/Athena") {
  32. static readonly layer: Layer.Layer<Athena> = Layer.effect(
  33. Athena,
  34. Effect.sync(() => {
  35. const client = new AwsAthenaClient({ region: Resource.InferenceEvent.region })
  36. const query = Effect.fn("Athena.query")(function* (query: string) {
  37. const started = yield* Effect.tryPromise({
  38. try: () =>
  39. client.send(
  40. new StartQueryExecutionCommand({
  41. QueryString: query,
  42. WorkGroup: Resource.InferenceEvent.workgroup,
  43. QueryExecutionContext: {
  44. Catalog: Resource.InferenceEvent.catalog,
  45. Database: Resource.InferenceEvent.database,
  46. },
  47. }),
  48. ),
  49. catch: (cause) => new AthenaQueryError({ message: "Failed to start Athena stats query", cause }),
  50. })
  51. const queryExecutionId = started.QueryExecutionId
  52. if (!queryExecutionId)
  53. return yield* new AthenaQueryError({ message: "Athena did not return a query execution id" })
  54. yield* poll(client, queryExecutionId)
  55. return yield* results(client, queryExecutionId)
  56. })
  57. return Athena.of({ query })
  58. }),
  59. )
  60. }
  61. const poll: (
  62. client: AwsAthenaClient,
  63. queryExecutionId: string,
  64. attempt?: number,
  65. ) => Effect.Effect<void, AthenaQueryError | AthenaQueryTimeoutError> = Effect.fn("Athena.poll")(function* (
  66. client: AwsAthenaClient,
  67. queryExecutionId: string,
  68. attempt = 0,
  69. ) {
  70. if (attempt > 0) yield* Effect.sleep("2 seconds")
  71. const result = yield* Effect.tryPromise({
  72. try: () => client.send(new GetQueryExecutionCommand({ QueryExecutionId: queryExecutionId })),
  73. catch: (cause) => new AthenaQueryError({ message: "Failed to poll Athena stats query", queryExecutionId, cause }),
  74. })
  75. const status = result.QueryExecution?.Status
  76. if (status?.State === "SUCCEEDED") return
  77. if (status?.State === "FAILED" || status?.State === "CANCELLED")
  78. return yield* new AthenaQueryError({
  79. message: `Athena stats query ${status.State.toLowerCase()}: ${status.StateChangeReason ?? "unknown reason"}`,
  80. queryExecutionId,
  81. })
  82. if (attempt >= ATHENA_MAX_POLL_ATTEMPTS - 1)
  83. return yield* new AthenaQueryTimeoutError({
  84. message: `Athena stats query ${queryExecutionId} did not complete`,
  85. queryExecutionId,
  86. })
  87. return yield* poll(client, queryExecutionId, attempt + 1)
  88. })
  89. const results: (
  90. client: AwsAthenaClient,
  91. queryExecutionId: string,
  92. nextToken?: string,
  93. ) => Effect.Effect<AthenaData[], AthenaQueryError> = Effect.fn("Athena.results")(function* (
  94. client: AwsAthenaClient,
  95. queryExecutionId: string,
  96. nextToken?: string,
  97. ) {
  98. const result = yield* Effect.tryPromise({
  99. try: () =>
  100. client.send(
  101. new GetQueryResultsCommand({
  102. QueryExecutionId: queryExecutionId,
  103. NextToken: nextToken,
  104. MaxResults: ATHENA_PAGE_SIZE,
  105. }),
  106. ),
  107. catch: (cause) => new AthenaQueryError({ message: "Failed to read Athena stats results", queryExecutionId, cause }),
  108. })
  109. const columns = result.ResultSet?.ResultSetMetadata?.ColumnInfo?.map((item) => item.Name ?? "") ?? []
  110. const rows = (result.ResultSet?.Rows ?? []).slice(nextToken ? 0 : 1).map((row) => rowData(columns, row))
  111. if (!result.NextToken) return rows
  112. return [...rows, ...(yield* results(client, queryExecutionId, result.NextToken))]
  113. })
  114. function rowData(columns: string[], row: Row): AthenaData {
  115. return Object.fromEntries(
  116. columns.flatMap((column, index) => {
  117. const value = row.Data?.[index]?.VarCharValue
  118. if (!column || value === undefined) return []
  119. return [[column, value]]
  120. }),
  121. )
  122. }