Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
221 changes: 0 additions & 221 deletions src/utils/stats.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ import {
} from './npm-download-outliers'
import { envFunctions } from './env.functions'
import {
NPM_STATS_START_DATE,
addUtcDays,
getNormalizedNpmDownloadChunks,
getNpmDailyDownloadsFromResponse,
Expand Down Expand Up @@ -883,226 +882,6 @@ export async function fetchNpmDownloadsBulk({ data }: { data: unknown }) {
return results
}

/**
* Fetch NPM download data for a package for a specific chunk
* Uses standardized year-based chunks for maximum cache reuse
* GET request with fixed boundaries allows CDN and browser caching
*
* Chunk format: YYYY (e.g., "2023" means Jan 1 - Dec 31, 2023)
* Special chunk "current" means current year to date
*/
export async function fetchNpmDownloadChunk({
data,
}: {
data: { packageName: string; year: string }
}) {
const { packageName, year } = data

// NPM download statistics only go back to January 10, 2015
const today = new Date().toISOString().substring(0, 10)
const currentYear = new Date().getFullYear().toString()

// Determine date range for this chunk
let startDate: string
let endDate: string
const isCurrentYear = year === 'current' || year === currentYear

if (year === 'current') {
// Current year to date
startDate = `${currentYear}-01-01`
endDate = today
} else {
// Full year
startDate = `${year}-01-01`
endDate = `${year}-12-31`

// Don't fetch future years
if (parseInt(year) > parseInt(currentYear)) {
return {
start: startDate,
end: endDate,
package: packageName,
year,
downloads: [],
}
}
}

// Adjust start date if before npm stats started
if (startDate < NPM_STATS_START_DATE) {
startDate = NPM_STATS_START_DATE
}

// Set aggressive cache headers for immutable historical data
// Current year data changes daily, historical data is immutable
const cacheMaxAge = isCurrentYear ? 3600 : 31536000 // 1 hour / 1 year
const cdnMaxAge = isCurrentYear ? 3600 : 31536000 // 1 hour / 1 year

setResponseHeaders(
new Headers({
// Keep CDN and browser TTLs separate so historical data can stay hot at
// the edge without forcing longer browser freshness.
'Cloudflare-CDN-Cache-Control': `public, max-age=${cdnMaxAge}${isCurrentYear ? '' : ', stale-while-revalidate=86400'}`,
'Cache-Control': `public, max-age=${cacheMaxAge}`,
}),
)

// Import cache functions
const { getCachedNpmDownloadChunk, setCachedNpmDownloadChunk } =
await import('./npm-download-cache.server')

// Check R2 cache first
let cachedChunk
try {
cachedChunk = await getCachedNpmDownloadChunk(
packageName,
startDate,
endDate,
'daily',
)
} catch (error) {
console.warn(
`[NPM Download Chunk] Cache lookup error for ${packageName} ${year}:`,
error,
)
}

// Use cache if available and immutable
if (cachedChunk) {
if (cachedChunk.isImmutable) {
return {
start: cachedChunk.dateFrom,
end: cachedChunk.dateTo,
package: packageName,
year,
downloads: normalizeNpmDownloadSeries(
packageName,
cachedChunk.dailyData,
new Date().toISOString().substring(0, 10),
),
}
}
// For current year, check if cache is still fresh (within 1 hour)
// If expired, fall through to fetch fresh data
}

// Fetch from NPM API
try {
if (npmRateLimit.isCoolingDown()) {
throw new Error('NPM API cooling down after rate limit')
}

const response = await fetch(
`https://api.npmjs.org/downloads/range/${startDate}:${endDate}/${encodeURIComponent(packageName)}`,
{
headers: {
Accept: 'application/json',
'User-Agent': 'TanStack-Stats',
},
},
)

npmRateLimit.noteResponse(response)

if (!response.ok) {
if (response.status === 404) {
// Package not found or no data for this range
console.warn(`[NPM Download Chunk] 404 for ${packageName} ${year}`)
return {
start: startDate,
end: endDate,
package: packageName,
year,
downloads: [],
}
}
if (response.status === 429) {
// Rate limited - use cached data if available
if (cachedChunk) {
console.warn(
`[NPM Download Chunk] Rate limited, using cached data for ${packageName} ${year}`,
)
return {
start: cachedChunk.dateFrom,
end: cachedChunk.dateTo,
package: packageName,
year,
downloads: cachedChunk.dailyData,
}
}
throw new Error(
'NPM API rate limit exceeded. Please try again in a moment.',
)
}
throw new Error(
`NPM API error for ${packageName} ${year}: ${response.status}`,
)
}

const result = await response.json()
const downloads = getNpmDailyDownloadsFromResponse(result)

if (!hasCompleteDailyCoverage(downloads, startDate, endDate)) {
throw new Error(
`NPM API returned incomplete range ${downloads[0]?.day ?? 'empty'}:${downloads.at(-1)?.day ?? 'empty'} for ${startDate}:${endDate}`,
)
}

// Cache this chunk
try {
const isImmutable = !isCurrentYear
await setCachedNpmDownloadChunk({
packageName,
dateFrom: startDate,
dateTo: endDate,
binSize: 'daily',
totalDownloads: downloads.reduce(
(sum: number, d: any) => sum + d.downloads,
0,
),
dailyData: downloads,
isImmutable,
})
} catch (error) {
console.warn(
`[NPM Download Chunk] Cache write error for ${packageName} ${year}:`,
error,
)
}

return {
start: startDate,
end: endDate,
package: packageName,
year,
downloads: normalizeNpmDownloadSeries(
packageName,
downloads,
new Date().toISOString().substring(0, 10),
),
}
} catch (error) {
// If fetch fails and we have cached data, use that
if (cachedChunk) {
console.warn(
`[NPM Download Chunk] Fetch failed, using cached data for ${packageName} ${year}`,
)
return {
start: cachedChunk.dateFrom,
end: cachedChunk.dateTo,
package: packageName,
year,
downloads: normalizeNpmDownloadSeries(
packageName,
cachedChunk.dailyData,
new Date().toISOString().substring(0, 10),
),
}
}
throw error
}
}

/**
* Fetch recent download statistics (daily, weekly, monthly) for a library.
*/
Expand Down
Loading