@vllnt/convex-music 0.1.0-canary.09eea4e

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (301) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +169 -0
  3. package/dist/client/index.d.ts +284 -0
  4. package/dist/client/index.d.ts.map +1 -0
  5. package/dist/client/index.js +166 -0
  6. package/dist/client/index.js.map +1 -0
  7. package/dist/client/types.d.ts +100 -0
  8. package/dist/client/types.d.ts.map +1 -0
  9. package/dist/client/types.js +2 -0
  10. package/dist/client/types.js.map +1 -0
  11. package/dist/component/_generated/api.d.ts +125 -0
  12. package/dist/component/_generated/api.d.ts.map +1 -0
  13. package/dist/component/_generated/api.js +31 -0
  14. package/dist/component/_generated/api.js.map +1 -0
  15. package/dist/component/_generated/component.d.ts +1143 -0
  16. package/dist/component/_generated/component.d.ts.map +1 -0
  17. package/dist/component/_generated/component.js +11 -0
  18. package/dist/component/_generated/component.js.map +1 -0
  19. package/dist/component/_generated/dataModel.d.ts +46 -0
  20. package/dist/component/_generated/dataModel.d.ts.map +1 -0
  21. package/dist/component/_generated/dataModel.js +11 -0
  22. package/dist/component/_generated/dataModel.js.map +1 -0
  23. package/dist/component/_generated/server.d.ts +133 -0
  24. package/dist/component/_generated/server.d.ts.map +1 -0
  25. package/dist/component/_generated/server.js +80 -0
  26. package/dist/component/_generated/server.js.map +1 -0
  27. package/dist/component/actions.d.ts +144 -0
  28. package/dist/component/actions.d.ts.map +1 -0
  29. package/dist/component/actions.js +125 -0
  30. package/dist/component/actions.js.map +1 -0
  31. package/dist/component/catalog/browse_order.d.ts +22 -0
  32. package/dist/component/catalog/browse_order.d.ts.map +1 -0
  33. package/dist/component/catalog/browse_order.js +37 -0
  34. package/dist/component/catalog/browse_order.js.map +1 -0
  35. package/dist/component/catalog/field_source_policy.d.ts +30 -0
  36. package/dist/component/catalog/field_source_policy.d.ts.map +1 -0
  37. package/dist/component/catalog/field_source_policy.js +36 -0
  38. package/dist/component/catalog/field_source_policy.js.map +1 -0
  39. package/dist/component/catalog/merge.d.ts +58 -0
  40. package/dist/component/catalog/merge.d.ts.map +1 -0
  41. package/dist/component/catalog/merge.js +74 -0
  42. package/dist/component/catalog/merge.js.map +1 -0
  43. package/dist/component/catalog/mutations.d.ts +78 -0
  44. package/dist/component/catalog/mutations.d.ts.map +1 -0
  45. package/dist/component/catalog/mutations.js +259 -0
  46. package/dist/component/catalog/mutations.js.map +1 -0
  47. package/dist/component/catalog/promote.d.ts +21 -0
  48. package/dist/component/catalog/promote.d.ts.map +1 -0
  49. package/dist/component/catalog/promote.js +25 -0
  50. package/dist/component/catalog/promote.js.map +1 -0
  51. package/dist/component/catalog/queries.d.ts +421 -0
  52. package/dist/component/catalog/queries.d.ts.map +1 -0
  53. package/dist/component/catalog/queries.js +168 -0
  54. package/dist/component/catalog/queries.js.map +1 -0
  55. package/dist/component/config/mutations.d.ts +11 -0
  56. package/dist/component/config/mutations.d.ts.map +1 -0
  57. package/dist/component/config/mutations.js +30 -0
  58. package/dist/component/config/mutations.js.map +1 -0
  59. package/dist/component/config/queries.d.ts +9 -0
  60. package/dist/component/config/queries.d.ts.map +1 -0
  61. package/dist/component/config/queries.js +20 -0
  62. package/dist/component/config/queries.js.map +1 -0
  63. package/dist/component/convex.config.d.ts +3 -0
  64. package/dist/component/convex.config.d.ts.map +1 -0
  65. package/dist/component/convex.config.js +30 -0
  66. package/dist/component/convex.config.js.map +1 -0
  67. package/dist/component/crons.d.ts +11 -0
  68. package/dist/component/crons.d.ts.map +1 -0
  69. package/dist/component/crons.js +41 -0
  70. package/dist/component/crons.js.map +1 -0
  71. package/dist/component/imports/actions.d.ts +119 -0
  72. package/dist/component/imports/actions.d.ts.map +1 -0
  73. package/dist/component/imports/actions.js +442 -0
  74. package/dist/component/imports/actions.js.map +1 -0
  75. package/dist/component/imports/dedupe.d.ts +29 -0
  76. package/dist/component/imports/dedupe.d.ts.map +1 -0
  77. package/dist/component/imports/dedupe.js +33 -0
  78. package/dist/component/imports/dedupe.js.map +1 -0
  79. package/dist/component/imports/mutations.d.ts +59 -0
  80. package/dist/component/imports/mutations.d.ts.map +1 -0
  81. package/dist/component/imports/mutations.js +151 -0
  82. package/dist/component/imports/mutations.js.map +1 -0
  83. package/dist/component/imports/queries.d.ts +68 -0
  84. package/dist/component/imports/queries.d.ts.map +1 -0
  85. package/dist/component/imports/queries.js +22 -0
  86. package/dist/component/imports/queries.js.map +1 -0
  87. package/dist/component/imports/state.d.ts +36 -0
  88. package/dist/component/imports/state.d.ts.map +1 -0
  89. package/dist/component/imports/state.js +62 -0
  90. package/dist/component/imports/state.js.map +1 -0
  91. package/dist/component/mutations.d.ts +55 -0
  92. package/dist/component/mutations.d.ts.map +1 -0
  93. package/dist/component/mutations.js +74 -0
  94. package/dist/component/mutations.js.map +1 -0
  95. package/dist/component/providers/actions.d.ts +26 -0
  96. package/dist/component/providers/actions.d.ts.map +1 -0
  97. package/dist/component/providers/actions.js +92 -0
  98. package/dist/component/providers/actions.js.map +1 -0
  99. package/dist/component/providers/apple/impl.d.ts +52 -0
  100. package/dist/component/providers/apple/impl.d.ts.map +1 -0
  101. package/dist/component/providers/apple/impl.js +127 -0
  102. package/dist/component/providers/apple/impl.js.map +1 -0
  103. package/dist/component/providers/apple/jwt.d.ts +32 -0
  104. package/dist/component/providers/apple/jwt.d.ts.map +1 -0
  105. package/dist/component/providers/apple/jwt.js +68 -0
  106. package/dist/component/providers/apple/jwt.js.map +1 -0
  107. package/dist/component/providers/apple/mappers.d.ts +20 -0
  108. package/dist/component/providers/apple/mappers.d.ts.map +1 -0
  109. package/dist/component/providers/apple/mappers.js +68 -0
  110. package/dist/component/providers/apple/mappers.js.map +1 -0
  111. package/dist/component/providers/apple/types.d.ts +80 -0
  112. package/dist/component/providers/apple/types.d.ts.map +1 -0
  113. package/dist/component/providers/apple/types.js +7 -0
  114. package/dist/component/providers/apple/types.js.map +1 -0
  115. package/dist/component/providers/deezer/impl.d.ts +37 -0
  116. package/dist/component/providers/deezer/impl.d.ts.map +1 -0
  117. package/dist/component/providers/deezer/impl.js +99 -0
  118. package/dist/component/providers/deezer/impl.js.map +1 -0
  119. package/dist/component/providers/deezer/mappers.d.ts +18 -0
  120. package/dist/component/providers/deezer/mappers.d.ts.map +1 -0
  121. package/dist/component/providers/deezer/mappers.js +53 -0
  122. package/dist/component/providers/deezer/mappers.js.map +1 -0
  123. package/dist/component/providers/deezer/types.d.ts +59 -0
  124. package/dist/component/providers/deezer/types.d.ts.map +1 -0
  125. package/dist/component/providers/deezer/types.js +7 -0
  126. package/dist/component/providers/deezer/types.js.map +1 -0
  127. package/dist/component/providers/fetch.d.ts +69 -0
  128. package/dist/component/providers/fetch.d.ts.map +1 -0
  129. package/dist/component/providers/fetch.js +145 -0
  130. package/dist/component/providers/fetch.js.map +1 -0
  131. package/dist/component/providers/musicbrainz/impl.d.ts +36 -0
  132. package/dist/component/providers/musicbrainz/impl.d.ts.map +1 -0
  133. package/dist/component/providers/musicbrainz/impl.js +74 -0
  134. package/dist/component/providers/musicbrainz/impl.js.map +1 -0
  135. package/dist/component/providers/musicbrainz/mappers.d.ts +10 -0
  136. package/dist/component/providers/musicbrainz/mappers.d.ts.map +1 -0
  137. package/dist/component/providers/musicbrainz/mappers.js +32 -0
  138. package/dist/component/providers/musicbrainz/mappers.js.map +1 -0
  139. package/dist/component/providers/musicbrainz/types.d.ts +24 -0
  140. package/dist/component/providers/musicbrainz/types.d.ts.map +1 -0
  141. package/dist/component/providers/musicbrainz/types.js +7 -0
  142. package/dist/component/providers/musicbrainz/types.js.map +1 -0
  143. package/dist/component/providers/registry.d.ts +22 -0
  144. package/dist/component/providers/registry.d.ts.map +1 -0
  145. package/dist/component/providers/registry.js +33 -0
  146. package/dist/component/providers/registry.js.map +1 -0
  147. package/dist/component/providers/spotify/client.d.ts +25 -0
  148. package/dist/component/providers/spotify/client.d.ts.map +1 -0
  149. package/dist/component/providers/spotify/client.js +30 -0
  150. package/dist/component/providers/spotify/client.js.map +1 -0
  151. package/dist/component/providers/spotify/impl.d.ts +51 -0
  152. package/dist/component/providers/spotify/impl.d.ts.map +1 -0
  153. package/dist/component/providers/spotify/impl.js +131 -0
  154. package/dist/component/providers/spotify/impl.js.map +1 -0
  155. package/dist/component/providers/spotify/mappers.d.ts +18 -0
  156. package/dist/component/providers/spotify/mappers.d.ts.map +1 -0
  157. package/dist/component/providers/spotify/mappers.js +60 -0
  158. package/dist/component/providers/spotify/mappers.js.map +1 -0
  159. package/dist/component/providers/spotify/types.d.ts +97 -0
  160. package/dist/component/providers/spotify/types.d.ts.map +1 -0
  161. package/dist/component/providers/spotify/types.js +7 -0
  162. package/dist/component/providers/spotify/types.js.map +1 -0
  163. package/dist/component/providers/types.d.ts +84 -0
  164. package/dist/component/providers/types.d.ts.map +1 -0
  165. package/dist/component/providers/types.js +10 -0
  166. package/dist/component/providers/types.js.map +1 -0
  167. package/dist/component/providers/wikidata/impl.d.ts +34 -0
  168. package/dist/component/providers/wikidata/impl.d.ts.map +1 -0
  169. package/dist/component/providers/wikidata/impl.js +88 -0
  170. package/dist/component/providers/wikidata/impl.js.map +1 -0
  171. package/dist/component/providers/wikidata/mappers.d.ts +11 -0
  172. package/dist/component/providers/wikidata/mappers.d.ts.map +1 -0
  173. package/dist/component/providers/wikidata/mappers.js +53 -0
  174. package/dist/component/providers/wikidata/mappers.js.map +1 -0
  175. package/dist/component/providers/wikidata/types.d.ts +35 -0
  176. package/dist/component/providers/wikidata/types.d.ts.map +1 -0
  177. package/dist/component/providers/wikidata/types.js +8 -0
  178. package/dist/component/providers/wikidata/types.js.map +1 -0
  179. package/dist/component/queries.d.ts +103 -0
  180. package/dist/component/queries.d.ts.map +1 -0
  181. package/dist/component/queries.js +45 -0
  182. package/dist/component/queries.js.map +1 -0
  183. package/dist/component/schema.d.ts +566 -0
  184. package/dist/component/schema.d.ts.map +1 -0
  185. package/dist/component/schema.js +59 -0
  186. package/dist/component/schema.js.map +1 -0
  187. package/dist/component/sources/actions.d.ts +51 -0
  188. package/dist/component/sources/actions.d.ts.map +1 -0
  189. package/dist/component/sources/actions.js +164 -0
  190. package/dist/component/sources/actions.js.map +1 -0
  191. package/dist/component/sources/mutations.d.ts +25 -0
  192. package/dist/component/sources/mutations.d.ts.map +1 -0
  193. package/dist/component/sources/mutations.js +64 -0
  194. package/dist/component/sources/mutations.js.map +1 -0
  195. package/dist/component/sources/queries.d.ts +19 -0
  196. package/dist/component/sources/queries.d.ts.map +1 -0
  197. package/dist/component/sources/queries.js +20 -0
  198. package/dist/component/sources/queries.js.map +1 -0
  199. package/dist/component/sync/lifecycle.d.ts +46 -0
  200. package/dist/component/sync/lifecycle.d.ts.map +1 -0
  201. package/dist/component/sync/lifecycle.js +87 -0
  202. package/dist/component/sync/lifecycle.js.map +1 -0
  203. package/dist/component/sync/mutations.d.ts +101 -0
  204. package/dist/component/sync/mutations.d.ts.map +1 -0
  205. package/dist/component/sync/mutations.js +132 -0
  206. package/dist/component/sync/mutations.js.map +1 -0
  207. package/dist/component/sync/queries.d.ts +69 -0
  208. package/dist/component/sync/queries.d.ts.map +1 -0
  209. package/dist/component/sync/queries.js +32 -0
  210. package/dist/component/sync/queries.js.map +1 -0
  211. package/dist/component/validators.d.ts +1112 -0
  212. package/dist/component/validators.d.ts.map +1 -0
  213. package/dist/component/validators.js +317 -0
  214. package/dist/component/validators.js.map +1 -0
  215. package/dist/react/index.d.ts +42 -0
  216. package/dist/react/index.d.ts.map +1 -0
  217. package/dist/react/index.js +43 -0
  218. package/dist/react/index.js.map +1 -0
  219. package/dist/shared.d.ts +28 -0
  220. package/dist/shared.d.ts.map +1 -0
  221. package/dist/shared.js +24 -0
  222. package/dist/shared.js.map +1 -0
  223. package/package.json +126 -0
  224. package/src/client/index.ts +558 -0
  225. package/src/client/types.ts +117 -0
  226. package/src/component/_generated/api.ts +141 -0
  227. package/src/component/_generated/component.ts +1814 -0
  228. package/src/component/_generated/dataModel.ts +60 -0
  229. package/src/component/_generated/server.ts +169 -0
  230. package/src/component/actions.ts +156 -0
  231. package/src/component/catalog/browse_order.test.ts +55 -0
  232. package/src/component/catalog/browse_order.ts +43 -0
  233. package/src/component/catalog/field_source_policy.test.ts +47 -0
  234. package/src/component/catalog/field_source_policy.ts +44 -0
  235. package/src/component/catalog/merge.test.ts +187 -0
  236. package/src/component/catalog/merge.ts +134 -0
  237. package/src/component/catalog/mutations.ts +328 -0
  238. package/src/component/catalog/promote.ts +40 -0
  239. package/src/component/catalog/queries.ts +220 -0
  240. package/src/component/config/mutations.ts +29 -0
  241. package/src/component/config/queries.ts +20 -0
  242. package/src/component/convex.config.ts +32 -0
  243. package/src/component/crons.test.ts +8 -0
  244. package/src/component/crons.ts +52 -0
  245. package/src/component/imports/actions.ts +553 -0
  246. package/src/component/imports/dedupe.test.ts +66 -0
  247. package/src/component/imports/dedupe.ts +54 -0
  248. package/src/component/imports/mutations.ts +203 -0
  249. package/src/component/imports/queries.ts +25 -0
  250. package/src/component/imports/state.test.ts +60 -0
  251. package/src/component/imports/state.ts +74 -0
  252. package/src/component/mutations.ts +96 -0
  253. package/src/component/providers/actions.ts +127 -0
  254. package/src/component/providers/apple/impl.test.ts +267 -0
  255. package/src/component/providers/apple/impl.ts +224 -0
  256. package/src/component/providers/apple/jwt.test.ts +153 -0
  257. package/src/component/providers/apple/jwt.ts +99 -0
  258. package/src/component/providers/apple/mappers.test.ts +190 -0
  259. package/src/component/providers/apple/mappers.ts +100 -0
  260. package/src/component/providers/apple/types.ts +77 -0
  261. package/src/component/providers/deezer/impl.test.ts +109 -0
  262. package/src/component/providers/deezer/impl.ts +179 -0
  263. package/src/component/providers/deezer/mappers.test.ts +78 -0
  264. package/src/component/providers/deezer/mappers.ts +72 -0
  265. package/src/component/providers/deezer/types.ts +59 -0
  266. package/src/component/providers/fetch.test.ts +282 -0
  267. package/src/component/providers/fetch.ts +190 -0
  268. package/src/component/providers/musicbrainz/impl.test.ts +79 -0
  269. package/src/component/providers/musicbrainz/impl.ts +132 -0
  270. package/src/component/providers/musicbrainz/mappers.test.ts +75 -0
  271. package/src/component/providers/musicbrainz/mappers.ts +34 -0
  272. package/src/component/providers/musicbrainz/types.ts +20 -0
  273. package/src/component/providers/registry.test.ts +14 -0
  274. package/src/component/providers/registry.ts +48 -0
  275. package/src/component/providers/spotify/client.test.ts +80 -0
  276. package/src/component/providers/spotify/client.ts +57 -0
  277. package/src/component/providers/spotify/impl.test.ts +311 -0
  278. package/src/component/providers/spotify/impl.ts +230 -0
  279. package/src/component/providers/spotify/mappers.test.ts +182 -0
  280. package/src/component/providers/spotify/mappers.ts +81 -0
  281. package/src/component/providers/spotify/types.ts +101 -0
  282. package/src/component/providers/types.ts +95 -0
  283. package/src/component/providers/wikidata/impl.test.ts +81 -0
  284. package/src/component/providers/wikidata/impl.ts +139 -0
  285. package/src/component/providers/wikidata/mappers.test.ts +62 -0
  286. package/src/component/providers/wikidata/mappers.ts +66 -0
  287. package/src/component/providers/wikidata/types.ts +28 -0
  288. package/src/component/queries.ts +51 -0
  289. package/src/component/schema.ts +81 -0
  290. package/src/component/sources/actions.ts +177 -0
  291. package/src/component/sources/mutations.ts +67 -0
  292. package/src/component/sources/queries.ts +21 -0
  293. package/src/component/sync/lifecycle.test.ts +72 -0
  294. package/src/component/sync/lifecycle.ts +121 -0
  295. package/src/component/sync/mutations.ts +154 -0
  296. package/src/component/sync/queries.ts +33 -0
  297. package/src/component/validators.ts +411 -0
  298. package/src/react/index.test.ts +78 -0
  299. package/src/react/index.ts +112 -0
  300. package/src/shared.ts +32 -0
  301. package/src/test.ts +22 -0
