ModelDownloader.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. // Copyright 2021 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. import Foundation
  15. import FirebaseCore
  16. import FirebaseInstallations
  17. /// Possible errors with model downloading.
  18. public enum DownloadError: Error, Equatable {
  19. /// No model with this name found on server.
  20. case notFound
  21. /// Caller does not have necessary permissions for this operation.
  22. case permissionDenied
  23. /// Conditions not met to perform download.
  24. case failedPrecondition
  25. /// Not enough space for model on device.
  26. case notEnoughSpace
  27. /// Malformed model name.
  28. case invalidArgument
  29. /// Other errors with description.
  30. case internalError(description: String)
  31. }
  32. /// Possible errors with locating model on device.
  33. public enum DownloadedModelError: Error {
  34. /// File system error.
  35. case fileIOError(description: String)
  36. /// Model not found on device.
  37. case notFound
  38. /// Other errors with description.
  39. case internalError(description: String)
  40. }
  41. /// Extension to handle internally meaningful errors.
  42. extension DownloadError {
  43. static let expiredDownloadURL: DownloadError = {
  44. DownloadError.internalError(description: "Expired model download URL.")
  45. }()
  46. }
  47. /// Possible ways to get a custom model.
  48. public enum ModelDownloadType {
  49. /// Get local model stored on device.
  50. case localModel
  51. /// Get local model on device and update to latest model from server in the background.
  52. case localModelUpdateInBackground
  53. /// Get latest model from server.
  54. case latestModel
  55. }
  56. /// Downloader to manage custom model downloads.
  57. public class ModelDownloader {
  58. /// Name of the app associated with this instance of ModelDownloader.
  59. private let appName: String
  60. /// Current Firebase app options.
  61. private let options: FirebaseOptions
  62. /// Installations instance for current Firebase app.
  63. private let installations: Installations
  64. /// User defaults for model info.
  65. private let userDefaults: UserDefaults
  66. /// Telemetry logger tied to this instance of model downloader.
  67. let telemetryLogger: TelemetryLogger?
  68. /// Number of retries in case of model download URL expiry.
  69. var numberOfRetries: Int = 1
  70. /// Handler that always runs on the main thread
  71. let mainQueueHandler = { handler in
  72. DispatchQueue.main.async {
  73. handler
  74. }
  75. }
  76. /// Shared dictionary mapping app name to a specific instance of model downloader.
  77. // TODO: Switch to using Firebase components.
  78. private static var modelDownloaderDictionary: [String: ModelDownloader] = [:]
  79. /// Private init for downloader.
  80. private init(app: FirebaseApp, defaults: UserDefaults = .firebaseMLDefaults) {
  81. appName = app.name
  82. options = app.options
  83. installations = Installations.installations(app: app)
  84. /// Respect Firebase-wide data collection setting.
  85. telemetryLogger = TelemetryLogger(app: app)
  86. userDefaults = defaults
  87. let notificationName = "FIRAppDeleteNotification"
  88. NotificationCenter.default.addObserver(
  89. self,
  90. selector: #selector(deleteModelDownloader),
  91. name: Notification.Name(notificationName),
  92. object: nil
  93. )
  94. }
  95. /// Handles app deletion notification.
  96. @objc private func deleteModelDownloader(notification: Notification) {
  97. let userInfoKey = "FIRAppNameKey"
  98. if let userInfo = notification.userInfo,
  99. let appName = userInfo[userInfoKey] as? String {
  100. ModelDownloader.modelDownloaderDictionary.removeValue(forKey: appName)
  101. // TODO: Do we need to force deinit downloader instance?
  102. // TODO: Clean up user defaults
  103. // TODO: Clean up local instances of app
  104. DeviceLogger.logEvent(level: .debug,
  105. message: ModelDownloader.DebugDescription.deleteModelDownloader,
  106. messageCode: .downloaderInstanceDeleted)
  107. }
  108. }
  109. /// Model downloader with default app.
  110. public static func modelDownloader() -> ModelDownloader {
  111. guard let defaultApp = FirebaseApp.app() else {
  112. fatalError(ModelDownloader.ErrorDescription.defaultAppNotConfigured)
  113. }
  114. return modelDownloader(app: defaultApp)
  115. }
  116. /// Model Downloader with custom app.
  117. public static func modelDownloader(app: FirebaseApp) -> ModelDownloader {
  118. if let downloader = modelDownloaderDictionary[app.name] {
  119. DeviceLogger.logEvent(level: .debug,
  120. message: ModelDownloader.DebugDescription.retrieveModelDownloader,
  121. messageCode: .downloaderInstanceRetrieved)
  122. return downloader
  123. } else {
  124. let downloader = ModelDownloader(app: app)
  125. modelDownloaderDictionary[app.name] = downloader
  126. DeviceLogger.logEvent(level: .debug,
  127. message: ModelDownloader.DebugDescription.createModelDownloader,
  128. messageCode: .downloaderInstanceCreated)
  129. return downloader
  130. }
  131. }
  132. /// Downloads a custom model to device or gets a custom model already on device, w/ optional handler for progress.
  133. public func getModel(name modelName: String,
  134. downloadType: ModelDownloadType,
  135. conditions: ModelDownloadConditions,
  136. progressHandler: ((Float) -> Void)? = nil,
  137. completion: @escaping (Result<CustomModel, DownloadError>) -> Void) {
  138. switch downloadType {
  139. case .localModel:
  140. if let localModel = getLocalModel(modelName: modelName) {
  141. DeviceLogger.logEvent(level: .debug,
  142. message: ModelDownloader.DebugDescription.localModelFound,
  143. messageCode: .localModelFound)
  144. mainQueueHandler(completion(.success(localModel)))
  145. } else {
  146. getRemoteModel(
  147. modelName: modelName,
  148. conditions: conditions,
  149. progressHandler: progressHandler,
  150. completion: completion
  151. )
  152. }
  153. case .localModelUpdateInBackground:
  154. if let localModel = getLocalModel(modelName: modelName) {
  155. DeviceLogger.logEvent(level: .debug,
  156. message: ModelDownloader.DebugDescription.localModelFound,
  157. messageCode: .localModelFound)
  158. mainQueueHandler(completion(.success(localModel)))
  159. telemetryLogger?.logModelDownloadEvent(
  160. eventName: .modelDownload,
  161. status: .scheduled,
  162. downloadErrorCode: .noError
  163. )
  164. DispatchQueue.global(qos: .utility).async { [weak self] in
  165. self?.getRemoteModel(
  166. modelName: modelName,
  167. conditions: conditions,
  168. progressHandler: nil,
  169. completion: { result in
  170. switch result {
  171. case let .success(model):
  172. DeviceLogger.logEvent(level: .debug,
  173. message: ModelDownloader.DebugDescription
  174. .backgroundModelDownloaded,
  175. messageCode: .backgroundModelDownloaded)
  176. self?.telemetryLogger?.logModelDownloadEvent(
  177. eventName: .modelDownload,
  178. status: .succeeded,
  179. model: model,
  180. downloadErrorCode: .noError
  181. )
  182. case .failure:
  183. DeviceLogger.logEvent(level: .debug,
  184. message: ModelDownloader.ErrorDescription
  185. .backgroundModelDownload,
  186. messageCode: .backgroundDownloadError)
  187. self?.telemetryLogger?.logModelDownloadEvent(
  188. eventName: .modelDownload,
  189. status: .failed,
  190. downloadErrorCode: .downloadFailed
  191. )
  192. }
  193. }
  194. )
  195. }
  196. } else {
  197. getRemoteModel(
  198. modelName: modelName,
  199. conditions: conditions,
  200. progressHandler: progressHandler,
  201. completion: completion
  202. )
  203. }
  204. case .latestModel:
  205. getRemoteModel(
  206. modelName: modelName,
  207. conditions: conditions,
  208. progressHandler: progressHandler,
  209. completion: completion
  210. )
  211. }
  212. }
  213. /// Gets all downloaded models.
  214. public func listDownloadedModels(completion: @escaping (Result<Set<CustomModel>,
  215. DownloadedModelError>) -> Void) {
  216. do {
  217. let modelPaths = try ModelFileManager.contentsOfModelsDirectory()
  218. var customModels = Set<CustomModel>()
  219. for path in modelPaths {
  220. guard let modelName = ModelFileManager.getModelNameFromFilePath(path) else {
  221. let description = ModelDownloader.ErrorDescription.parseModelName(path.absoluteString)
  222. DeviceLogger.logEvent(level: .debug,
  223. message: description,
  224. messageCode: .modelNameParseError)
  225. mainQueueHandler(completion(.failure(.internalError(description: description))))
  226. return
  227. }
  228. guard let modelInfo = getLocalModelInfo(modelName: modelName) else {
  229. let description = ModelDownloader.ErrorDescription.noLocalModelInfo(modelName)
  230. DeviceLogger.logEvent(level: .debug,
  231. message: description,
  232. messageCode: .noLocalModelInfo)
  233. mainQueueHandler(completion(.failure(.internalError(description: description))))
  234. return
  235. }
  236. guard let pathURL = URL(string: modelInfo.path)?.standardizedFileURL,
  237. pathURL == path.standardizedFileURL else {
  238. DeviceLogger.logEvent(level: .debug,
  239. message: ModelDownloader.ErrorDescription.outdatedModelPath,
  240. messageCode: .outdatedModelPathError)
  241. mainQueueHandler(completion(.failure(.internalError(description: ModelDownloader
  242. .ErrorDescription.outdatedModelPath))))
  243. return
  244. }
  245. let model = CustomModel(localModelInfo: modelInfo)
  246. customModels.insert(model)
  247. }
  248. DeviceLogger.logEvent(level: .debug,
  249. message: ModelDownloader.DebugDescription.allLocalModelsFound,
  250. messageCode: .allLocalModelsFound)
  251. completion(.success(customModels))
  252. } catch let error as DownloadedModelError {
  253. DeviceLogger.logEvent(level: .debug,
  254. message: ModelDownloader.ErrorDescription.listModelsFailed(error),
  255. messageCode: .listModelsError)
  256. mainQueueHandler(completion(.failure(error)))
  257. } catch {
  258. DeviceLogger.logEvent(level: .debug,
  259. message: ModelDownloader.ErrorDescription.listModelsFailed(error),
  260. messageCode: .listModelsError)
  261. mainQueueHandler(completion(.failure(.internalError(description: error
  262. .localizedDescription))))
  263. }
  264. }
  265. /// Deletes a custom model from device.
  266. public func deleteDownloadedModel(name modelName: String,
  267. completion: @escaping (Result<Void, DownloadedModelError>)
  268. -> Void) {
  269. guard let localModelInfo = getLocalModelInfo(modelName: modelName),
  270. let localPath = URL(string: localModelInfo.path)
  271. else {
  272. DeviceLogger.logEvent(level: .debug,
  273. message: ModelDownloader.ErrorDescription.modelNotFound(modelName),
  274. messageCode: .modelNotFound)
  275. mainQueueHandler(completion(.failure(.notFound)))
  276. return
  277. }
  278. do {
  279. try ModelFileManager.removeFile(at: localPath)
  280. DeviceLogger.logEvent(level: .debug,
  281. message: ModelDownloader.DebugDescription.modelDeleted,
  282. messageCode: .modelDeleted)
  283. mainQueueHandler(completion(.success(())))
  284. } catch let error as DownloadedModelError {
  285. mainQueueHandler(completion(.failure(error)))
  286. } catch {
  287. mainQueueHandler(completion(.failure(.internalError(description: error
  288. .localizedDescription))))
  289. }
  290. }
  291. }
  292. extension ModelDownloader {
  293. /// Return local model info only if the model info is available and the corresponding model file is already on device.
  294. private func getLocalModelInfo(modelName: String) -> LocalModelInfo? {
  295. guard let localModelInfo = LocalModelInfo(
  296. fromDefaults: userDefaults,
  297. name: modelName,
  298. appName: appName
  299. ) else {
  300. let description = ModelDownloader.DebugDescription.noLocalModelInfo(modelName)
  301. DeviceLogger.logEvent(level: .debug,
  302. message: description,
  303. messageCode: .noLocalModelInfo)
  304. return nil
  305. }
  306. /// There is local model info on device, but no model file at the expected path.
  307. guard let localPath = URL(string: localModelInfo.path),
  308. ModelFileManager.isFileReachable(at: localPath) else {
  309. // TODO: Consider deleting local model info in user defaults.
  310. return nil
  311. }
  312. return localModelInfo
  313. }
  314. /// Get model saved on device if available.
  315. private func getLocalModel(modelName: String) -> CustomModel? {
  316. guard let localModelInfo = getLocalModelInfo(modelName: modelName) else { return nil }
  317. let model = CustomModel(localModelInfo: localModelInfo)
  318. return model
  319. }
  320. /// Download and get model from server, unless the latest model is already available on device.
  321. private func getRemoteModel(modelName: String,
  322. conditions: ModelDownloadConditions,
  323. progressHandler: ((Float) -> Void)? = nil,
  324. completion: @escaping (Result<CustomModel, DownloadError>) -> Void) {
  325. let localModelInfo = getLocalModelInfo(modelName: modelName)
  326. guard let projectID = options.projectID, let apiKey = options.apiKey else {
  327. DeviceLogger.logEvent(level: .debug,
  328. message: ModelDownloader.ErrorDescription.invalidOptions,
  329. messageCode: .invalidOptions)
  330. completion(.failure(.internalError(description: ModelDownloader.ErrorDescription
  331. .invalidOptions)))
  332. return
  333. }
  334. let modelInfoRetriever = ModelInfoRetriever(
  335. modelName: modelName,
  336. projectID: projectID,
  337. apiKey: apiKey,
  338. installations: installations,
  339. appName: appName,
  340. localModelInfo: localModelInfo,
  341. telemetryLogger: telemetryLogger
  342. )
  343. let downloader = ModelFileDownloader(conditions: conditions)
  344. downloadInfoAndModel(
  345. modelName: modelName,
  346. modelInfoRetriever: modelInfoRetriever,
  347. downloader: downloader,
  348. conditions: conditions,
  349. progressHandler: progressHandler,
  350. completion: completion
  351. )
  352. }
  353. func downloadInfoAndModel(modelName: String,
  354. modelInfoRetriever: ModelInfoRetriever,
  355. downloader: FileDownloader,
  356. conditions: ModelDownloadConditions,
  357. progressHandler: ((Float) -> Void)? = nil,
  358. completion: @escaping (Result<CustomModel, DownloadError>)
  359. -> Void) {
  360. // TODO: Merge if there are multiple same requests.
  361. modelInfoRetriever.downloadModelInfo { result in
  362. switch result {
  363. case let .success(downloadModelInfoResult):
  364. switch downloadModelInfoResult {
  365. /// New model info was downloaded from server.
  366. case let .modelInfo(remoteModelInfo):
  367. let downloadTask = ModelDownloadTask(
  368. remoteModelInfo: remoteModelInfo,
  369. appName: self.appName,
  370. defaults: self.userDefaults,
  371. downloader: downloader,
  372. telemetryLogger: self.telemetryLogger
  373. )
  374. downloadTask.download(progressHandler: { progress in
  375. if let progressHandler = progressHandler {
  376. self.mainQueueHandler(progressHandler(progress))
  377. }
  378. }) { result in
  379. switch result {
  380. case let .success(model):
  381. self.mainQueueHandler(completion(.success(model)))
  382. case let .failure(error):
  383. switch error {
  384. case .notFound:
  385. self.mainQueueHandler(completion(.failure(.notFound)))
  386. case .invalidArgument:
  387. self.mainQueueHandler(completion(.failure(.invalidArgument)))
  388. case .permissionDenied:
  389. self.mainQueueHandler(completion(.failure(.permissionDenied)))
  390. /// This is the error returned when URL expired.
  391. case .expiredDownloadURL:
  392. /// Check if retries are allowed.
  393. guard self.numberOfRetries > 0 else {
  394. self
  395. .mainQueueHandler(
  396. completion(.failure(.internalError(description: ModelDownloader
  397. .ErrorDescription
  398. .expiredModelInfo)))
  399. )
  400. return
  401. }
  402. self.numberOfRetries -= 1
  403. DeviceLogger.logEvent(level: .debug,
  404. message: ModelDownloader.DebugDescription.retryDownload,
  405. messageCode: .retryDownload)
  406. self.downloadInfoAndModel(
  407. modelName: modelName,
  408. modelInfoRetriever: modelInfoRetriever,
  409. downloader: downloader,
  410. conditions: conditions,
  411. progressHandler: progressHandler,
  412. completion: completion
  413. )
  414. default:
  415. self.mainQueueHandler(completion(.failure(error)))
  416. }
  417. }
  418. }
  419. /// Local model info is the latest model info.
  420. case .notModified:
  421. guard let localModel = self.getLocalModel(modelName: modelName) else {
  422. /// This can only happen if either local model info or the model file was suddenly wiped out in the middle of model info request and server response
  423. // TODO: Consider handling: If model file is deleted after local model info is retrieved but before model info network call.
  424. self
  425. .mainQueueHandler(completion(.failure(.internalError(description: ModelDownloader
  426. .ErrorDescription.deletedLocalModelInfo))))
  427. return
  428. }
  429. self.mainQueueHandler(completion(.success(localModel)))
  430. }
  431. case let .failure(error):
  432. self.mainQueueHandler(completion(.failure(error)))
  433. }
  434. }
  435. }
  436. }
  437. /// Model downloader extension for testing.
  438. extension ModelDownloader {
  439. /// Model downloader instance for testing.
  440. // TODO: Consider using protocols
  441. static func modelDownloaderWithDefaults(_ defaults: UserDefaults,
  442. app: FirebaseApp) -> ModelDownloader {
  443. if let downloader = modelDownloaderDictionary[app.name] {
  444. return downloader
  445. } else {
  446. let downloader = ModelDownloader(app: app, defaults: defaults)
  447. modelDownloaderDictionary[app.name] = downloader
  448. return downloader
  449. }
  450. }
  451. }
  452. /// Possible error messages while using model downloader.
  453. extension ModelDownloader {
  454. /// Debug descriptions.
  455. private enum DebugDescription {
  456. static let deleteModelDownloader = "Model downloader instance deleted due to app deletion."
  457. static let retrieveModelDownloader =
  458. "Initialized with existing downloader instance associated with this app."
  459. static let createModelDownloader =
  460. "Initialized with new downloader instance associated with this app."
  461. static let localModelFound = "Found local model on device."
  462. static let backgroundModelDownloaded = "Downloaded latest model in the background."
  463. static let allLocalModelsFound = "Found and listed all local models."
  464. static let modelDeleted = "Model deleted successfully."
  465. static let retryDownload = "Retrying download."
  466. static let noLocalModelInfo = { (name: String) in
  467. "No local model info for model file named: \(name)."
  468. }
  469. }
  470. /// Error descriptions.
  471. private enum ErrorDescription {
  472. static let defaultAppNotConfigured =
  473. "Default Firebase app not configured."
  474. static let parseModelName = { (path: String) in
  475. "List models failed due to unexpected model file name at \(path)."
  476. }
  477. static let invalidOptions = "Unable to retrieve project ID and/or API key for Firebase app."
  478. static let listModelsFailed = { (error: Error) in
  479. "Unable to list models, failed with error: \(error)"
  480. }
  481. static let modelNotFound = { (name: String) in
  482. "Model deletion failed due to no model found with name: \(name)"
  483. }
  484. static let noLocalModelInfo = { (name: String) in
  485. "List models failed due to no local model info for model file named: \(name)."
  486. }
  487. static let modelDownloadFailed = { (error: Error) in
  488. "Model download failed with error: \(error)"
  489. }
  490. static let modelInfoRetrievalFailed = { (error: Error) in
  491. "Model info retrieval failed with error: \(error)"
  492. }
  493. static let outdatedModelPath =
  494. "List models failed due to outdated model paths in local storage."
  495. static let deletedLocalModelInfo =
  496. "Model unavailable due to deleted local model info."
  497. static let backgroundModelDownload =
  498. "Failed to update model in background."
  499. static let expiredModelInfo = "Unable to update expired model info."
  500. }
  501. }