import-from-disk.test.ts 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. /**
  2. * @vitest-environment node
  3. *
  4. * A backup restic wrote out is a data.json and an uploads folder on disk.
  5. * It goes through the same restore as the uploaded zip: the rows are
  6. * replaced, then the files are moved into the workshop's uploads folder and
  7. * the ones the backup did not bring back go through the file manager.
  8. */
  9. import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
  10. import { tmpdir } from 'node:os'
  11. import path from 'node:path'
  12. import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest'
  13. const root = mkdtempSync(path.join(tmpdir(), 'import-from-disk-'))
  14. const uploads = path.join(root, 'uploads')
  15. const state = vi.hoisted(() => ({
  16. calls: [] as { model: string; method: string; args: any }[],
  17. }))
  18. vi.mock('@/lib/db', () => {
  19. const tx = new Proxy(
  20. {},
  21. {
  22. get: (_target, model: string) => {
  23. // The row locks a restore takes before it reads the portal chat.
  24. if (model === '$queryRaw') return async () => [{ count: 0 }]
  25. return new Proxy(
  26. {},
  27. {
  28. get: (_t, method: string) => async (args: any) => {
  29. state.calls.push({ model, method, args })
  30. if (method === 'findMany') return []
  31. if (method === 'findFirst' || method === 'findUnique') return null
  32. return { count: 0 }
  33. },
  34. }
  35. )
  36. },
  37. }
  38. )
  39. return { db: { $transaction: async (fn: (t: unknown) => unknown) => fn(tx) } }
  40. })
  41. vi.mock('@/lib/files/manager', () => ({ releaseFilesNotRestored: vi.fn(async () => undefined) }))
  42. vi.mock('@/lib/upload-root', () => ({ uploadsRoot: () => uploads }))
  43. import { releaseFilesNotRestored } from '@/lib/files/manager'
  44. import { directoryFileSource, restoreFromDisk } from '@/lib/backup/import'
  45. const actor = { organizationId: 'org1', userId: 'user1' }
  46. function writeBackup(dir: string, backup: unknown, files: Record<string, string> = {}) {
  47. mkdirSync(path.join(dir, 'stage'), { recursive: true })
  48. writeFileSync(path.join(dir, 'stage', 'data.json'), JSON.stringify(backup))
  49. for (const [name, body] of Object.entries(files)) {
  50. const file = path.join(dir, 'files', name)
  51. mkdirSync(path.dirname(file), { recursive: true })
  52. writeFileSync(file, body)
  53. }
  54. }
  55. beforeEach(() => {
  56. state.calls = []
  57. vi.clearAllMocks()
  58. rmSync(root, { recursive: true, force: true })
  59. mkdirSync(root, { recursive: true })
  60. })
  61. afterAll(() => {
  62. rmSync(root, { recursive: true, force: true })
  63. })
  64. describe('restoreFromDisk', () => {
  65. it('replaces the rows and moves the files into the uploads folder', async () => {
  66. const dir = path.join(root, 'restored')
  67. writeBackup(
  68. dir,
  69. { version: 2, data: { settings: [{ id: 's1', key: 'workshop.phone', value: '+47 1' }] } },
  70. {
  71. 'logos/logo.png': 'png bytes',
  72. 'logos/notes.txt': 'kept out of no category',
  73. 'not-a-category/x.bin': 'ignored',
  74. }
  75. )
  76. mkdirSync(path.join(uploads, 'org1', 'logos'), { recursive: true })
  77. writeFileSync(path.join(uploads, 'org1', 'logos', 'old.png'), 'old')
  78. const result = await restoreFromDisk(actor, {
  79. dataFile: path.join(dir, 'stage', 'data.json'),
  80. filesDir: path.join(dir, 'files'),
  81. })
  82. expect(result).toEqual({ redactedSettings: [] })
  83. const created = state.calls.find((c) => c.model === 'appSetting' && c.method === 'createMany')
  84. expect(created?.args.data).toEqual([
  85. { id: 's1', key: 'workshop.phone', value: '+47 1', userId: 'user1', organizationId: 'org1' },
  86. ])
  87. expect(readFileSync(path.join(uploads, 'org1', 'logos', 'logo.png'), 'utf8')).toBe('png bytes')
  88. expect(readFileSync(path.join(uploads, 'org1', 'logos', 'notes.txt'), 'utf8')).toBe(
  89. 'kept out of no category'
  90. )
  91. expect(existsSync(path.join(uploads, 'org1', 'not-a-category'))).toBe(false)
  92. // The file manager decides about what the backup did not bring back.
  93. expect(existsSync(path.join(uploads, 'org1', 'logos', 'old.png'))).toBe(true)
  94. expect(releaseFilesNotRestored).toHaveBeenCalledTimes(1)
  95. expect(vi.mocked(releaseFilesNotRestored).mock.calls[0][0]).toBe('org1')
  96. expect(vi.mocked(releaseFilesNotRestored).mock.calls[0][1]).toBe('logos')
  97. expect([...vi.mocked(releaseFilesNotRestored).mock.calls[0][2]].sort()).toEqual([
  98. 'logo.png',
  99. 'notes.txt',
  100. ])
  101. })
  102. it('restores a data-only snapshot without touching the uploads folder', async () => {
  103. const dir = path.join(root, 'restored')
  104. writeBackup(dir, { version: 2, data: { customers: [] } })
  105. await restoreFromDisk(actor, { dataFile: path.join(dir, 'stage', 'data.json'), filesDir: null })
  106. expect(existsSync(path.join(uploads, 'org1'))).toBe(false)
  107. expect(releaseFilesNotRestored).not.toHaveBeenCalled()
  108. })
  109. it('refuses a file that is not a backup before any row is touched', async () => {
  110. const dir = path.join(root, 'restored')
  111. writeBackup(dir, { version: 3, data: {} })
  112. await expect(
  113. restoreFromDisk(actor, { dataFile: path.join(dir, 'stage', 'data.json'), filesDir: null })
  114. ).rejects.toThrow('Unsupported or missing backup version')
  115. writeBackup(dir, { version: 2 })
  116. await expect(
  117. restoreFromDisk(actor, { dataFile: path.join(dir, 'stage', 'data.json'), filesDir: null })
  118. ).rejects.toThrow('No data found in backup')
  119. expect(state.calls).toEqual([])
  120. })
  121. it('lists one entry per file inside a category folder', async () => {
  122. const dir = path.join(root, 'files')
  123. mkdirSync(path.join(dir, 'logos', 'nested'), { recursive: true })
  124. mkdirSync(path.join(dir, 'service-files'), { recursive: true })
  125. writeFileSync(path.join(dir, 'logos', 'a.png'), 'a')
  126. writeFileSync(path.join(dir, 'service-files', 'b.pdf'), 'b')
  127. writeFileSync(path.join(dir, 'loose.txt'), 'not in a category')
  128. const source = await directoryFileSource(dir)
  129. expect(source.entries.map((e) => `${e.category}/${e.name}`).sort()).toEqual([
  130. 'logos/a.png',
  131. 'service-files/b.pdf',
  132. ])
  133. const target = path.join(root, 'out', 'deep', 'b.pdf')
  134. await source.extract({ category: 'service-files', name: 'b.pdf' }, target)
  135. expect(readFileSync(target, 'utf8')).toBe('b')
  136. })
  137. })