1 import removeSlash from "remove-trailing-slash"
2 import axios from "axios"
3 import axiosRetry from "axios-retry"
4
5 import showAnalyticsNotification from "./show-notification"
6 import Store from "../store"
7 import isTruthy from "./is-truthy"
8
9 const MEDUSA_TELEMETRY_VERBOSE = process.env.MEDUSA_TELEMETRY_VERBOSE || false
10
11 class TelemetryDispatcher {
12 constructor(options) {
13 this.store_ = new Store()
14
15 this.host = removeSlash(
16 options.host || "https://telemetry.medusa-commerce.com"
17 )
18 this.path = removeSlash(options.path || "/batch")
19
20 let axiosInstance = options.axiosInstance
21 if (!axiosInstance) {
22 axiosInstance = axios.create()
23 }
24 this.axiosInstance = axiosInstance
25
26 this.timeout = options.timeout || false
27 this.flushed = false
28
29 axiosRetry(this.axiosInstance, {
30 retries: 3,
31 retryDelay: axiosRetry.exponentialDelay,
32 retryCondition: this.isErrorRetryable_,
33 })
34 }
35
36 isTrackingEnabled() {
37 // Cache the result
38 if (this.trackingEnabled !== undefined) {
39 return this.trackingEnabled
40 }
41 let enabled = this.store_.getConfig(`telemetry.enabled`)
42 if (enabled === undefined || enabled === null) {
43 showAnalyticsNotification()
44 enabled = true
45 this.store_.setConfig(`telemetry.enabled`, enabled)
46 }
47 this.trackingEnabled = enabled
48 return enabled
49 }
50
51 async dispatch() {
52 if (!this.isTrackingEnabled()) {
53 return
54 }
55
56 await this.store_.flushEvents(async events => {
57 if (!events.length) {
58 if (isTruthy(MEDUSA_TELEMETRY_VERBOSE)) {
59 console.log("No events to POST - skipping")
60 }
61 return true
62 }
63
64 const data = {
65 batch: events,
66 timestamp: new Date(),
67 }
68
69 const req = {
70 headers: {},
71 }
72
73 return await this.axiosInstance
74 .post(`${this.host}${this.path}`, data, req)
75 .then(() => {
76 if (isTruthy(MEDUSA_TELEMETRY_VERBOSE)) {
77 console.log("POSTing batch succeeded")
78 }
79 return true
80 })
81 .catch(e => {
82 if (isTruthy(MEDUSA_TELEMETRY_VERBOSE)) {
83 console.error("Failed to POST event batch", e)
84 }
85 return false
86 })
87 })
88 }
89
90 isErrorRetryable_(error) {
91 // Retry Network Errors.
92 if (axiosRetry.isNetworkError(error)) {
93 return true
94 }
95
96 if (!error.response) {
97 // Cannot determine if the request can be retried
98 return false
99 }
100
101 // Retry Server Errors (5xx).
102 if (error.response.status >= 500 && error.response.status <= 599) {
103 return true
104 }
105
106 // Retry if rate limited.
107 if (error.response.status === 429) {
108 return true
109 }
110
111 return false
112 }
113 }
114
115 export default TelemetryDispatcher