Skip to content

Commit

Permalink
Make file download requests chunked (#75)
Browse files Browse the repository at this point in the history
  • Loading branch information
NoFearJoe authored Mar 2, 2021
1 parent a41f5f3 commit 02e7176
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 17 deletions.
10 changes: 0 additions & 10 deletions Sources/FigmaExport/Loaders/ImagesLoader.swift
Original file line number Diff line number Diff line change
Expand Up @@ -214,13 +214,3 @@ private extension String {
}

}

// MARK: - Array Utils

private extension Array {
func chunked(into size: Int) -> [[Element]] {
stride(from: 0, to: count, by: size).map {
Array(self[$0 ..< Swift.min($0 + size, count)])
}
}
}
20 changes: 13 additions & 7 deletions Sources/FigmaExport/Output/FileDownloader.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,22 +14,26 @@ final class FileDownloader {
func fetch(files: [FileContents]) throws -> [FileContents] {
let group = DispatchGroup()
var errors: [Error] = []

var newFiles = [FileContents]()

let remoteFileCount = files.filter { $0.sourceURL != nil }.count
var downloaded = 0

let semaphore = DispatchSemaphore(value: session.configuration.httpMaximumConnectionsPerHost - 1)

files.forEach { file in
guard let remoteURL = file.sourceURL else {
newFiles.append(file)
return
}

group.enter()
let task = session.downloadTask(with: remoteURL) { localURL, _, error in
defer { group.leave() }

defer {
semaphore.signal()
group.leave()
}

guard let fileURL = localURL, error == nil else {
errors.append(error!)
return
Expand All @@ -44,15 +48,17 @@ final class FileDownloader {
downloaded += 1
self.logger.info("Downloaded \(downloaded)/\(remoteFileCount)")
}


group.enter()
semaphore.wait()
task.resume()
}
group.wait()

if !errors.isEmpty {
throw ErrorGroup(all: errors)
}

return newFiles
}
}
9 changes: 9 additions & 0 deletions Sources/FigmaExportCore/Extensions/Array+chunked.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import Foundation

public extension Array {
func chunked(into size: Int) -> [[Element]] {
stride(from: 0, to: count, by: size).map {
Array(self[$0 ..< Swift.min($0 + size, count)])
}
}
}

0 comments on commit 02e7176

Please sign in to comment.