file_map.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. // @ts-check
  2. 'use strict'
  3. const _ = require('lodash')
  4. const assert = require('check-types').assert
  5. const OError = require('@overleaf/o-error')
  6. const pMap = require('p-map')
  7. const File = require('./file')
  8. const safePathname = require('./safe_pathname')
  9. /**
  10. * @import { RawFile, RawFileMap } from './types'
  11. *
  12. * @typedef {Record<String, File | null>} FileMapData
  13. */
  14. class PathnameError extends OError {}
  15. class NonUniquePathnameError extends PathnameError {
  16. /**
  17. * @param {string[]} pathnames
  18. */
  19. constructor(pathnames) {
  20. super('pathnames are not unique', { pathnames })
  21. this.pathnames = pathnames
  22. }
  23. }
  24. class BadPathnameError extends PathnameError {
  25. /**
  26. * @param {string} pathname
  27. * @param {string} reason
  28. */
  29. constructor(pathname, reason) {
  30. if (pathname.length > 10) {
  31. pathname = pathname.slice(0, 5) + '...' + pathname.slice(-5)
  32. }
  33. super('invalid pathname', { reason, pathname })
  34. this.pathname = pathname
  35. }
  36. }
  37. class PathnameConflictError extends PathnameError {
  38. /**
  39. * @param {string} pathname
  40. */
  41. constructor(pathname) {
  42. super('pathname conflicts with another file', { pathname })
  43. this.pathname = pathname
  44. }
  45. }
  46. class FileNotFoundError extends PathnameError {
  47. /**
  48. * @param {string} pathname
  49. */
  50. constructor(pathname) {
  51. super('file does not exist', { pathname })
  52. this.pathname = pathname
  53. }
  54. }
  55. /**
  56. * A set of {@link File}s. Several properties are enforced on the pathnames:
  57. *
  58. * 1. File names and paths are case sensitive and can differ by case alone. This
  59. * is consistent with most Linux file systems, but it is not consistent with
  60. * Windows or OS X. Ideally, we would be case-preserving and case insensitive,
  61. * like they are. And we used to be, but it caused too many incompatibilities
  62. * with the old system, which was case sensitive. See
  63. * https://github.com/overleaf/overleaf-ot-prototype/blob/
  64. * 19ed046c09f5a4d14fa12b3ea813ce0d977af88a/editor/core/lib/file_map.js
  65. * for an implementation of this map with those properties.
  66. *
  67. * 2. Uniqueness: No two pathnames are the same.
  68. *
  69. * 3. No type conflicts: A pathname cannot refer to both a file and a directory
  70. * within the same snapshot. That is, you can't have pathnames `a` and `a/b` in
  71. * the same file map; {@see FileMap#wouldConflict}.
  72. */
  73. class FileMap {
  74. static PathnameError = PathnameError
  75. static NonUniquePathnameError = NonUniquePathnameError
  76. static BadPathnameError = BadPathnameError
  77. static PathnameConflictError = PathnameConflictError
  78. static FileNotFoundError = FileNotFoundError
  79. /**
  80. * @param {Record<String, File | null>} files
  81. */
  82. constructor(files) {
  83. // create bare object for use as Map
  84. // http://ryanmorr.com/true-hash-maps-in-javascript/
  85. /** @type FileMapData */
  86. this.files = Object.create(null)
  87. _.assign(this.files, files)
  88. checkPathnamesAreUnique(this.files)
  89. checkPathnamesDoNotConflict(this)
  90. }
  91. /**
  92. * @param {RawFileMap} raw
  93. * @returns {FileMap}
  94. */
  95. static fromRaw(raw) {
  96. assert.object(raw, 'bad raw files')
  97. return new FileMap(_.mapValues(raw, File.fromRaw))
  98. }
  99. /**
  100. * Convert to raw object for serialization.
  101. *
  102. * @return {RawFileMap}
  103. */
  104. toRaw() {
  105. /**
  106. * @param {File} file
  107. * @return {RawFile}
  108. */
  109. function fileToRaw(file) {
  110. return file.toRaw()
  111. }
  112. // TODO(das7pad): refine types to enforce no nulls in FileMapData
  113. // @ts-ignore
  114. return _.mapValues(this.files, fileToRaw)
  115. }
  116. /**
  117. * Create the given file.
  118. *
  119. * @param {string} pathname
  120. * @param {File} file
  121. */
  122. addFile(pathname, file) {
  123. checkPathname(pathname)
  124. assert.object(file, 'bad file')
  125. // TODO(das7pad): make ignoredPathname argument fully optional
  126. // @ts-ignore
  127. checkNewPathnameDoesNotConflict(this, pathname)
  128. addFile(this.files, pathname, file)
  129. }
  130. /**
  131. * Remove the given file.
  132. *
  133. * @param {string} pathname
  134. */
  135. removeFile(pathname) {
  136. checkPathname(pathname)
  137. const key = findPathnameKey(this.files, pathname)
  138. if (!key) {
  139. throw new FileMap.FileNotFoundError(pathname)
  140. }
  141. delete this.files[key]
  142. }
  143. /**
  144. * Move or remove a file. If the origin file does not exist, or if the old
  145. * and new paths are identical, this has no effect.
  146. *
  147. * @param {string} pathname
  148. * @param {string} newPathname if a blank string, {@link FileMap#removeFile}
  149. */
  150. moveFile(pathname, newPathname) {
  151. if (pathname === newPathname) return
  152. if (newPathname === '') return this.removeFile(pathname)
  153. checkPathname(pathname)
  154. checkPathname(newPathname)
  155. checkNewPathnameDoesNotConflict(this, newPathname, pathname)
  156. const key = findPathnameKey(this.files, pathname)
  157. if (!key) {
  158. throw new FileMap.FileNotFoundError(pathname)
  159. }
  160. const file = this.files[key]
  161. delete this.files[key]
  162. addFile(this.files, newPathname, file)
  163. }
  164. /**
  165. * The number of files in the file map.
  166. *
  167. * @return {number}
  168. */
  169. countFiles() {
  170. return _.size(this.files)
  171. }
  172. /**
  173. * Get a file by its pathname.
  174. *
  175. * @param {string} pathname
  176. * @return {File | null | undefined}
  177. */
  178. getFile(pathname) {
  179. const key = findPathnameKey(this.files, pathname)
  180. if (key) return this.files[key]
  181. }
  182. /**
  183. * Whether the given pathname conflicts with any file in the map.
  184. *
  185. * Paths conflict in type if one path is a strict prefix of the other path. For
  186. * example, 'a/b' conflicts with 'a', because in the former case 'a' is a
  187. * folder, but in the latter case it is a file. Similarly, the pathname 'a/b/c'
  188. * conflicts with 'a' and 'a/b', but it does not conflict with 'a/b/c', 'a/x',
  189. * or 'a/b/x'. (In our case, identical paths don't conflict, because AddFile
  190. * and MoveFile overwrite existing files.)
  191. *
  192. * @param {string} pathname
  193. * @param {string?} ignoredPathname pretend this pathname does not exist
  194. */
  195. wouldConflict(pathname, ignoredPathname) {
  196. checkPathname(pathname)
  197. assert.maybe.string(ignoredPathname)
  198. const pathnames = this.getPathnames()
  199. const dirname = pathname + '/'
  200. // Check the filemap to see whether the supplied pathname is a
  201. // parent of any entry, or any entry is a parent of the pathname.
  202. for (let i = 0; i < pathnames.length; i++) {
  203. // First check if pathname is a strict prefix of pathnames[i] (and that
  204. // pathnames[i] is not ignored)
  205. if (
  206. pathnames[i].startsWith(dirname) &&
  207. !pathnamesEqual(pathnames[i], ignoredPathname)
  208. ) {
  209. return true
  210. }
  211. // Now make the reverse check, whether pathnames[i] is a strict prefix of
  212. // pathname. To avoid expensive string concatenation on each pathname we
  213. // first perform a partial check with a.startsWith(b), and then do the
  214. // full check for a subsequent '/' if this passes. This saves about 25%
  215. // of the runtime. Again only return a conflict if pathnames[i] is not
  216. // ignored.
  217. if (
  218. pathname.startsWith(pathnames[i]) &&
  219. pathname.length > pathnames[i].length &&
  220. pathname[pathnames[i].length] === '/' &&
  221. !pathnamesEqual(pathnames[i], ignoredPathname)
  222. ) {
  223. return true
  224. }
  225. }
  226. // No conflicts - after excluding ignoredPathname, there were no entries
  227. // which were a strict prefix of pathname, and pathname was not a strict
  228. // prefix of any entry.
  229. return false
  230. }
  231. /** @see Snapshot#getFilePathnames */
  232. getPathnames() {
  233. return _.keys(this.files)
  234. }
  235. /**
  236. * Map the files in this map to new values.
  237. * @template T
  238. * @param {(file: File | null, path: string) => T} iteratee
  239. * @return {Record<String, T>}
  240. */
  241. map(iteratee) {
  242. return _.mapValues(this.files, iteratee)
  243. }
  244. /**
  245. * Map the files in this map to new values asynchronously, with an optional
  246. * limit on concurrency.
  247. * @template T
  248. * @param {(file: File | null | undefined, path: string, pathnames: string[]) => T} iteratee
  249. * @param {number} [concurrency]
  250. * @return {Promise<Record<String, T>>}
  251. */
  252. async mapAsync(iteratee, concurrency) {
  253. assert.maybe.number(concurrency, 'bad concurrency')
  254. const pathnames = this.getPathnames()
  255. const files = await pMap(
  256. pathnames,
  257. file => {
  258. return iteratee(this.getFile(file), file, pathnames)
  259. },
  260. { concurrency: concurrency || 1 }
  261. )
  262. return _.zipObject(pathnames, files)
  263. }
  264. }
  265. /**
  266. * @param {string} pathname0
  267. * @param {string?} pathname1
  268. * @returns {boolean}
  269. */
  270. function pathnamesEqual(pathname0, pathname1) {
  271. return pathname0 === pathname1
  272. }
  273. /**
  274. * @param {FileMapData} files
  275. * @returns {boolean}
  276. */
  277. function pathnamesAreUnique(files) {
  278. const keys = _.keys(files)
  279. return _.uniqWith(keys, pathnamesEqual).length === keys.length
  280. }
  281. /**
  282. * @param {FileMapData} files
  283. */
  284. function checkPathnamesAreUnique(files) {
  285. if (pathnamesAreUnique(files)) return
  286. throw new FileMap.NonUniquePathnameError(_.keys(files))
  287. }
  288. /**
  289. * @param {string} pathname
  290. */
  291. function checkPathname(pathname) {
  292. assert.nonEmptyString(pathname, 'bad pathname')
  293. const [isClean, reason] = safePathname.isCleanDebug(pathname)
  294. if (isClean) return
  295. throw new FileMap.BadPathnameError(pathname, reason)
  296. }
  297. /**
  298. * @param {FileMap} fileMap
  299. * @param {string} pathname
  300. * @param {string?} ignoredPathname
  301. */
  302. function checkNewPathnameDoesNotConflict(fileMap, pathname, ignoredPathname) {
  303. if (fileMap.wouldConflict(pathname, ignoredPathname)) {
  304. throw new FileMap.PathnameConflictError(pathname)
  305. }
  306. }
  307. /**
  308. * @param {FileMap} fileMap
  309. */
  310. function checkPathnamesDoNotConflict(fileMap) {
  311. const pathnames = fileMap.getPathnames()
  312. // check pathnames for validity first
  313. pathnames.forEach(checkPathname)
  314. // convert pathnames to candidate directory names
  315. const dirnames = []
  316. for (let i = 0; i < pathnames.length; i++) {
  317. dirnames[i] = pathnames[i] + '/'
  318. }
  319. // sort in lexical order and check if one directory contains another
  320. dirnames.sort()
  321. for (let i = 0; i < dirnames.length - 1; i++) {
  322. if (dirnames[i + 1].startsWith(dirnames[i])) {
  323. // strip trailing slash to get original pathname
  324. const conflictPathname = dirnames[i + 1].substr(0, -1)
  325. throw new FileMap.PathnameConflictError(conflictPathname)
  326. }
  327. }
  328. }
  329. /**
  330. * This function is somewhat vestigial: it was used when this map used
  331. * case-insensitive pathname comparison. We could probably simplify some of the
  332. * logic in the callers, but in the hope that we will one day return to
  333. * case-insensitive semantics, we've just left things as-is for now.
  334. *
  335. * TODO(das7pad): In a followup, inline this function and make types stricter.
  336. *
  337. * @param {FileMapData} files
  338. * @param {string} pathname
  339. * @returns {string | undefined}
  340. */
  341. function findPathnameKey(files, pathname) {
  342. // we can check for the key without worrying about properties
  343. // in the prototype because we are now using a bare object/
  344. if (pathname in files) return pathname
  345. }
  346. /**
  347. * @param {FileMapData} files
  348. * @param {string} pathname
  349. * @param {File?} file
  350. */
  351. function addFile(files, pathname, file) {
  352. const key = findPathnameKey(files, pathname)
  353. if (key) delete files[key]
  354. files[pathname] = file
  355. }
  356. module.exports = FileMap