Mahdi Naser Moghadasi commited on
Commit
ca60d9c
·
1 Parent(s): 8811b71

Update analytics to use /data persistent storage with fallbacks

Browse files
Files changed (1) hide show
  1. app/api/analytics/route.ts +67 -36
app/api/analytics/route.ts CHANGED
@@ -3,11 +3,20 @@ import { writeFile, readFile, mkdir } from 'fs/promises'
3
  import { join } from 'path'
4
  import { existsSync } from 'fs'
5
 
6
- // Use /tmp for analytics if /app/data is not writable (Hugging Face Spaces)
 
 
 
7
  const getAnalyticsFile = () => {
 
 
 
 
 
 
 
8
  const dataDir = process.cwd()
9
  const dataPath = join(dataDir, 'data', 'analytics.json')
10
- // Check if we can write to this location, otherwise use /tmp
11
  try {
12
  if (existsSync(join(dataDir, 'data'))) {
13
  return dataPath
@@ -15,6 +24,8 @@ const getAnalyticsFile = () => {
15
  } catch {
16
  // Fallback to /tmp
17
  }
 
 
18
  return join('/tmp', 'analytics-data.json')
19
  }
20
 
@@ -100,24 +111,39 @@ function parseUserAgent(userAgent: string): { os: string; browser: string; devic
100
  }
101
 
102
  async function readAnalytics(): Promise<AnalyticsData> {
103
- const dataDir = await ensureDataDir()
104
- let analyticsFile: string
 
 
 
 
105
 
106
- // Determine which file to use
107
- if (dataDir === join(process.cwd(), 'data')) {
108
- analyticsFile = ANALYTICS_FILE
109
- } else {
110
- // Using /tmp fallback
111
- analyticsFile = join('/tmp', 'analytics-data.json')
 
112
  }
113
 
114
- // Also check /tmp as fallback
115
- const tmpFile = join('/tmp', 'analytics-data.json')
116
- if (!existsSync(analyticsFile) && existsSync(tmpFile)) {
117
- analyticsFile = tmpFile
118
  }
119
 
120
  if (!existsSync(analyticsFile)) {
 
 
 
 
 
 
 
 
 
 
121
  return {
122
  totalVisits: 0,
123
  uniqueVisitors: new Set(),
@@ -168,16 +194,12 @@ async function readAnalytics(): Promise<AnalyticsData> {
168
  }
169
 
170
  async function writeAnalytics(data: AnalyticsData): Promise<void> {
171
- const dataDir = await ensureDataDir()
172
- let analyticsFile: string
173
-
174
- // Determine which file to use
175
- if (dataDir === join(process.cwd(), 'data')) {
176
- analyticsFile = ANALYTICS_FILE
177
- } else {
178
- // Using /tmp fallback
179
- analyticsFile = join('/tmp', 'analytics-data.json')
180
- }
181
 
182
  // Convert Set to array for JSON serialization
183
  const serializable = {
@@ -186,20 +208,29 @@ async function writeAnalytics(data: AnalyticsData): Promise<void> {
186
  lastUpdated: new Date().toISOString(),
187
  }
188
 
189
- try {
190
- await writeFile(analyticsFile, JSON.stringify(serializable, null, 2))
191
- console.log(`Analytics written to: ${analyticsFile}`)
192
- } catch (error: any) {
193
- console.error(`Failed to write analytics to ${analyticsFile}:`, error)
194
- // Try /tmp as final fallback
195
- if (analyticsFile !== join('/tmp', 'analytics-data.json')) {
196
- const tmpFile = join('/tmp', 'analytics-data.json')
197
- await writeFile(tmpFile, JSON.stringify(serializable, null, 2))
198
- console.log(`Analytics written to fallback: ${tmpFile}`)
199
- } else {
200
- throw error
 
 
 
 
 
201
  }
202
  }
 
 
 
 
203
  }
204
 
205
  export async function POST(request: NextRequest) {
 
3
  import { join } from 'path'
4
  import { existsSync } from 'fs'
5
 
6
+ // Priority order for analytics file location (Hugging Face Spaces)
7
+ // 1. /data (persistent storage - paid feature, survives restarts)
8
+ // 2. /app/data (ephemeral, but works during container lifetime)
9
+ // 3. /tmp (ephemeral, cleared on restart)
10
  const getAnalyticsFile = () => {
11
+ // Try /data first (Hugging Face persistent storage)
12
+ const persistentPath = '/data/analytics.json'
13
+ if (existsSync('/data')) {
14
+ return persistentPath
15
+ }
16
+
17
+ // Try /app/data (created by Dockerfile)
18
  const dataDir = process.cwd()
19
  const dataPath = join(dataDir, 'data', 'analytics.json')
 
20
  try {
21
  if (existsSync(join(dataDir, 'data'))) {
22
  return dataPath
 
24
  } catch {
25
  // Fallback to /tmp
26
  }
27
+
28
+ // Last resort: /tmp (ephemeral)
29
  return join('/tmp', 'analytics-data.json')
30
  }
31
 
 
111
  }
112
 
113
  async function readAnalytics(): Promise<AnalyticsData> {
114
+ // Try multiple locations in priority order
115
+ const possibleFiles = [
116
+ '/data/analytics.json', // Hugging Face persistent storage (best)
117
+ ANALYTICS_FILE, // /app/data/analytics.json (ephemeral)
118
+ join('/tmp', 'analytics-data.json'), // /tmp fallback (ephemeral)
119
+ ]
120
 
121
+ let analyticsFile: string | null = null
122
+ for (const file of possibleFiles) {
123
+ if (existsSync(file)) {
124
+ analyticsFile = file
125
+ console.log(`Reading analytics from: ${file}`)
126
+ break
127
+ }
128
  }
129
 
130
+ // If no file exists, use the best available location
131
+ if (!analyticsFile) {
132
+ analyticsFile = possibleFiles[0] // Prefer /data if available
133
+ console.log(`No existing analytics file found, will create at: ${analyticsFile}`)
134
  }
135
 
136
  if (!existsSync(analyticsFile)) {
137
+ // Ensure directory exists before returning empty data
138
+ try {
139
+ const dir = analyticsFile.substring(0, analyticsFile.lastIndexOf('/'))
140
+ if (!existsSync(dir)) {
141
+ await mkdir(dir, { recursive: true, mode: 0o755 })
142
+ }
143
+ } catch {
144
+ // Directory creation failed, will try on write
145
+ }
146
+
147
  return {
148
  totalVisits: 0,
149
  uniqueVisitors: new Set(),
 
194
  }
195
 
196
  async function writeAnalytics(data: AnalyticsData): Promise<void> {
197
+ // Try multiple locations in priority order
198
+ const possibleFiles = [
199
+ '/data/analytics.json', // Hugging Face persistent storage (best)
200
+ ANALYTICS_FILE, // /app/data/analytics.json (ephemeral)
201
+ join('/tmp', 'analytics-data.json'), // /tmp fallback (ephemeral)
202
+ ]
 
 
 
 
203
 
204
  // Convert Set to array for JSON serialization
205
  const serializable = {
 
208
  lastUpdated: new Date().toISOString(),
209
  }
210
 
211
+ // Try to write to the best available location
212
+ let written = false
213
+ for (const analyticsFile of possibleFiles) {
214
+ try {
215
+ // Ensure directory exists
216
+ const dir = analyticsFile.substring(0, analyticsFile.lastIndexOf('/'))
217
+ if (!existsSync(dir)) {
218
+ await mkdir(dir, { recursive: true, mode: 0o755 })
219
+ }
220
+
221
+ await writeFile(analyticsFile, JSON.stringify(serializable, null, 2))
222
+ console.log(`✅ Analytics written to: ${analyticsFile}`)
223
+ written = true
224
+ break
225
+ } catch (error: any) {
226
+ console.warn(`⚠️ Failed to write to ${analyticsFile}:`, error.message)
227
+ // Continue to next location
228
  }
229
  }
230
+
231
+ if (!written) {
232
+ throw new Error('Failed to write analytics to any available location')
233
+ }
234
  }
235
 
236
  export async function POST(request: NextRequest) {