Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

offline.ts

109 lines3.8 KB

1import { convexToJson, jsonToConvex } from 'convex/values'
2import { NonRetriableError } from '@tanstack/offline-transactions'
3import type { JSONValue, Value } from 'convex/values'
4import type {
5 MutationValueCodec,
6 OfflineConfig,
7} from '@tanstack/offline-transactions'
8import type { ConvexClient } from 'convex/browser'
9import type { ConvexReactClient } from 'convex/react'
10import type { FunctionArgs, FunctionReference } from 'convex/server'
11import type { ConvexCollectionUtils } from './options'
12​
13type OfflineMutation = OfflineConfig[`mutationFns`][string]
14type OfflineParams = Parameters<OfflineMutation>[0]
15​
16/**
17 * Use as a named mutationFn in startOfflineExecutor. The existing outbox owns
18 * durability, restoration, leadership and retries. The server mutation must
19 * atomically deduplicate idempotencyKey with its writes.
20 */
21export function convexOfflineMutation<
22 TMutation extends FunctionReference<`mutation`>,
23>(
24 config: {
25 client: Pick<ConvexClient, `mutation`> | Pick<ConvexReactClient, `mutation`>
26 mutation: TMutation
27 getArgs: (
28 params: OfflineParams,
29 ) => Omit<FunctionArgs<TMutation>, `idempotencyKey`>
30 collections: ReadonlyArray<{
31 utils: Pick<ConvexCollectionUtils, `awaitSync`>
32 }>
33 } & (FunctionArgs<TMutation> extends { idempotencyKey: string }
34 ? unknown
35 : never),
36): OfflineMutation {
37 return async (params) => {
38 try {
39 const args = {
40 ...config.getArgs(params),
41 idempotencyKey: params.idempotencyKey,
42 } as FunctionArgs<TMutation>
43 await config.client.mutation(config.mutation, args)
44 } catch (cause) {
45 // The WebSocket clients retry transport interruptions themselves. A
46 // rejected mutation has a server/function or client configuration error.
47 const error = new NonRetriableError(
48 cause instanceof Error ? cause.message : String(cause),
49 )
50 throw error
51 }
52 await Promise.all(
53 config.collections.map((collection) => collection.utils.awaitSync()),
54 )
55 }
57​
58/** Lossless, opt-in outbox encoding for Convex values and removed fields. */
59export const convexMutationCodec: MutationValueCodec = {
60 id: `tanstack-convex-values/1`,
61 encode: (value) => JSON.stringify(encodeValue(value)),
62 decode: (value) => decodeValue(JSON.parse(value)),
64​
65function encodeValue(value: unknown): unknown {
66 if (value === undefined) return [`undefined`]
67 if (Array.isArray(value)) return [`array`, value.map(encodeValue)]
68 if (
69 value !== null &&
70 typeof value === `object` &&
71 !(value instanceof ArrayBuffer)
72 ) {
73 const prototype = Object.getPrototypeOf(value)
74 if (prototype !== Object.prototype && prototype !== null)
75 throw new TypeError(
76 `Convex mutation codecs support plain objects and Convex scalar values`,
77 )
78 return [
79 `object`,
80 Object.entries(value).map(([key, field]) => [key, encodeValue(field)]),
81 ]
82 }
83 return [`scalar`, convexToJson(value as Value)]
85​
86function decodeValue(value: unknown): unknown {
87 if (!Array.isArray(value))
88 throw new TypeError(`Invalid Convex mutation codec record`)
89 if (value[0] === `undefined` && value.length === 1) return undefined
90 if (value.length !== 2)
91 throw new TypeError(`Invalid Convex mutation codec record`)
92 if (value[0] === `scalar`) return jsonToConvex(value[1] as JSONValue)
93 if (!Array.isArray(value[1]))
94 throw new TypeError(`Invalid Convex mutation codec container`)
95 if (value[0] === `array`) return value[1].map(decodeValue)
96 if (value[0] === `object`)
97 return Object.fromEntries(
98 value[1].map((entry: unknown) => {
99 if (
100 !Array.isArray(entry) ||
101 entry.length !== 2 ||
102 typeof entry[0] !== `string`
103 )
104 throw new TypeError(`Invalid Convex mutation codec field`)
105 return [entry[0], decodeValue(entry[1])]
106 }),
107 )
108 throw new TypeError(`Invalid Convex mutation codec tag`)