-
-
Notifications
You must be signed in to change notification settings - Fork 372
Expand file tree
/
Copy pathstats-db.server.ts
More file actions
1556 lines (1400 loc) · 44.6 KB
/
Copy pathstats-db.server.ts
File metadata and controls
1556 lines (1400 loc) · 44.6 KB
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Database operations for stats caching
* This file contains server-only code that uses the database.
* It should only be imported inside server function handlers.
*/
import { db } from '~/db/client'
import {
githubStatsCache,
npmPackages,
npmOrgStatsCache,
npmLibraryStatsCache,
npmDownloadChunks,
ossStatsCache,
} from '~/db/schema'
import type { OssStatsCache } from '~/db/schema'
import { desc, eq, gte, inArray, and, lte } from 'drizzle-orm'
import type {
GitHubStats,
NpmPackageStats,
NpmStats,
OSSStatsWithDelta,
} from './stats.types'
type OssStatsScopeType = 'org' | 'library'
type OssStatsRowInput = {
github: GitHubStats
previousGithub?: GitHubStats | null
githubUpdatedAt?: Date
npm: NpmStats
npmPackageCount?: number
npmUpdatedAt?: Date
scopeKey: string
scopeType: OssStatsScopeType
timeDelta?: number
}
function isGitHubStats(value: unknown): value is GitHubStats {
return (
!!value &&
typeof value === 'object' &&
typeof Reflect.get(value, 'starCount') === 'number' &&
typeof Reflect.get(value, 'contributorCount') === 'number'
)
}
function getGitHubStats(value: unknown): GitHubStats {
if (isGitHubStats(value)) {
return value
}
return {
starCount: 0,
contributorCount: 0,
}
}
function calculateGithubDelta(
current: GitHubStats,
previous: GitHubStats | null,
) {
if (!previous) {
return {}
}
return {
githubDeltaStarCount: current.starCount - previous.starCount,
githubDeltaContributorCount:
current.contributorCount - previous.contributorCount,
githubDeltaDependentCount:
current.dependentCount !== undefined &&
previous.dependentCount !== undefined
? current.dependentCount - previous.dependentCount
: null,
githubDeltaForkCount:
current.forkCount !== undefined && previous.forkCount !== undefined
? current.forkCount - previous.forkCount
: null,
}
}
function mapOssStatsRow(row: OssStatsCache): OSSStatsWithDelta {
return {
github: {
contributorCount: row.githubContributorCount,
dependentCount: row.githubDependentCount ?? undefined,
forkCount: row.githubForkCount ?? undefined,
repositoryCount: row.githubRepositoryCount ?? undefined,
starCount: row.githubStarCount,
},
npm: {
ratePerDay: row.npmRatePerDay ?? undefined,
totalDownloads: row.npmTotalDownloads,
updatedAt: row.npmUpdatedAt?.getTime(),
},
delta:
row.githubDeltaStarCount !== null ||
row.githubDeltaContributorCount !== null ||
row.githubDeltaDependentCount !== null ||
row.githubDeltaForkCount !== null
? {
github: {
contributorCount: row.githubDeltaContributorCount ?? undefined,
dependentCount: row.githubDeltaDependentCount ?? undefined,
forkCount: row.githubDeltaForkCount ?? undefined,
starCount: row.githubDeltaStarCount ?? undefined,
},
}
: undefined,
timeDelta: row.timeDeltaMs ?? undefined,
}
}
/**
* Batch fetch cached NPM package stats for multiple packages
* Much more efficient than calling getCachedNpmPackageStats individually
* Returns a map of packageName -> NpmPackageStats
*/
export async function getBatchCachedNpmPackageStats(
packageNames: string[],
): Promise<Map<string, NpmPackageStats>> {
const results = new Map<string, NpmPackageStats>()
if (packageNames.length === 0) {
return results
}
try {
// Single query to fetch all packages at once
const cached = await db.query.npmPackages.findMany({
where: inArray(npmPackages.packageName, packageNames),
})
// Process all cached results
for (const pkg of cached) {
if (pkg.downloads !== null) {
results.set(pkg.packageName, {
downloads: pkg.downloads,
ratePerDay: pkg.ratePerDay ?? undefined,
updatedAt: pkg.updatedAt.getTime(),
})
}
}
return results
} catch (error) {
console.error('[NPM Stats Cache] Error reading batch cache:', error)
return results
}
}
export async function getCachedOssStats(
scopeType: OssStatsScopeType,
scopeKey: string,
): Promise<OSSStatsWithDelta | null> {
try {
const row = await db.query.ossStatsCache.findFirst({
where: and(
eq(ossStatsCache.scopeType, scopeType),
eq(ossStatsCache.scopeKey, scopeKey),
),
})
return row ? mapOssStatsRow(row) : null
} catch (error) {
console.error(
`[OSS Stats Cache] Error reading ${scopeType}:${scopeKey}:`,
error,
)
return null
}
}
export async function upsertOssStatsCacheRow({
github,
previousGithub,
githubUpdatedAt,
npm,
npmPackageCount,
npmUpdatedAt,
scopeKey,
scopeType,
timeDelta,
}: OssStatsRowInput): Promise<void> {
const now = new Date()
await db
.insert(ossStatsCache)
.values({
scopeType,
scopeKey,
githubStarCount: github.starCount,
githubContributorCount: github.contributorCount,
githubDependentCount: github.dependentCount ?? null,
githubForkCount: github.forkCount ?? null,
githubRepositoryCount: github.repositoryCount ?? null,
...calculateGithubDelta(github, previousGithub ?? null),
githubUpdatedAt: githubUpdatedAt ?? now,
npmTotalDownloads: npm.totalDownloads,
npmRatePerDay: npm.ratePerDay ?? null,
npmPackageCount: npmPackageCount ?? 0,
npmUpdatedAt: npmUpdatedAt ?? now,
timeDeltaMs: timeDelta ?? null,
updatedAt: now,
})
.onConflictDoUpdate({
target: [ossStatsCache.scopeType, ossStatsCache.scopeKey],
set: {
githubStarCount: github.starCount,
githubContributorCount: github.contributorCount,
githubDependentCount: github.dependentCount ?? null,
githubForkCount: github.forkCount ?? null,
githubRepositoryCount: github.repositoryCount ?? null,
...calculateGithubDelta(github, previousGithub ?? null),
githubUpdatedAt: githubUpdatedAt ?? now,
npmTotalDownloads: npm.totalDownloads,
npmRatePerDay: npm.ratePerDay ?? null,
npmPackageCount: npmPackageCount ?? 0,
npmUpdatedAt: npmUpdatedAt ?? now,
timeDeltaMs: timeDelta ?? null,
updatedAt: now,
},
})
}
export async function rebuildOssStatsCache(org: string = 'tanstack') {
const now = new Date()
const { libraries } = await import('~/libraries')
const [packages, githubCacheRows] = await Promise.all([
db.query.npmPackages.findMany(),
db.query.githubStatsCache.findMany(),
])
const githubCacheMap = new Map(
githubCacheRows.map((row) => [row.cacheKey, row] as const),
)
const orgNpmStats: NpmStats = {
totalDownloads: 0,
}
let orgPackageCount = 0
let orgLatestUpdate: Date | undefined
const libraryNpmStatsMap = new Map<
string,
{ npm: NpmStats; packageCount: number; updatedAt?: Date }
>()
// When a library declares explicit npmPackageNames, only those packages
// count toward its aggregate. This avoids counting internal sub-packages
// (e.g. start-server-core, start-plugin-core) that are co-installed as
// dependencies of a single user-facing install and would otherwise inflate
// the totals several times over.
const explicitPackagesByLibrary = new Map<string, Set<string>>()
for (const library of libraries) {
if (library.npmPackageNames?.length) {
explicitPackagesByLibrary.set(
library.id,
new Set(library.npmPackageNames),
)
}
}
for (const pkg of packages) {
if (pkg.downloads === null) {
continue
}
orgNpmStats.totalDownloads += pkg.downloads
orgNpmStats.ratePerDay =
(orgNpmStats.ratePerDay ?? 0) + (pkg.ratePerDay ?? 0)
orgPackageCount += 1
if (!orgLatestUpdate || pkg.updatedAt > orgLatestUpdate) {
orgLatestUpdate = pkg.updatedAt
}
if (!pkg.libraryId) {
continue
}
const explicitPackages = explicitPackagesByLibrary.get(pkg.libraryId)
if (explicitPackages && !explicitPackages.has(pkg.packageName)) {
continue
}
const existing = libraryNpmStatsMap.get(pkg.libraryId) ?? {
npm: { totalDownloads: 0 },
packageCount: 0,
updatedAt: undefined,
}
existing.npm.totalDownloads += pkg.downloads
existing.npm.ratePerDay =
(existing.npm.ratePerDay ?? 0) + (pkg.ratePerDay ?? 0)
existing.packageCount += 1
if (!existing.updatedAt || pkg.updatedAt > existing.updatedAt) {
existing.updatedAt = pkg.updatedAt
}
libraryNpmStatsMap.set(pkg.libraryId, existing)
}
if (orgLatestUpdate) {
orgNpmStats.updatedAt = orgLatestUpdate.getTime()
}
const orgGithubRow = githubCacheMap.get(`org:${org}`)
const orgGithubStats = getGitHubStats(orgGithubRow?.stats)
const orgPreviousGithubStats = orgGithubRow?.previousStats
? getGitHubStats(orgGithubRow.previousStats)
: null
const orgTimeDelta = orgGithubRow?.updatedAt
? orgGithubRow.updatedAt.getTime() - orgGithubRow.createdAt.getTime()
: undefined
await upsertOssStatsCacheRow({
github: orgGithubStats,
previousGithub: orgPreviousGithubStats,
githubUpdatedAt: orgGithubRow?.updatedAt ?? now,
npm: orgNpmStats,
npmPackageCount: orgPackageCount,
npmUpdatedAt: orgLatestUpdate ?? now,
scopeKey: org,
scopeType: 'org',
timeDelta: orgTimeDelta,
})
for (const library of libraries) {
const npmAggregate = libraryNpmStatsMap.get(library.id) ?? {
npm: { totalDownloads: 0 },
packageCount: 0,
updatedAt: undefined,
}
const githubRow = githubCacheMap.get(library.repo)
const githubStats = getGitHubStats(githubRow?.stats)
const previousGithubStats = githubRow?.previousStats
? getGitHubStats(githubRow.previousStats)
: null
const timeDelta = githubRow?.updatedAt
? githubRow.updatedAt.getTime() - githubRow.createdAt.getTime()
: undefined
if (npmAggregate.updatedAt) {
npmAggregate.npm.updatedAt = npmAggregate.updatedAt.getTime()
}
await upsertOssStatsCacheRow({
github: githubStats,
previousGithub: previousGithubStats,
githubUpdatedAt: githubRow?.updatedAt ?? now,
npm: npmAggregate.npm,
npmPackageCount: npmAggregate.packageCount,
npmUpdatedAt: npmAggregate.updatedAt ?? now,
scopeKey: library.id,
scopeType: 'library',
timeDelta,
})
}
}
/**
* Store NPM package stats in cache with calculated growth rate
* Also incrementally updates library and org-level caches
*/
export async function setCachedNpmPackageStats(
packageName: string,
downloads: number,
ttlHours: number = 24,
ratePerDay?: number,
): Promise<void> {
try {
const expiresAt = new Date()
expiresAt.setHours(expiresAt.getHours() + ttlHours)
const now = new Date()
const existing = await db.query.npmPackages.findFirst({
where: eq(npmPackages.packageName, packageName),
})
const oldDownloads = existing?.downloads ?? 0
const downloadDelta = downloads - oldDownloads
// Get libraryId from existing record, or we'll need to look it up after update
const libraryId = existing?.libraryId
if (existing) {
// Update stats with new data
await db
.update(npmPackages)
.set({
downloads, // New download count
ratePerDay: ratePerDay ?? null, // Store calculated growth rate
statsExpiresAt: expiresAt,
updatedAt: now,
})
.where(eq(npmPackages.packageName, packageName))
} else {
try {
// First time inserting package
await db.insert(npmPackages).values({
packageName,
downloads,
ratePerDay: ratePerDay ?? null,
statsExpiresAt: expiresAt,
})
} catch (insertError: any) {
// Handle race condition: if another request inserted the same package concurrently,
// try updating instead
if (insertError?.code === '23505') {
// Unique constraint violation - fetch existing and update properly
const raceExisting = await db.query.npmPackages.findFirst({
where: eq(npmPackages.packageName, packageName),
})
if (raceExisting) {
await db
.update(npmPackages)
.set({
downloads,
ratePerDay: ratePerDay ?? null,
statsExpiresAt: expiresAt,
updatedAt: now,
})
.where(eq(npmPackages.packageName, packageName))
}
} else {
throw insertError
}
}
}
// Get libraryId after update (in case it was set during package discovery)
const updated = await db.query.npmPackages.findFirst({
where: eq(npmPackages.packageName, packageName),
})
const finalLibraryId = updated?.libraryId ?? libraryId
// Incrementally update library cache if libraryId exists
if (finalLibraryId && downloadDelta !== 0) {
await updateLibraryStatsCache(finalLibraryId, downloadDelta)
}
// Incrementally update org cache (always update for @tanstack packages)
if (packageName.startsWith('@tanstack/') && downloadDelta !== 0) {
await updateOrgStatsCache(
'tanstack',
packageName,
oldDownloads,
downloads,
)
}
} catch (error) {
console.error('[NPM Stats Cache] Error writing cache:', error)
// Don't throw - cache failures shouldn't break the request
}
}
/**
* Incrementally update library stats cache
*/
async function updateLibraryStatsCache(
libraryId: string,
downloadDelta: number,
): Promise<void> {
try {
const existing = await db.query.npmLibraryStatsCache.findFirst({
where: eq(npmLibraryStatsCache.libraryId, libraryId),
})
if (existing) {
await db
.update(npmLibraryStatsCache)
.set({
previousTotalDownloads: existing.totalDownloads,
totalDownloads: existing.totalDownloads + downloadDelta,
updatedAt: new Date(),
})
.where(eq(npmLibraryStatsCache.libraryId, libraryId))
} else {
// Get package count for this library
const packages = await db.query.npmPackages.findMany({
where: eq(npmPackages.libraryId, libraryId),
})
const totalDownloads = packages.reduce(
(sum, pkg) => sum + (pkg.downloads ?? 0),
0,
)
await db.insert(npmLibraryStatsCache).values({
libraryId,
totalDownloads,
packageCount: packages.length,
previousTotalDownloads: null,
})
}
} catch (error) {
console.error(
`[Library Stats Cache] Error updating cache for ${libraryId}:`,
error,
)
}
}
/**
* Incrementally update org stats cache
*/
async function updateOrgStatsCache(
orgName: string,
packageName: string,
oldDownloads: number,
newDownloads: number,
): Promise<void> {
try {
const existing = await db.query.npmOrgStatsCache.findFirst({
where: eq(npmOrgStatsCache.orgName, orgName),
})
if (existing) {
const packageStats = (existing.packageStats as Record<string, any>) || {}
const downloadDelta = newDownloads - oldDownloads
// Update package stats
packageStats[packageName] = {
downloads: newDownloads,
previousDownloads: oldDownloads,
}
await db
.update(npmOrgStatsCache)
.set({
totalDownloads: existing.totalDownloads + downloadDelta,
packageStats,
updatedAt: new Date(),
})
.where(eq(npmOrgStatsCache.orgName, orgName))
} else {
// If org cache doesn't exist, we'll need to compute it from all packages
// This should be rare - scheduled tasks should create it
console.warn(
`[Org Stats Cache] Cache doesn't exist for ${orgName}, skipping incremental update`,
)
}
} catch (error) {
console.error(
`[Org Stats Cache] Error updating cache for ${orgName}:`,
error,
)
}
}
/**
* Get cached NPM org stats if available and not expired
*/
export async function getCachedNpmOrgStats(
orgName: string,
): Promise<NpmStats | null> {
try {
const cached = await db.query.npmOrgStatsCache.findFirst({
where: eq(npmOrgStatsCache.orgName, orgName),
})
if (cached && cached.expiresAt > new Date()) {
console.log(`[NPM Org Stats Cache] Cache hit for org ${orgName}`)
// Calculate org-level ratePerDay from packages in the database
const { like, or } = await import('drizzle-orm')
const { libraries } = await import('~/libraries')
const legacyPackages: string[] = []
for (const library of libraries) {
if (
'legacyPackages' in library &&
Array.isArray(library.legacyPackages)
) {
legacyPackages.push(...library.legacyPackages)
}
}
let packages = await db.query.npmPackages.findMany({
where: like(npmPackages.packageName, `@${orgName}/%`),
})
if (legacyPackages.length > 0) {
const legacyResults = await db.query.npmPackages.findMany({
where: or(
...legacyPackages.map((pkg) => eq(npmPackages.packageName, pkg)),
),
})
packages = [...packages, ...legacyResults]
}
const totalRatePerDay = packages.reduce(
(sum, pkg) => sum + (pkg.ratePerDay ?? 0),
0,
)
return {
totalDownloads: cached.totalDownloads,
packageStats: cached.packageStats as Record<string, NpmPackageStats>,
ratePerDay: totalRatePerDay > 0 ? totalRatePerDay : undefined,
updatedAt: cached.updatedAt.getTime(),
}
}
return null
} catch (error) {
console.error('[NPM Org Stats Cache] Error reading cache:', error)
return null
}
}
/**
* Get expired NPM org stats cache if available (for fallback when cache is expired)
*/
export async function getExpiredNpmOrgStats(
orgName: string,
): Promise<NpmStats | null> {
try {
const cached = await db.query.npmOrgStatsCache.findFirst({
where: eq(npmOrgStatsCache.orgName, orgName),
})
if (cached) {
console.log(
`[NPM Org Stats Cache] Using expired cache for org ${orgName}`,
)
// Calculate org-level ratePerDay from packages in the database
const { like, or } = await import('drizzle-orm')
const { libraries } = await import('~/libraries')
const legacyPackages: string[] = []
for (const library of libraries) {
if (
'legacyPackages' in library &&
Array.isArray(library.legacyPackages)
) {
legacyPackages.push(...library.legacyPackages)
}
}
let packages = await db.query.npmPackages.findMany({
where: like(npmPackages.packageName, `@${orgName}/%`),
})
if (legacyPackages.length > 0) {
const legacyResults = await db.query.npmPackages.findMany({
where: or(
...legacyPackages.map((pkg) => eq(npmPackages.packageName, pkg)),
),
})
packages = [...packages, ...legacyResults]
}
const totalRatePerDay = packages.reduce(
(sum, pkg) => sum + (pkg.ratePerDay ?? 0),
0,
)
return {
totalDownloads: cached.totalDownloads,
packageStats: cached.packageStats as Record<string, NpmPackageStats>,
ratePerDay: totalRatePerDay > 0 ? totalRatePerDay : undefined,
updatedAt: cached.updatedAt.getTime(),
}
}
return null
} catch (error) {
console.error('[NPM Org Stats Cache] Error reading expired cache:', error)
return null
}
}
/**
* Store NPM org stats in cache, preserving previous stats for rate calculation
*/
export async function setCachedNpmOrgStats(
orgName: string,
stats: NpmStats,
ttlHours: number = 24,
): Promise<void> {
try {
const expiresAt = new Date()
expiresAt.setHours(expiresAt.getHours() + ttlHours)
const now = new Date()
const existing = await db.query.npmOrgStatsCache.findFirst({
where: eq(npmOrgStatsCache.orgName, orgName),
})
if (existing) {
// Update stats
await db
.update(npmOrgStatsCache)
.set({
totalDownloads: stats.totalDownloads,
packageStats: stats.packageStats,
expiresAt,
updatedAt: now,
})
.where(eq(npmOrgStatsCache.orgName, orgName))
console.log(
`[NPM Org Stats Cache] Updated cache for org ${orgName} (expires at ${expiresAt.toISOString()})`,
)
} else {
// First time
await db.insert(npmOrgStatsCache).values({
orgName,
totalDownloads: stats.totalDownloads,
packageStats: stats.packageStats,
expiresAt,
})
console.log(
`[NPM Org Stats Cache] Created cache for org ${orgName} (expires at ${expiresAt.toISOString()})`,
)
}
} catch (error) {
console.error('[NPM Org Stats Cache] Error writing cache:', error)
// Don't throw - cache failures shouldn't break the request
}
}
/**
* Get cached library stats
*/
export async function getCachedLibraryStats(libraryId: string): Promise<{
libraryId: string
totalDownloads: number
packageCount: number
previousTotalDownloads: number | null
} | null> {
try {
const cached = await db.query.npmLibraryStatsCache.findFirst({
where: eq(npmLibraryStatsCache.libraryId, libraryId),
})
if (cached) {
return {
libraryId: cached.libraryId,
totalDownloads: cached.totalDownloads,
packageCount: cached.packageCount,
previousTotalDownloads: cached.previousTotalDownloads,
}
}
return null
} catch (error) {
console.error(
`[Library Stats Cache] Error reading cache for ${libraryId}:`,
error,
)
return null
}
}
/**
* Get all cached library stats
*/
export async function getAllCachedLibraryStats(): Promise<
Array<{
libraryId: string
totalDownloads: number
packageCount: number
previousTotalDownloads: number | null
}>
> {
try {
const allCached = await db.query.npmLibraryStatsCache.findMany({
orderBy: [npmLibraryStatsCache.libraryId],
})
return allCached.map((cached) => ({
libraryId: cached.libraryId,
totalDownloads: cached.totalDownloads,
packageCount: cached.packageCount,
previousTotalDownloads: cached.previousTotalDownloads,
}))
} catch (error) {
console.error('[Library Stats Cache] Error reading all cache:', error)
return []
}
}
/**
* Get all registered packages for a specific library or all packages
*/
export async function getRegisteredPackages(
libraryId?: string,
): Promise<string[]> {
try {
const packages = libraryId
? await db.query.npmPackages.findMany({
where: eq(npmPackages.libraryId, libraryId),
})
: await db.query.npmPackages.findMany()
return packages.map((p) => p.packageName)
} catch (error) {
console.error(
'[Package Registry] Error fetching packages:',
error instanceof Error ? error.message : String(error),
)
return []
}
}
/**
* Discover and register all packages for an org
* This fetches all packages from npm registry and registers them in the database
*/
export async function discoverAndRegisterPackages(org: string): Promise<void> {
try {
// Fetch all packages in the org
const response = await fetch(
`https://registry.npmjs.org/-/org/${org}/package`,
{
headers: {
Accept: 'application/json',
'User-Agent': 'TanStack-Stats',
},
},
)
if (!response.ok) {
throw new Error(
`NPM Registry API error: ${response.status} ${response.statusText}`,
)
}
const data = await response.json()
let packageNames = Object.keys(data)
// Import libraries to map packages to library IDs
const { libraries } = await import('~/libraries')
// Add legacy (non-scoped) packages from library definitions
// The org endpoint only returns @tanstack/* scoped packages
const legacyPackages: string[] = []
for (const library of libraries) {
if (
'legacyPackages' in library &&
Array.isArray(library.legacyPackages)
) {
legacyPackages.push(...library.legacyPackages)
}
}
if (legacyPackages.length > 0) {
packageNames = [...packageNames, ...legacyPackages]
}
// For each package, check if it exists and register/update metadata
for (const packageName of packageNames) {
try {
// Check if package already exists
const existing = await db.query.npmPackages.findFirst({
where: eq(npmPackages.packageName, packageName),
})
// Try to determine libraryId from package name
let libraryId: string | null = null
let isLegacy = false
// Check for legacy packages first (exact match)
for (const library of libraries) {
if (
'legacyPackages' in library &&
Array.isArray(library.legacyPackages) &&
library.legacyPackages.includes(packageName)
) {
libraryId = library.id
isLegacy = true
break
}
}
// If not a legacy package, try to map based on package name patterns
if (!libraryId) {
for (const library of libraries) {
const libraryName = library.id
// Special handling for "react-charts" library id
if (libraryName === 'react-charts') {
if (
packageName === `@${org}/react-charts` ||
packageName.includes('/react-charts')
) {
libraryId = libraryName
break
}
}
// Special handling for "create-tsrouter-app" library id
if (libraryName === 'create-tsrouter-app') {
if (
packageName === `@${org}/create-router` ||
packageName === `@${org}/create-start` ||
packageName.includes('/create-router') ||
packageName.includes('/create-start')
) {
libraryId = libraryName
break
}
}
// Check various patterns:
// 1. Exact match: @tanstack/query
// 2. Prefixed: @tanstack/react-query, @tanstack/vue-query
// 3. Suffixed: @tanstack/query-core, @tanstack/query-devtools
if (
packageName === `@${org}/${libraryName}` ||
packageName.includes(`/${libraryName}-`) ||
packageName.includes(`-${libraryName}-`) ||
packageName.includes(`-${libraryName}`) ||
new RegExp(`^@${org}/[a-z]+-${libraryName}$`, 'i').test(
packageName,
)
) {
libraryId = libraryName
break
}
}
}
const now = new Date()
if (existing) {
// Update metadata if not checked recently (within last 7 days)
const shouldUpdate =
!existing.metadataCheckedAt ||
now.getTime() - existing.metadataCheckedAt.getTime() >
7 * 24 * 60 * 60 * 1000
if (shouldUpdate || existing.libraryId !== libraryId) {
await db
.update(npmPackages)
.set({
libraryId,
isLegacy,
metadataCheckedAt: now,
updatedAt: now,
})
.where(eq(npmPackages.packageName, packageName))
}
} else {
// Register new package
await db.insert(npmPackages).values({
packageName,
libraryId,
isLegacy,
metadataCheckedAt: now,
downloads: null,
statsExpiresAt: null,
})
}
} catch (error) {
console.error(
`[Package Discovery] Error processing ${packageName}:`,
error instanceof Error ? error.message : String(error),
)
// Continue with next package
}
}
} catch (error) {
console.error(
'[Package Discovery] Error discovering packages:',
error instanceof Error ? error.message : String(error),
)
throw error
}
}
/**
* Compute org stats purely from cached package data in the database
* This is a fast recalculation that doesn't fetch from NPM API
*/
export async function computeOrgStatsFromCache(org: string): Promise<NpmStats> {
try {
const { like, or, eq } = await import('drizzle-orm')
// Get legacy package names
const { libraries } = await import('~/libraries')
const legacyPackages: string[] = []
for (const library of libraries) {
if (
'legacyPackages' in library &&
Array.isArray(library.legacyPackages)
) {
legacyPackages.push(...library.legacyPackages)
}
}
// Get all packages for this org (e.g., all @tanstack/* packages + legacy packages)
let packages = await db.query.npmPackages.findMany({
where: like(npmPackages.packageName, `@${org}/%`),
})