-
Notifications
You must be signed in to change notification settings - Fork 2k
/
migrate.ts
290 lines (259 loc) · 8.45 KB
/
migrate.ts
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
import { assert, objectMapEntries } from '@tldraw/utils'
import { UnknownRecord } from './BaseRecord'
import { SerializedStore } from './Store'
let didWarn = false
/**
* @public
* @deprecated use `createShapePropsMigrationSequence` instead. See [the docs](https://tldraw.dev/docs/persistence#Updating-legacy-shape-migrations-defineMigrations) for how to migrate.
*/
export function defineMigrations(opts: {
firstVersion?: number
currentVersion?: number
migrators?: Record<number, LegacyMigration>
subTypeKey?: string
subTypeMigrations?: Record<string, LegacyBaseMigrationsInfo>
}): LegacyMigrations {
const { currentVersion, firstVersion, migrators = {}, subTypeKey, subTypeMigrations } = opts
if (!didWarn) {
console.warn(
`The 'defineMigrations' function is deprecated and will be removed in a future release. Use the new migrations API instead. See the migration guide for more info: https://tldraw.dev/docs/persistence#Updating-legacy-shape-migrations-defineMigrations`
)
didWarn = true
}
// Some basic guards against impossible version combinations, some of which will be caught by TypeScript
if (typeof currentVersion === 'number' && typeof firstVersion === 'number') {
if ((currentVersion as number) === (firstVersion as number)) {
throw Error(`Current version is equal to initial version.`)
} else if (currentVersion < firstVersion) {
throw Error(`Current version is lower than initial version.`)
}
}
return {
firstVersion: (firstVersion as number) ?? 0, // defaults
currentVersion: (currentVersion as number) ?? 0, // defaults
migrators,
subTypeKey,
subTypeMigrations,
}
}
function squashDependsOn(sequence: Array<Migration | StandaloneDependsOn>): Migration[] {
const result: Migration[] = []
for (let i = sequence.length - 1; i >= 0; i--) {
const elem = sequence[i]
if (!('id' in elem)) {
const dependsOn = elem.dependsOn
const prev = result[0]
if (prev) {
result[0] = {
...prev,
dependsOn: dependsOn.concat(prev.dependsOn ?? []),
}
}
} else {
result.unshift(elem)
}
}
return result
}
/**
* Creates a migration sequence.
* See the [migration guide](https://tldraw.dev/docs/persistence#Migrations) for more info on how to use this API.
* @public
*/
export function createMigrationSequence({
sequence,
sequenceId,
retroactive = true,
}: {
sequenceId: string
retroactive?: boolean
sequence: Array<Migration | StandaloneDependsOn>
}): MigrationSequence {
const migrations: MigrationSequence = {
sequenceId,
retroactive,
sequence: squashDependsOn(sequence),
}
validateMigrations(migrations)
return migrations
}
/**
* Creates a named set of migration ids given a named set of version numbers and a sequence id.
*
* See the [migration guide](https://tldraw.dev/docs/persistence#Migrations) for more info on how to use this API.
* @public
* @public
*/
export function createMigrationIds<
const ID extends string,
const Versions extends Record<string, number>,
>(sequenceId: ID, versions: Versions): { [K in keyof Versions]: `${ID}/${Versions[K]}` } {
return Object.fromEntries(
objectMapEntries(versions).map(([key, version]) => [key, `${sequenceId}/${version}`] as const)
) as any
}
/** @internal */
export function createRecordMigrationSequence(opts: {
recordType: string
filter?: (record: UnknownRecord) => boolean
retroactive?: boolean
sequenceId: string
sequence: Omit<Extract<Migration, { scope: 'record' }>, 'scope'>[]
}): MigrationSequence {
const sequenceId = opts.sequenceId
return createMigrationSequence({
sequenceId,
retroactive: opts.retroactive ?? true,
sequence: opts.sequence.map((m) =>
'id' in m
? {
...m,
scope: 'record',
filter: (r: UnknownRecord) =>
r.typeName === opts.recordType &&
(m.filter?.(r) ?? true) &&
(opts.filter?.(r) ?? true),
}
: m
),
})
}
/** @public */
export interface LegacyMigration<Before = any, After = any> {
up: (oldState: Before) => After
down: (newState: After) => Before
}
/** @public */
export type MigrationId = `${string}/${number}`
/** @public */
export interface StandaloneDependsOn {
readonly dependsOn: readonly MigrationId[]
}
/** @public */
export type Migration = {
readonly id: MigrationId
readonly dependsOn?: readonly MigrationId[] | undefined
} & (
| {
readonly scope: 'record'
readonly filter?: (record: UnknownRecord) => boolean
readonly up: (oldState: UnknownRecord) => void | UnknownRecord
readonly down?: (newState: UnknownRecord) => void | UnknownRecord
}
| {
readonly scope: 'store'
readonly up: (
oldState: SerializedStore<UnknownRecord>
) => void | SerializedStore<UnknownRecord>
readonly down?: (
newState: SerializedStore<UnknownRecord>
) => void | SerializedStore<UnknownRecord>
}
)
interface LegacyBaseMigrationsInfo {
firstVersion: number
currentVersion: number
migrators: { [version: number]: LegacyMigration }
}
/** @public */
export interface LegacyMigrations extends LegacyBaseMigrationsInfo {
subTypeKey?: string
subTypeMigrations?: Record<string, LegacyBaseMigrationsInfo>
}
/** @public */
export interface MigrationSequence {
sequenceId: string
/**
* retroactive should be true if the migrations should be applied to snapshots that were created before
* this migration sequence was added to the schema.
*
* In general:
*
* - retroactive should be true when app developers create their own new migration sequences.
* - retroactive should be false when library developers ship a migration sequence. When you install a library for the first time, any migrations that were added in the library before that point should generally _not_ be applied to your existing data.
*/
retroactive: boolean
sequence: Migration[]
}
export function sortMigrations(migrations: Migration[]): Migration[] {
// we do a topological sort using dependsOn and implicit dependencies between migrations in the same sequence
const byId = new Map(migrations.map((m) => [m.id, m]))
const isProcessing = new Set<MigrationId>()
const result: Migration[] = []
function process(m: Migration) {
assert(!isProcessing.has(m.id), `Circular dependency in migrations: ${m.id}`)
isProcessing.add(m.id)
const { version, sequenceId } = parseMigrationId(m.id)
const parent = byId.get(`${sequenceId}/${version - 1}`)
if (parent) {
process(parent)
}
if (m.dependsOn) {
for (const dep of m.dependsOn) {
const depMigration = byId.get(dep)
if (depMigration) {
process(depMigration)
}
}
}
byId.delete(m.id)
result.push(m)
}
for (const m of byId.values()) {
process(m)
}
return result
}
/** @internal */
export function parseMigrationId(id: MigrationId): { sequenceId: string; version: number } {
const [sequenceId, version] = id.split('/')
return { sequenceId, version: parseInt(version) }
}
function validateMigrationId(id: string, expectedSequenceId?: string) {
if (expectedSequenceId) {
assert(
id.startsWith(expectedSequenceId + '/'),
`Every migration in sequence '${expectedSequenceId}' must have an id starting with '${expectedSequenceId}/'. Got invalid id: '${id}'`
)
}
assert(id.match(/^(.*?)\/(0|[1-9]\d*)$/), `Invalid migration id: '${id}'`)
}
export function validateMigrations(migrations: MigrationSequence) {
assert(
!migrations.sequenceId.includes('/'),
`sequenceId cannot contain a '/', got ${migrations.sequenceId}`
)
assert(migrations.sequenceId.length, 'sequenceId must be a non-empty string')
if (migrations.sequence.length === 0) {
return
}
validateMigrationId(migrations.sequence[0].id, migrations.sequenceId)
let n = parseMigrationId(migrations.sequence[0].id).version
assert(
n === 1,
`Expected the first migrationId to be '${migrations.sequenceId}/1' but got '${migrations.sequence[0].id}'`
)
for (let i = 1; i < migrations.sequence.length; i++) {
const id = migrations.sequence[i].id
validateMigrationId(id, migrations.sequenceId)
const m = parseMigrationId(id).version
assert(
m === n + 1,
`Migration id numbers must increase in increments of 1, expected ${migrations.sequenceId}/${n + 1} but got '${migrations.sequence[i].id}'`
)
n = m
}
}
/** @public */
export type MigrationResult<T> =
| { type: 'success'; value: T }
| { type: 'error'; reason: MigrationFailureReason }
/** @public */
export enum MigrationFailureReason {
IncompatibleSubtype = 'incompatible-subtype',
UnknownType = 'unknown-type',
TargetVersionTooNew = 'target-version-too-new',
TargetVersionTooOld = 'target-version-too-old',
MigrationError = 'migration-error',
UnrecognizedSubtype = 'unrecognized-subtype',
}