@@ -0,0 +1,203 @@
1
+ import { v } from "convex/values";
2
+ import type { Doc, Id } from "../_generated/dataModel.js";
3
+ import {
4
+ type MutationCtx,
5
+ internalMutation,
6
+ mutation,
7
+ } from "../_generated/server.js";
8
+ import {
9
+ artistTracksMode,
10
+ importEntityType,
11
+ importMode,
12
+ importPriority,
13
+ importStatus,
14
+ importTargetMode,
15
+ provider,
16
+ } from "../validators.js";
17
+ import { buildDedupeKey } from "./dedupe.js";
18
+ import { ACTIVE_STATUSES, type ImportStatus, assertTransition } from "./state.js";
19
+
20
+ /** Find an in-flight request with this dedup key, or null. */
21
+ async function findActiveByDedupe(
22
+ ctx: MutationCtx,
23
+ dedupeKey: string,
24
+ ): Promise<Doc<"importRequests"> | null> {
25
+ const matches = await Promise.all(
26
+ ACTIVE_STATUSES.map((status) =>
27
+ ctx.db
28
+ .query("importRequests")
29
+ .withIndex("by_dedupe_status", (q) =>
30
+ q.eq("dedupeKey", dedupeKey).eq("status", status),
31
+ )
32
+ .first(),
33
+ ),
34
+ );
35
+ return matches.find((m) => m !== null) ?? null;
36
+ }
37
+
38
+ /**
39
+ * Create an import request, collapsing onto an existing **active** request with
40
+ * the same dedup key (so a duplicate in-flight import doesn't double-run). A
41
+ * `refresh` never dedups into an `import`, and a `withTracks` import never
42
+ * collapses into a shallow one (both differ in the key). Returns the collapsed
43
+ * request's current `status` so the caller can attach to it instead of re-running
44
+ * the traversal.
45
+ *
46
+ * Concurrency: two simultaneous creates with the same key are serializable under
47
+ * Convex OCC — `findActiveByDedupe` scans the `by_dedupe_status` ranges, so an
48
+ * insert into one of those (now-)read ranges conflicts the other create, which
49
+ * retries, sees the first row, and dedups. No duplicate active request results.
50
+ */
51
+ export const createRequest = mutation({
52
+ args: {
53
+ entityType: importEntityType,
54
+ requestType: importMode,
55
+ targetMode: importTargetMode,
56
+ providerScope: v.string(),
57
+ provider: v.optional(provider),
58
+ providerId: v.optional(v.string()),
59
+ entityId: v.optional(v.string()),
60
+ name: v.optional(v.string()),
61
+ isrc: v.optional(v.string()),
62
+ url: v.optional(v.string()),
63
+ withTracks: v.optional(v.boolean()),
64
+ tracks: v.optional(artistTracksMode),
65
+ withAlbum: v.optional(v.boolean()),
66
+ priority: v.optional(importPriority),
67
+ },
68
+ returns: v.object({
69
+ requestId: v.id("importRequests"),
70
+ deduped: v.boolean(),
71
+ status: importStatus,
72
+ }),
73
+ handler: async (
74
+ ctx,
75
+ args,
76
+ ): Promise<{
77
+ requestId: Id<"importRequests">;
78
+ deduped: boolean;
79
+ status: ImportStatus;
80
+ }> => {
81
+ const dedupeKey = buildDedupeKey(args);
82
+ const active = await findActiveByDedupe(ctx, dedupeKey);
83
+ if (active !== null) {
84
+ return { requestId: active._id, deduped: true, status: active.status };
85
+ }
86
+ const now = Date.now();
87
+ const requestId = await ctx.db.insert("importRequests", {
88
+ entityType: args.entityType,
89
+ requestType: args.requestType,
90
+ targetMode: args.targetMode,
91
+ providerScope: args.providerScope,
92
+ provider: args.provider,
93
+ providerId: args.providerId,
94
+ entityId: args.entityId,
95
+ name: args.name,
96
+ isrc: args.isrc,
97
+ url: args.url,
98
+ withTracks: args.withTracks,
99
+ priority: args.priority ?? "normal",
100
+ status: "queued",
101
+ dedupeKey,
102
+ retryCount: 0,
103
+ requestedAt: now,
104
+ updatedAt: now,
105
+ });
106
+ return { requestId, deduped: false, status: "queued" };
107
+ },
108
+ });
109
+
110
+ /** Optional columns a transition may also write. */
111
+ interface TransitionExtra {
112
+ startedAt?: number;
113
+ finishedAt?: number;
114
+ resolvedArtistId?: Id<"artists">;
115
+ resolvedTrackId?: Id<"tracks">;
116
+ resolvedPlaylistId?: Id<"playlists">;
117
+ resolvedAlbumId?: Id<"albums">;
118
+ resultSummary?: string;
119
+ errorSummary?: string;
120
+ }
121
+
122
+ /**
123
+ * Read-check-set in one transaction: load the request, assert the transition is
124
+ * legal for its CURRENT status (no blind patch-by-id), then apply it. This makes
125
+ * an out-of-order or duplicate drive (e.g. re-running a `completed` request)
126
+ * throw instead of silently corrupting the row, and rejects a missing request.
127
+ */
128
+ async function applyTransition(
129
+ ctx: MutationCtx,
130
+ requestId: Id<"importRequests">,
131
+ to: ImportStatus,
132
+ extra: TransitionExtra = {},
133
+ ): Promise<void> {
134
+ const request = await ctx.db.get("importRequests", requestId);
135
+ if (request === null) {
136
+ throw new Error(`import request not found: ${requestId}`);
137
+ }
138
+ assertTransition(request.status, to);
139
+ await ctx.db.patch("importRequests", requestId, { status: to, updatedAt: Date.now(), ...extra });
140
+ }
141
+
142
+ /** queued → claimed. */
143
+ export const markClaimed = internalMutation({
144
+ args: { requestId: v.id("importRequests") },
145
+ returns: v.null(),
146
+ handler: async (ctx, args) => {
147
+ await applyTransition(ctx, args.requestId, "claimed");
148
+ return null;
149
+ },
150
+ });
151
+
152
+ /** claimed → running. */
153
+ export const markRunning = internalMutation({
154
+ args: { requestId: v.id("importRequests") },
155
+ returns: v.null(),
156
+ handler: async (ctx, args) => {
157
+ await applyTransition(ctx, args.requestId, "running", {
158
+ startedAt: Date.now(),
159
+ });
160
+ return null;
161
+ },
162
+ });
163
+
164
+ /** running → completed, recording what was resolved. */
165
+ export const markCompleted = internalMutation({
166
+ args: {
167
+ requestId: v.id("importRequests"),
168
+ resolvedArtistId: v.optional(v.id("artists")),
169
+ resolvedTrackId: v.optional(v.id("tracks")),
170
+ resolvedPlaylistId: v.optional(v.id("playlists")),
171
+ resolvedAlbumId: v.optional(v.id("albums")),
172
+ resultSummary: v.optional(v.string()),
173
+ },
174
+ returns: v.null(),
175
+ handler: async (ctx, args) => {
176
+ await applyTransition(ctx, args.requestId, "completed", {
177
+ finishedAt: Date.now(),
178
+ resolvedArtistId: args.resolvedArtistId,
179
+ resolvedTrackId: args.resolvedTrackId,
180
+ resolvedPlaylistId: args.resolvedPlaylistId,
181
+ resolvedAlbumId: args.resolvedAlbumId,
182
+ resultSummary: args.resultSummary,
183
+ });
184
+ return null;
185
+ },
186
+ });
187
+
188
+ /** running → failed | stale, recording the error. */
189
+ export const markFailed = internalMutation({
190
+ args: {
191
+ requestId: v.id("importRequests"),
192
+ status: v.union(v.literal("failed"), v.literal("stale")),
193
+ errorSummary: v.string(),
194
+ },
195
+ returns: v.null(),
196
+ handler: async (ctx, args) => {
197
+ await applyTransition(ctx, args.requestId, args.status, {
198
+ finishedAt: Date.now(),
199
+ errorSummary: args.errorSummary,
200
+ });
201
+ return null;
202
+ },
203
+ });
@@ -0,0 +1,25 @@
1
+ import { v } from "convex/values";
2
+ import { query } from "../_generated/server.js";
3
+ import { importRequestDoc, importStatus } from "../validators.js";
4
+
5
+ /** Default page size for a request listing. */
6
+ const DEFAULT_LIST_LIMIT = 50;
7
+
8
+ /** Fetch one import request by id. */
9
+ export const getRequest = query({
10
+ args: { requestId: v.id("importRequests") },
11
+ returns: v.union(v.null(), importRequestDoc),
12
+ handler: async (ctx, args) => await ctx.db.get("importRequests", args.requestId),
13
+ });
14
+
15
+ /** List import requests in a status, newest first. */
16
+ export const listRequests = query({
17
+ args: { status: importStatus, limit: v.optional(v.number()) },
18
+ returns: v.array(importRequestDoc),
19
+ handler: async (ctx, args) =>
20
+ await ctx.db
21
+ .query("importRequests")
22
+ .withIndex("by_status", (q) => q.eq("status", args.status))
23
+ .order("desc")
24
+ .take(args.limit ?? DEFAULT_LIST_LIMIT),
25
+ });
@@ -0,0 +1,60 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import {
3
+ MAX_IMPORT_RETRIES,
4
+ assertTransition,
5
+ canTransition,
6
+ importRetryDelayMs,
7
+ isActive,
8
+ shouldRetry,
9
+ } from "./state.js";
10
+
11
+ describe("isActive", () => {
12
+ it("is true for in-flight statuses", () => {
13
+ expect(isActive("queued")).toBe(true);
14
+ expect(isActive("running")).toBe(true);
15
+ });
16
+ it("is false for terminal statuses", () => {
17
+ expect(isActive("completed")).toBe(false);
18
+ expect(isActive("canceled")).toBe(false);
19
+ });
20
+ });
21
+
22
+ describe("canTransition", () => {
23
+ it("allows legal transitions", () => {
24
+ expect(canTransition("queued", "claimed")).toBe(true);
25
+ expect(canTransition("running", "completed")).toBe(true);
26
+ expect(canTransition("stale", "queued")).toBe(true);
27
+ });
28
+ it("rejects illegal transitions", () => {
29
+ expect(canTransition("queued", "running")).toBe(false);
30
+ expect(canTransition("completed", "queued")).toBe(false);
31
+ });
32
+ });
33
+
34
+ describe("assertTransition", () => {
35
+ it("passes a legal transition", () => {
36
+ expect(() => assertTransition("claimed", "running")).not.toThrow();
37
+ });
38
+ it("throws on an illegal transition", () => {
39
+ expect(() => assertTransition("completed", "running")).toThrow(
40
+ /Invalid import transition: completed -> running/,
41
+ );
42
+ });
43
+ });
44
+
45
+ describe("importRetryDelayMs", () => {
46
+ it("returns 15s, then 60s, then 60s past the end", () => {
47
+ expect(importRetryDelayMs(0)).toBe(15_000);
48
+ expect(importRetryDelayMs(1)).toBe(60_000);
49
+ expect(importRetryDelayMs(2)).toBe(60_000);
50
+ expect(importRetryDelayMs(99)).toBe(60_000);
51
+ });
52
+ });
53
+
54
+ describe("shouldRetry", () => {
55
+ it("retries within budget, stops at the max", () => {
56
+ expect(shouldRetry(0)).toBe(true);
57
+ expect(shouldRetry(MAX_IMPORT_RETRIES - 1)).toBe(true);
58
+ expect(shouldRetry(MAX_IMPORT_RETRIES)).toBe(false);
59
+ });
60
+ });
@@ -0,0 +1,74 @@
1
+ /**
2
+ * The import control-plane state machine (songtrivia's 8-state `music_imports`,
3
+ * generalized). A component-owned control-plane over the `importRequests` table —
4
+ * NOT `@convex-dev/workflow`; the bounded traversal runs inline. Pure transition +
5
+ * retry logic; the mutations enforce it on the request rows via `assertTransition`.
6
+ */
7
+
8
+ /** The lifecycle states of an import request. */
9
+ export const IMPORT_STATUS = {
10
+ queued: "queued",
11
+ claimed: "claimed",
12
+ running: "running",
13
+ retryWaiting: "retry_waiting",
14
+ completed: "completed",
15
+ failed: "failed",
16
+ canceled: "canceled",
17
+ stale: "stale",
18
+ } as const;
19
+
20
+ /** An import request status. */
21
+ export type ImportStatus = (typeof IMPORT_STATUS)[keyof typeof IMPORT_STATUS];
22
+
23
+ /** Statuses an in-flight request occupies — dedup collapses only against these. */
24
+ export const ACTIVE_STATUSES: readonly ImportStatus[] = [
25
+ "queued",
26
+ "claimed",
27
+ "running",
28
+ "retry_waiting",
29
+ ];
30
+
31
+ /** Allowed transitions out of each status. */
32
+ const TRANSITIONS: Record<ImportStatus, readonly ImportStatus[]> = {
33
+ queued: ["claimed", "canceled"],
34
+ claimed: ["running", "canceled", "failed"],
35
+ running: ["completed", "retry_waiting", "failed", "stale", "canceled"],
36
+ retry_waiting: ["claimed", "canceled", "failed", "stale"],
37
+ completed: [],
38
+ failed: ["queued"],
39
+ canceled: [],
40
+ stale: ["queued"],
41
+ };
42
+
43
+ /** Whether a status is one an in-flight request occupies. */
44
+ export function isActive(status: ImportStatus): boolean {
45
+ return ACTIVE_STATUSES.includes(status);
46
+ }
47
+
48
+ /** Whether `from → to` is a legal transition. */
49
+ export function canTransition(from: ImportStatus, to: ImportStatus): boolean {
50
+ return TRANSITIONS[from].includes(to);
51
+ }
52
+
53
+ /** Assert a legal transition, throwing on an illegal one. */
54
+ export function assertTransition(from: ImportStatus, to: ImportStatus): void {
55
+ if (!canTransition(from, to)) {
56
+ throw new Error(`Invalid import transition: ${from} -> ${to}`);
57
+ }
58
+ }
59
+
60
+ /** Per-request retry backoff: `2 × [15s, 60s]` then `stale`. */
61
+ export const IMPORT_RETRY_DELAYS_MS: readonly number[] = [15_000, 60_000];
62
+
63
+ /** Max automatic retries before a request goes `stale`. */
64
+ export const MAX_IMPORT_RETRIES = 2;
65
+
66
+ /** Backoff before the next retry, by prior retry count (last value past the end). */
67
+ export function importRetryDelayMs(retryCount: number): number {
68
+ return IMPORT_RETRY_DELAYS_MS[retryCount] ?? 60_000;
69
+ }
70
+
71
+ /** Whether another retry is within budget. */
72
+ export function shouldRetry(retryCount: number): boolean {
73
+ return retryCount < MAX_IMPORT_RETRIES;
74
+ }
@@ -0,0 +1,96 @@
1
+ import { v } from "convex/values";
2
+ import { mutation } from "./_generated/server.js";
3
+ import type { Doc } from "./_generated/dataModel.js";
4
+ import type { MutationCtx } from "./_generated/server.js";
5
+ import { cacheValue, entityKind, provider } from "./validators.js";
6
+ import { NEVER_EXPIRES } from "../shared.js";
7
+
8
+ async function findEntry(
9
+ ctx: MutationCtx,
10
+ kind: Doc<"cacheEntries">["kind"],
11
+ prov: Doc<"cacheEntries">["provider"],
12
+ externalId: string,
13
+ ): Promise<Doc<"cacheEntries"> | null> {
14
+ return await ctx.db
15
+ .query("cacheEntries")
16
+ .withIndex("by_lookup", (q) =>
17
+ q.eq("kind", kind).eq("provider", prov).eq("externalId", externalId),
18
+ )
19
+ .unique();
20
+ }
21
+
22
+ /**
23
+ * Cache (insert or refresh) one provider's normalized facts for an entity.
24
+ * `ttlMs` omitted means the entry never expires. Returns the entry id.
25
+ */
26
+ export const put = mutation({
27
+ args: {
28
+ kind: entityKind,
29
+ provider,
30
+ externalId: v.string(),
31
+ isrc: v.optional(v.string()),
32
+ value: cacheValue,
33
+ ttlMs: v.optional(v.number()),
34
+ },
35
+ returns: v.id("cacheEntries"),
36
+ handler: async (ctx, args) => {
37
+ const now = Date.now();
38
+ const expiresAt = args.ttlMs === undefined ? NEVER_EXPIRES : now + args.ttlMs;
39
+ const fields = {
40
+ kind: args.kind,
41
+ provider: args.provider,
42
+ externalId: args.externalId,
43
+ isrc: args.isrc,
44
+ value: args.value,
45
+ fetchedAt: now,
46
+ expiresAt,
47
+ };
48
+ const existing = await findEntry(
49
+ ctx,
50
+ args.kind,
51
+ args.provider,
52
+ args.externalId,
53
+ );
54
+ if (existing !== null) {
55
+ await ctx.db.patch("cacheEntries", existing._id, fields);
56
+ return existing._id;
57
+ }
58
+ return await ctx.db.insert("cacheEntries", fields);
59
+ },
60
+ });
61
+
62
+ /** Drop a single cached entry. Returns whether a row was deleted. */
63
+ export const invalidate = mutation({
64
+ args: { kind: entityKind, provider, externalId: v.string() },
65
+ returns: v.boolean(),
66
+ handler: async (ctx, args) => {
67
+ const existing = await findEntry(
68
+ ctx,
69
+ args.kind,
70
+ args.provider,
71
+ args.externalId,
72
+ );
73
+ if (existing === null) {
74
+ return false;
75
+ }
76
+ await ctx.db.delete("cacheEntries", existing._id);
77
+ return true;
78
+ },
79
+ });
80
+
81
+ /** Delete every expired entry. Idempotent; safe to run on a schedule. */
82
+ export const pruneExpired = mutation({
83
+ args: {},
84
+ returns: v.number(),
85
+ handler: async (ctx) => {
86
+ const now = Date.now();
87
+ const expired = await ctx.db
88
+ .query("cacheEntries")
89
+ .withIndex("by_expiry", (q) => q.lte("expiresAt", now))
90
+ .collect();
91
+ for (const entry of expired) {
92
+ await ctx.db.delete("cacheEntries", entry._id);
93
+ }
94
+ return expired.length;
95
+ },
96
+ });
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Provider auth tokens, cached via `@convex-dev/action-cache`. Each token is
3
+ * fetched/signed by an internal action (reading credentials from Convex env
4
+ * vars) and cached by the child component, so read-through actions reuse a token
5
+ * instead of re-authenticating every call. Tokens never leave the component.
6
+ */
7
+
8
+ import { ActionCache } from "@convex-dev/action-cache";
9
+ import { v } from "convex/values";
10
+ import { components, internal } from "../_generated/api.js";
11
+ import { type ActionCtx, internalAction } from "../_generated/server.js";
12
+ import type { Provider } from "../../shared.js";
13
+ import { signAppleDeveloperToken } from "./apple/jwt.js";
14
+ import { createProvider } from "./registry.js";
15
+ import { fetchSpotifyToken } from "./spotify/client.js";
16
+ import type { MusicProvider } from "./types.js";
17
+
18
+ /** Spotify token TTL — Spotify tokens last ~1h; cache 55m. */
19
+ const SPOTIFY_TOKEN_TTL_MS = 55 * 60 * 1000;
20
+ /** Apple developer-token cache TTL — well under the 6-month JWT `exp`. */
21
+ const APPLE_TOKEN_TTL_MS = 150 * 24 * 60 * 60 * 1000;
22
+
23
+ /** Load a provider's configured credentials, or throw if unconfigured. */
24
+ async function loadSecrets(
25
+ ctx: ActionCtx,
26
+ prov: Provider,
27
+ ): Promise<Record<string, string>> {
28
+ const secrets = await ctx.runQuery(
29
+ internal.config.queries.getProviderSecrets,
30
+ { provider: prov },
31
+ );
32
+ if (secrets === null) {
33
+ throw new Error(
34
+ `No credentials configured for provider "${prov}". Call configure() first.`,
35
+ );
36
+ }
37
+ return secrets;
38
+ }
39
+
40
+ /** Read a required credential from a secrets map; throws if unset or empty. */
41
+ function requireSecret(secrets: Record<string, string>, key: string): string {
42
+ const value = secrets[key];
43
+ if (value === undefined || value === "") {
44
+ throw new Error(`Missing required credential: ${key}`);
45
+ }
46
+ return value;
47
+ }
48
+
49
+ /** Fetch a Spotify client-credentials token (cached by action-cache). */
50
+ export const spotifyTokenFetch = internalAction({
51
+ args: {},
52
+ returns: v.string(),
53
+ handler: async (ctx): Promise<string> => {
54
+ const secrets = await loadSecrets(ctx, "spotify");
55
+ const { accessToken } = await fetchSpotifyToken(
56
+ requireSecret(secrets, "clientId"),
57
+ requireSecret(secrets, "clientSecret"),
58
+ );
59
+ return accessToken;
60
+ },
61
+ });
62
+
63
+ /** Sign an Apple Music developer token (cached by action-cache). */
64
+ export const appleTokenSign = internalAction({
65
+ args: {},
66
+ returns: v.string(),
67
+ handler: async (ctx): Promise<string> => {
68
+ const secrets = await loadSecrets(ctx, "apple");
69
+ return signAppleDeveloperToken({
70
+ issuer: requireSecret(secrets, "issuer"),
71
+ keyId: requireSecret(secrets, "keyId"),
72
+ privateKeyPem: requireSecret(secrets, "privateKeyPem"),
73
+ nowSec: Math.floor(Date.now() / 1000),
74
+ });
75
+ },
76
+ });
77
+
78
+ const spotifyTokenCache = new ActionCache(components.actionCache, {
79
+ action: internal.providers.actions.spotifyTokenFetch,
80
+ name: "spotify-token",
81
+ ttl: SPOTIFY_TOKEN_TTL_MS,
82
+ });
83
+
84
+ const appleTokenCache = new ActionCache(components.actionCache, {
85
+ action: internal.providers.actions.appleTokenSign,
86
+ name: "apple-token",
87
+ ttl: APPLE_TOKEN_TTL_MS,
88
+ });
89
+
90
+ /**
91
+ * The ctx `ActionCache.fetch` expects. action-cache 0.3.0 types it with a
92
+ * query-context `runQuery`, which convex >=1.41 widened with a
93
+ * `transactionLimits` option that an action-context `runQuery` does not carry —
94
+ * a cosmetic 3rd-party type seam. The cache only runs its own internal action,
95
+ * so the action ctx is correct at runtime; we bridge the type at the boundary.
96
+ */
97
+ type TokenCacheCtx = Parameters<typeof spotifyTokenCache.fetch>[0];
98
+
99
+ /**
100
+ * Resolve a cached bearer token for a provider, for use as an adapter's
101
+ * `getToken`. No-auth providers return an empty token.
102
+ */
103
+ export async function getProviderToken(
104
+ ctx: ActionCtx,
105
+ prov: Provider,
106
+ ): Promise<string> {
107
+ const cacheCtx = ctx as unknown as TokenCacheCtx;
108
+ if (prov === "spotify") return await spotifyTokenCache.fetch(cacheCtx, {});
109
+ if (prov === "apple") return await appleTokenCache.fetch(cacheCtx, {});
110
+ // No-auth providers (MusicBrainz / Wikidata / Deezer) carry their own headers
111
+ // (e.g. User-Agent) instead of a bearer token.
112
+ return "";
113
+ }
114
+
115
+ /**
116
+ * Build a ready-to-use provider adapter: resolve the (cached) token and wire it
117
+ * as the adapter's `getToken`. The single seam where token resolution meets
118
+ * adapter construction — every read-through + import traversal builds its adapter
119
+ * here, so the token plumbing lives in one place.
120
+ */
121
+ export async function adapterFor(
122
+ ctx: ActionCtx,
123
+ prov: Provider,
124
+ ): Promise<MusicProvider> {
125
+ const token = await getProviderToken(ctx, prov);
126
+ return createProvider(prov, () => Promise.resolve(token));
127
+ }