File size: 3,428 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
import type { Interface } from '../index.js'
import os from 'os'
import {
  CPU_ARCH,
  CPU_MODEL,
  GIT_BRANCH,
  GIT_SHA,
  IS_CI,
  NODE_VERSION,
  NUM_CPUS,
  OS,
  OS_RELEASE,
  USERNAME,
} from './constants.js'
import { randomUUID } from 'crypto'

type DevlowMetric = {
  event_time: number
  scenario: string
  props: Record<string, string | number | boolean | null>
  metric: string
  value: number
  unit: string
  relative_to?: string
  is_ci: boolean
  os: string
  os_release: string
  cpus: number
  cpu_model: string
  user: string
  arch: string
  total_memory_bytes: number
  node_version: string
  git_sha: string
  git_branch: string
}

export default function createInterface({
  gatewayUri = process.env.SNOWFLAKE_BATCH_URI,
  topicName = process.env.SNOWFLAKE_TOPIC_NAME,
  schemaId = process.env.SNOWFLAKE_SCHEMA_ID
    ? parseInt(process.env.SNOWFLAKE_SCHEMA_ID, 10)
    : undefined,
}: {
  gatewayUri?: string
  topicName?: string
  schemaId?: number
} = {}): Interface {
  if (!gatewayUri)
    throw new Error(
      'Snowflake gateway URI is required (set SNOWFLAKE_GATEWAY_URI)'
    )
  if (!topicName)
    throw new Error(
      'Snowflake topic name is required (set SNOWFLAKE_TOPIC_NAME)'
    )
  if (!schemaId)
    throw new Error(
      'Snowflake schema ID is required (set SNOWFLAKE_SCHEMA_ID to a valid integer)'
    )

  const records: DevlowMetric[] = []
  const iface: Interface = {
    measurement: async (scenario, props, name, value, unit, relativeTo) => {
      records.push({
        event_time: Date.now(),
        scenario,
        props,
        metric: name,
        value,
        unit,
        relative_to: relativeTo,
        is_ci: IS_CI,
        os: OS,
        os_release: OS_RELEASE,
        cpus: NUM_CPUS,
        cpu_model: CPU_MODEL,
        user: USERNAME,
        arch: CPU_ARCH,
        total_memory_bytes: os.totalmem(),
        node_version: NODE_VERSION,
        git_sha: GIT_SHA,
        git_branch: GIT_BRANCH,
      })
    },
    end: async (scenario, props) => {
      await trackAnalytics(gatewayUri, topicName, schemaId, records)
    },
  }
  return iface
}

async function trackAnalytics(
  batchUri: string,
  topic: string,
  schemaId: number,
  records: DevlowMetric[]
): Promise<void> {
  try {
    const res = await fetch(batchUri, {
      method: 'POST',
      headers: {
        'Client-Id': 'nextjs',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        schema_id: schemaId,
        topic,
        records: records.map((record) =>
          omit(
            {
              ...record,
              id: randomUUID(),
              props_json: JSON.stringify(record.props),
            },
            ['props']
          )
        ),
      }),
    })
    if (!res.ok) {
      throw new Error(
        `Unexpected HTTP response from reporting ${topic} event to Snowflake: ${res.status}. Body: ${await res.text()}`
      )
    }
  } catch (e) {
    const wrappedError = new Error('Unexpected error tracking analytics event')
    wrappedError.cause = e
    console.error(wrappedError)
  }
}

export function omit<T extends { [key: string]: unknown }, K extends keyof T>(
  object: T,
  keys: K[]
): Omit<T, K> {
  const omitted: { [key: string]: unknown } = {}
  Object.keys(object).forEach((key) => {
    if (!keys.includes(key as K)) {
      omitted[key] = object[key]
    }
  })
  return omitted as Omit<T, K>
}