1 import path from "path"
2 import {
3 appendFileSync,
4 statSync,
5 readFileSync,
6 renameSync,
7 readdirSync,
8 existsSync,
9 unlinkSync,
10 } from "fs"
11
12 import isTruthy from "./is-truthy"
13
14 const MEDUSA_TELEMETRY_VERBOSE = process.env.MEDUSA_TELEMETRY_VERBOSE || false
15
16 class Outbox {
17 constructor(baseDir) {
18 this.eventsJsonFileName = `events.json`
19 this.bufferFilePath = path.join(baseDir, this.eventsJsonFileName)
20 this.baseDir = baseDir
21 }
22
23 appendToBuffer(event) {
24 try {
25 appendFileSync(this.bufferFilePath, event, `utf8`)
26 } catch (e) {
27 if (isTruthy(MEDUSA_TELEMETRY_VERBOSE)) {
28 console.error("Failed to append to buffer", e)
29 }
30 }
31 }
32
33 getSize() {
34 if (!existsSync(this.bufferFilePath)) {
35 return 0
36 }
37
38 try {
39 const stats = statSync(this.bufferFilePath)
40 return stats.size
41 } catch (e) {
42 if (isTruthy(MEDUSA_TELEMETRY_VERBOSE)) {
43 console.error("Failed to get outbox size", e)
44 }
45 }
46 return 0
47 }
48
49 getCount() {
50 if (!existsSync(this.bufferFilePath)) {
51 return 0
52 }
53
54 try {
55 const fileBuffer = readFileSync(this.bufferFilePath)
56 const str = fileBuffer.toString()
57 const lines = str.split("\n")
58 return lines.length - 1
59 } catch (e) {
60 if (isTruthy(MEDUSA_TELEMETRY_VERBOSE)) {
61 console.error("Failed to get outbox count", e)
62 }
63 }
64 return 0
65 }
66
67 async flushFile(filePath, flushOperation) {
68 const now = `${Date.now()}-${process.pid}`
69 let success = false
70 let contents = ``
71 try {
72 if (!existsSync(filePath)) {
73 return true
74 }
75 // Unique temporary file name across multiple concurrent Medusa instances
76 const newPath = `${this.bufferFilePath}-${now}`
77 renameSync(filePath, newPath)
78 contents = readFileSync(newPath, `utf8`)
79 unlinkSync(newPath)
80
81 // There is still a chance process dies while sending data and some events are lost
82 // This will be ok for now, however
83 success = await flushOperation(contents)
84 } catch (e) {
85 if (isTruthy(MEDUSA_TELEMETRY_VERBOSE)) {
86 console.error("Failed to perform file flush", e)
87 }
88 } finally {
89 // if sending fails, we write the data back to the log
90 if (!success) {
91 if (isTruthy(MEDUSA_TELEMETRY_VERBOSE)) {
92 console.error(
93 "File flush did not succeed - writing back to file",
94 success
95 )
96 }
97 this.appendToBuffer(contents)
98 }
99 }
100 return true
101 }
102
103 async startFlushEvents(flushOperation) {
104 try {
105 await this.flushFile(this.bufferFilePath, flushOperation)
106 const files = readdirSync(this.baseDir)
107 const filtered = files.filter(p => p.startsWith(`events.json`))
108 for (const file of filtered) {
109 await this.flushFile(path.join(this.baseDir, file), flushOperation)
110 }
111 return true
112 } catch (e) {
113 if (isTruthy(MEDUSA_TELEMETRY_VERBOSE)) {
114 console.error("Failed to perform flush", e)
115 }
116 }
117 return false
118 }
119 }
120
121 export default Outbox