Skip to content

Sync-in · Sovereign platform for file storage, sharing, synchronization, and collaboration.

12.8 KB
Raw Blame
import { Injectable, Logger } from '@nestjs/common'
import crypto from 'node:crypto'

import { toErrorMessage } from '../../../common/errors.js'
import { currentTimeStamp } from '../../../common/shared.js'
import { Cache } from '../../../infrastructure/cache/cache.service.js'
import { UserModel } from '../../users/models/user.model.js'
import { DEPTH, LOCK_DEPTH, LOCK_PREFIX, LOCK_SCOPE } from '../../webdav/constants/webdav.js'
import { CACHE_LOCK_DEFAULT_TTL, CACHE_LOCK_PREFIX } from '../constants/cache.js'
import { FileDBProps } from '../interfaces/file-db-props.interface.js'
import { FileLock, FileLockOptions, LOCK_APP } from '../interfaces/file-lock.interface.js'
import { FileLockProps } from '../interfaces/file-props.interface.js'
import { LockConflict } from '../models/file-lock-error.js'
import { files } from '../schemas/files.schema.js'
import { dirName, fileName } from '../utils/files.js'

@Injectable()
export class FilesLockManager {
  /* Philosophy
  Currently this manager only handles conflicting locks between multiple users, not between clients
  - The locks created from api
      * They do not contain a token key or a davLock property
      * They are exclusive only
      * They must have a depth of 'infinity' (all children) or '0' (root and root members)
  - The locks created from WebDAV or OnlyOffice or CollaboraOnline are stored with a token and a davLock property
      * They must have a depth of 'infinity' (all children) or '0' (root and root members)
      * They can be exclusive (WebDAV) or shared (OnlyOffice, CollaboraOnline)
      * If created with WebDAV, they are stored with a token and a davLock property
      * If created with OnlyOffice, they are stored with no token and a davLock property whose `locktoken` & `lockroot` properties are `null`
      * If created with CollaboraOnline, they are stored with token and a davLock property whose `lockroot` property is `null`
  Cache token key format = `flock|token?:${uuid}|path:${path}|ownerId?:${number}|spaceId?:${number}|...props` => FileLock
  */
  private readonly logger = new Logger(FilesLockManager.name)

  constructor(private readonly cache: Cache) {}

  async create(
    user: UserModel,
    dbFile: FileDBProps,
    app: LOCK_APP,
    depth: LOCK_DEPTH,
    options?: FileLockOptions | null,
    ttl?: number
  ): Promise<[boolean, FileLock]> {
    try {
      await this.checkConflicts(dbFile, depth, { app: app, lockScope: options?.lockScope })
    } catch (e) {
      if (e instanceof LockConflict) {
        return [false, e.lock]
      }
      if (e instanceof Error) throw e
      throw new Error(toErrorMessage(e))
    }
    ttl ??= CACHE_LOCK_DEFAULT_TTL
    const key = `${CACHE_LOCK_PREFIX}|${this.genSuffixKey(dbFile, { depth: depth, token: options?.lockToken })}`
    const expiration = Math.floor(currentTimeStamp() + ttl)
    const lock: FileLock = {
      owner: user.asOwner(),
      dbFilePath: dbFile.path,
      key: key,
      app: app,
      depth: depth,
      expiration: expiration,
      options: options ?? undefined
    }
    this.logger.verbose({ tag: this.create.name, msg: `${key}` })
    await this.cache.set(key, lock, ttl)
    return [true, lock]
  }

  async createOrRefresh(user: UserModel, dbFile: FileDBProps, app: LOCK_APP, depth: LOCK_DEPTH, ttl?: number): Promise<[boolean, FileLock]> {
    // Returns: [created, lock]
    ttl ??= CACHE_LOCK_DEFAULT_TTL
    const locks = await this.getLocksByPath(dbFile)
    // Check the existing lock and refresh it if needed
    if (locks.length > 0) {
      for (const lock of locks) {
        if (lock.owner.id === user.id) {
          // Refresh if more than half of the TTL has passed
          const mustRefresh = lock.expiration - currentTimeStamp() < ttl / 2
          if (mustRefresh) {
            this.refreshLockTimeout(lock, ttl).catch((e: Error) => this.logger.error({ tag: this.createOrRefresh.name, msg: toErrorMessage(e) }))
          }
        } else {
          throw new LockConflict(lock, 'Conflicting lock')
        }
      }
      return [false, locks[0]]
    }
    // Create the lock
    const [ok, lock] = await this.create(user, dbFile, app, depth, null, ttl)
    if (!ok) {
      throw new LockConflict(lock, 'Conflicting lock')
    }
    return [true, lock]
  }

  removeLock(key: string): Promise<boolean> {
    this.logger.verbose({ tag: this.removeLock.name, msg: `${key}` })
    return this.cache.del(key)
  }

