|
| 1 | +import FigmaAPI |
| 2 | +import Foundation |
| 3 | + |
| 4 | +/// Configuration for pre-fetch operation. |
| 5 | +struct PreFetchConfiguration { |
| 6 | + let configs: [ConfigFile] |
| 7 | + let cacheEnabled: Bool |
| 8 | + let noCacheFlag: Bool |
| 9 | + let verbose: Bool |
| 10 | + let rateLimiter: SharedRateLimiter |
| 11 | + let retryPolicy: RetryPolicy |
| 12 | +} |
| 13 | + |
| 14 | +/// Pre-fetches file metadata for multiple Figma files in parallel. |
| 15 | +/// |
| 16 | +/// Used by batch processing to fetch all unique file versions upfront, |
| 17 | +/// avoiding redundant API calls when multiple configs reference the same files. |
| 18 | +struct FileVersionPreFetcher: Sendable { |
| 19 | + let client: Client |
| 20 | + let ui: TerminalUI |
| 21 | + |
| 22 | + // MARK: - Static Factory |
| 23 | + |
| 24 | + /// Pre-fetches file versions for all unique file IDs if cache is enabled. |
| 25 | + /// |
| 26 | + /// This optimization fetches file metadata once per unique fileId before parallel |
| 27 | + /// config processing, avoiding redundant API calls when multiple configs reference |
| 28 | + /// the same Figma files. |
| 29 | + /// |
| 30 | + /// - Parameters: |
| 31 | + /// - configuration: Pre-fetch configuration. |
| 32 | + /// - ui: Terminal UI for progress output. |
| 33 | + /// - Returns: PreFetchedFileVersions if successful, nil otherwise. |
| 34 | + static func preFetchIfNeeded( |
| 35 | + configuration: PreFetchConfiguration, |
| 36 | + ui: TerminalUI |
| 37 | + ) async -> PreFetchedFileVersions? { |
| 38 | + // Only pre-fetch when cache is enabled |
| 39 | + guard configuration.cacheEnabled, !configuration.noCacheFlag else { |
| 40 | + return nil |
| 41 | + } |
| 42 | + |
| 43 | + // Extract unique file IDs from all configs |
| 44 | + let extractor = FileIdExtractor() |
| 45 | + let configURLs = configuration.configs.map(\.url) |
| 46 | + let uniqueFileIds = extractor.extractUniqueFileIds(from: configURLs) |
| 47 | + |
| 48 | + guard !uniqueFileIds.isEmpty else { |
| 49 | + return nil |
| 50 | + } |
| 51 | + |
| 52 | + if configuration.verbose { |
| 53 | + ui.info("Found \(uniqueFileIds.count) unique Figma file(s) to pre-fetch") |
| 54 | + } |
| 55 | + |
| 56 | + // Get access token |
| 57 | + guard let token = ProcessInfo.processInfo.environment["FIGMA_PERSONAL_TOKEN"] else { |
| 58 | + // Token missing, let individual configs handle this error |
| 59 | + return nil |
| 60 | + } |
| 61 | + |
| 62 | + // Create rate-limited client for pre-fetch |
| 63 | + let baseClient = FigmaClient(accessToken: token, timeout: nil) |
| 64 | + let client = RateLimitedClient( |
| 65 | + client: baseClient, |
| 66 | + rateLimiter: configuration.rateLimiter, |
| 67 | + configID: ConfigID("prefetch"), |
| 68 | + retryPolicy: configuration.retryPolicy |
| 69 | + ) |
| 70 | + |
| 71 | + // Pre-fetch file versions |
| 72 | + let preFetcher = FileVersionPreFetcher(client: client, ui: ui) |
| 73 | + do { |
| 74 | + return try await preFetcher.preFetch(fileIds: uniqueFileIds) |
| 75 | + } catch { |
| 76 | + // Pre-fetch failed, proceed without optimization |
| 77 | + // Individual configs will fetch their own metadata |
| 78 | + if configuration.verbose { |
| 79 | + ui.warning("Pre-fetch failed: \(error.localizedDescription)") |
| 80 | + } |
| 81 | + return nil |
| 82 | + } |
| 83 | + } |
| 84 | + |
| 85 | + // MARK: - Instance Methods |
| 86 | + |
| 87 | + /// Pre-fetch file metadata for all unique file IDs. |
| 88 | + /// |
| 89 | + /// - Parameter fileIds: Set of unique file IDs to fetch. |
| 90 | + /// - Returns: PreFetchedFileVersions containing all successfully fetched metadata. |
| 91 | + /// - Throws: Error if all fetches fail. Partial failures are handled gracefully. |
| 92 | + func preFetch(fileIds: Set<String>) async throws -> PreFetchedFileVersions { |
| 93 | + guard !fileIds.isEmpty else { |
| 94 | + return PreFetchedFileVersions(versions: [:]) |
| 95 | + } |
| 96 | + |
| 97 | + let fileIdArray = Array(fileIds) |
| 98 | + |
| 99 | + let result = try await ui.withSpinner( |
| 100 | + "Pre-fetching file versions (\(fileIdArray.count) unique files)..." |
| 101 | + ) { |
| 102 | + try await fetchAllMetadata(fileIds: fileIdArray) |
| 103 | + } |
| 104 | + |
| 105 | + // Report partial failures if any |
| 106 | + let failedCount = fileIdArray.count - result.count |
| 107 | + if failedCount > 0 { |
| 108 | + ui.warning(.preFetchPartialFailure(failed: failedCount, total: fileIdArray.count)) |
| 109 | + } |
| 110 | + |
| 111 | + return result |
| 112 | + } |
| 113 | + |
| 114 | + /// Fetch metadata for all file IDs in parallel. |
| 115 | + private func fetchAllMetadata(fileIds: [String]) async throws -> PreFetchedFileVersions { |
| 116 | + try await withThrowingTaskGroup(of: (String, FileMetadata?).self) { group in |
| 117 | + for fileId in fileIds { |
| 118 | + group.addTask { [client] in |
| 119 | + do { |
| 120 | + let endpoint = FileMetadataEndpoint(fileId: fileId) |
| 121 | + let metadata = try await client.request(endpoint) |
| 122 | + return (fileId, metadata) |
| 123 | + } catch { |
| 124 | + // Individual file fetch failed, return nil |
| 125 | + // Will be handled as partial failure |
| 126 | + return (fileId, nil) |
| 127 | + } |
| 128 | + } |
| 129 | + } |
| 130 | + |
| 131 | + var versions: [String: FileMetadata] = [:] |
| 132 | + for try await (fileId, metadata) in group { |
| 133 | + if let metadata { |
| 134 | + versions[fileId] = metadata |
| 135 | + } |
| 136 | + } |
| 137 | + |
| 138 | + // If all fetches failed, throw error |
| 139 | + if versions.isEmpty, !fileIds.isEmpty { |
| 140 | + throw PreFetchError.allFetchesFailed(count: fileIds.count) |
| 141 | + } |
| 142 | + |
| 143 | + return PreFetchedFileVersions(versions: versions) |
| 144 | + } |
| 145 | + } |
| 146 | +} |
| 147 | + |
| 148 | +// MARK: - Errors |
| 149 | + |
| 150 | +/// Errors that can occur during pre-fetching. |
| 151 | +enum PreFetchError: Error, LocalizedError { |
| 152 | + /// All file metadata fetches failed. |
| 153 | + case allFetchesFailed(count: Int) |
| 154 | + |
| 155 | + var errorDescription: String? { |
| 156 | + switch self { |
| 157 | + case let .allFetchesFailed(count): |
| 158 | + "Failed to pre-fetch all \(count) file versions" |
| 159 | + } |
| 160 | + } |
| 161 | + |
| 162 | + var recoverySuggestion: String? { |
| 163 | + switch self { |
| 164 | + case .allFetchesFailed: |
| 165 | + "Check your FIGMA_PERSONAL_TOKEN and network connection" |
| 166 | + } |
| 167 | + } |
| 168 | +} |
0 commit comments