  async removeChildLocks(user: UserModel, dbFile: FileDBProps) {
    const ownedLockKeys: string[] = []
    for await (const lock of this.searchChildLocks(dbFile)) {
      if (user.id === lock.owner.id) {
        ownedLockKeys.push(lock.key)
        continue
      }
      const conflict = `cannot remove conflicting child lock : ${dbFile.path} (${user.login}) -> ${lock.dbFilePath} (${lock.owner.login})`
      this.logger.debug({ tag: this.removeChildLocks.name, msg: `${conflict}` })
      throw new LockConflict(lock, conflict)
    }
    for (const key of ownedLockKeys) {
      this.logger.verbose({ tag: this.removeChildLocks.name, msg: `child locks: ${key}` })
      await this.removeLock(key)
    }
  }

  async isLockedWithToken(token: string, dbFilePath: string): Promise<FileLock | null> {
    // check if the url (or any of its parents) is locked by the token
    const lock = await this.getLockByToken(token)
    return lock ? (dbFilePath.startsWith(lock.dbFilePath) ? lock : null) : null
  }

  async browseParentChildLocks(dbFile: FileDBProps, includeRoot = true): Promise<Record<string, FileLock>> {
    // find child locks inside the path
    const childLocks: Record<string, FileLock> = includeRoot ? await this.browseLocks(dbFile) : {}
    const lengthFilter = dbFile.path === '.' ? 1 : dbFile.path.split('/').length + 1
    for await (const lock of this.searchChildLocks(dbFile)) {
      // filter child locks on length
      if (lengthFilter === lock.dbFilePath.split('/').length) {
        // !!! locks with shared scope can have the same file name, in this case we only keep the first entry
        const dbFileName = fileName(lock.dbFilePath)
        if (!(dbFileName in childLocks)) {
          childLocks[fileName(lock.dbFilePath)] = lock
        }
      }
    }
    return childLocks
  }

  async browseLocks(dbFile: FileDBProps): Promise<Record<string, FileLock>> {
    return Object.fromEntries((await this.getLocksByPath(dbFile)).map((l) => [fileName(l.dbFilePath), l]))
  }

  async refreshLockTimeout(lock: FileLock, ttl: number) {
    lock.expiration = currentTimeStamp() + ttl
    this.cache.set(lock.key, lock, ttl).catch((e: Error) => this.logger.error({ tag: this.refreshLockTimeout.name, msg: toErrorMessage(e) }))
  }

  async getLockByToken(token: string): Promise<FileLock | null> {
    const key = await this.searchKeyByToken(token)
    return key ? (await this.cache.get(key)) || null : null
  }

  async getLocksByPath(dbFile: FileDBProps): Promise<FileLock[]> {
    if (dbFile.path !== '.') {
      const props = this.genSuffixKey(dbFile, { ignorePath: true })
      const keys = await this.searchKeysByPath(dbFile.path, props)
      if (keys.length) {
        return (await this.cache.mget(keys)).filter(Boolean)
      }
    }
    return []
  }

  async isPathLocked(dbFile: FileDBProps): Promise<boolean> {
    if (dbFile.path !== '.') return false
    const props = this.genSuffixKey(dbFile, { ignorePath: true })
    return !!(await this.searchKeysByPath(dbFile.path, props)).length
  }

  async checkConflicts(
    dbFile: FileDBProps,
    depth: LOCK_DEPTH,
    options?: { userId?: number; app?: LOCK_APP; lockScope?: LOCK_SCOPE; lockTokens?: string[] }
  ): Promise<void> {
    /* Checks if a file could be modified, created, moved, or deleted
       Throws a `LockConflict` error when there are parent locks (depth: 0) or child locks (depth: infinite) that prevent modification
       Returns on the first conflict (compliant with the RFC 4918)
    */
    for await (const l of this.searchParentLocks(dbFile, { includeRoot: true, depth: DEPTH.INFINITY })) {
      if (options?.lockScope && options?.lockScope === LOCK_SCOPE.SHARED && l.options?.lockScope === LOCK_SCOPE.SHARED && options?.app === l.app) {
        // Only compatible with shared locks (with the same owner and the same application)
        continue
      }
      if (
        options?.userId === l.owner.id &&
        (!l.options || (options?.lockTokens?.length && options.lockTokens.indexOf(l.options.lockToken as string) > -1))
      ) {
        // Owner owns this lock (no davLock if the lock was created from api)
        continue
      }
      const conflict = `conflicting parent lock : ${dbFile.path} -> ${l.dbFilePath} (${l.owner.login})`
      this.logger.debug({ tag: this.checkConflicts.name, msg: `${conflict}` })
      throw new LockConflict(l, conflict)
    }
    if (depth === DEPTH.INFINITY) {
      for await (const l of this.searchChildLocks(dbFile)) {
        if (
          options?.userId === l.owner.id &&
          (!l.options || (options?.lockTokens?.length && options.lockTokens.indexOf(l.options.lockToken as string) > -1))
        ) {
          // Owner owns this lock (no davLock if the lock was created from api)
          continue
        }
        const conflict = `conflicting child lock : ${dbFile.path} -> ${l.dbFilePath} (${l.owner.login})`
        this.logger.debug({ tag: this.checkConflicts.name, msg: `${conflict}` })
        throw new LockConflict(l, conflict)
      }
    }
  }

  async *searchChildLocks(dbFile: FileDBProps) {
    const props = this.genSuffixKey(dbFile, { ignorePath: true })
    const path = dbFile.path === '.' ? '*' : `${dbFile.path}/*`
    this.logger.verbose({ tag: this.searchChildLocks.name, msg: `${path} (${props})` })
    const keys = await this.searchKeysByPath(path, props)
    if (keys.length) {
      for (const l of (await this.cache.mget(keys)).filter(Boolean) as FileLock[]) {
        this.logger.verbose({ tag: this.searchChildLocks.name, msg: `-> ${l.dbFilePath} (owner: ${l.owner.login})` })
        yield l
      }
    }
  }

  convertLockToFileLockProps(lock: FileLock): FileLockProps
  convertLockToFileLockProps(lock: null): null
  convertLockToFileLockProps(lock: FileLock | null): FileLockProps | null {
    if (!lock) return null
    return {
      owner: lock.owner,
      app: lock?.app,
      info: lock?.options?.lockInfo,
      isExclusive: lock?.options?.lockScope ? lock?.options?.lockScope === LOCK_SCOPE.EXCLUSIVE : true
    }
  }

  genDAVToken(): string {
    return `${LOCK_PREFIX}${crypto.randomUUID()}`
  }

  private async *searchParentLocks(dbFile: FileDBProps, options: { includeRoot?: boolean; depth?: LOCK_DEPTH } = {}): AsyncGenerator<FileLock> {
    const props = this.genSuffixKey(dbFile, { ignorePath: true })
    let path = dbFile.path
    const parentPath = dirName(path)
    this.logger.verbose({ tag: this.searchParentLocks.name, msg: `(including root : ${options.includeRoot}) : ${path} (${props})` })
    if (!options.includeRoot) {
      path = dirName(path)
    }
    while (path !== '.') {
      // Even if the depth is "infinite", the path and the parent path could be locked with depth "0"
      const depth = options.depth && (dbFile.path === path || parentPath === path) ? null : options.depth
      const keys = await this.searchKeysByPath(path, props, depth)
      if (keys.length) {
        for (const l of (await this.cache.mget(keys)).filter(Boolean) as FileLock[]) {
          this.logger.verbose({ tag: this.searchParentLocks.name, msg: `-> ${l.dbFilePath}` })
          yield l
        }
      }
      path = dirName(path)
    }
  }

  private async searchKeyByToken(token: string): Promise<string | null> {
    const keys = await this.cache.keys(`${CACHE_LOCK_PREFIX}|token:${token}|*`)
    if (!keys.length) {
      return null
    } else if (keys.length > 1) {
      this.logger.warn({ tag: this.searchKeyByToken.name, msg: `Several keys found for token : ${token} => ${JSON.stringify(keys)}` })
    }
    return keys[0]
  }

  private searchKeysByPath(path: string, props = '*', depth?: LOCK_DEPTH | null): Promise<string[]> {
    return this.cache.keys(`${CACHE_LOCK_PREFIX}*${depth ? `|depth:${depth}` : ''}|path:${path}|${props}`)
  }

  private genSuffixKey(dbFile: FileDBProps, options: { ignorePath?: boolean; depth?: LOCK_DEPTH; token?: string | null } = {}): string {
    // return -> `depth:infinity|path:code/sync-in|spaceId:1` | `token:xxx|depth:0|path:code/sync-in.ts|ownerId:1`
    // ignorePath -> `spaceId:1`
    const suffixes = []
    for (const k of (Object.keys(dbFile) as (keyof FileDBProps)[]).filter((k) => k !== files.inTrash.name && dbFile[k] !== null).sort()) {
      if (k === files.path.name) {
        if (options.ignorePath) {
          continue
        }
        suffixes.unshift(`${k}:${dbFile[k]}`)
      } else {
        suffixes.push(`${k}:${dbFile[k]}`)
      }
    }
    if (options.depth) suffixes.unshift(`depth:${options.depth}`)
    if (options.token) suffixes.unshift(`token:${options.token}`)
    return suffixes.join('|')
  }
}