Alamofire源碼解讀系列(十二)之時間軸(Timeline)

本篇帶來Alamofire中關於Timeline的一些思路html

前言

Timeline翻譯後的意思是時間軸,能夠表示一個事件從開始到結束的時間節點。時間軸的概念可以應用在不少地方,好比說微博的主頁就是一個時間軸。swift

Alamofire中Timeline的代碼不多,很是簡單。所以本篇文章中,咱們不會把重點放到代碼的解讀上,咱們經過追蹤Timeline的身影,來說講關於代碼設計方面的東東。安全

爲何要設計Timeline

很簡單,我須要知道一個請求過程當中,每一個關鍵時間點的值或者時間點與時間點之間的距離。這樣的一個需求不只可以用於程序的調試,並且能爲別的設計提供必要的參數支持。服務器

咱們經過下邊的代碼進行打印:網絡

print(response.timeline)

顯示的結果是:優化

Timeline: { "Latency": 0.092 secs, "Request Duration": 0.092 secs, "Serialization Duration": 0.458 secs, "Total Duration": 0.551 secs }

上邊的代碼提供的信息有:編碼

  • Latency: 0.092 secs 延遲,它表示從請求開始到收到或者發送第一個字節的時間長度,這裏把它理解成創建鏈接花費的時間
  • Request Duration: 0.092 secs 請求時間,它表示從請求開始到結束的時間長度。這裏跟Latency: 0.092 secs都是0.092,緣由是我用的POST請求
  • Serialization Duration: 0.458 secs 序列化用時,這裏用了0.458秒,說明在當前的這個請求中,最耗時的操做是數據的序列化,所以,程序能夠在這方面進行優化
  • Total Duration: 0.551 secs 總耗時 用序列化完成的時間點減去請求開始的時間點

print(response.timeline)之因此可以打印出上邊這些信息,是由於它重寫了CustomStringConvertible協議的var description: String。固然,若是要打印更詳細的信息,能夠重寫CustomDebugStringConvertiblevar debugDescription: String。咱們經過代碼打印出來:翻譯

print(response.timeline.debugDescription)

打印結果是:debug

Timeline: { "Request Start Time": 513055266.217, "Initial Response Time": 513055266.241, "Request Completed Time": 513055266.241, "Serialization Completed Time": 513055266.752, "Latency": 0.024 secs, "Request Duration": 0.024 secs, "Serialization Duration": 0.511 secs, "Total Duration": 0.535 secs }

如何設計Timeline

Alamofire中,無論Request請求成功仍是失敗都會返回response。所以Timeline只有跟response綁定才合理。因此應該把他設爲response的一個屬性,在以前的文章中,咱們也詳細的介紹了response,他是一個struct類型的數據存儲屬性,所以在初始化的時候給Timeline賦值。設計

這樣咱們就解決了取出Timeline的問題,那麼Timeline又是如何賦值的呢?咱們在Alamofire中追蹤Timeline的身影,最終發現只有三個文件中出現了它的身影:

  • Response.swift Timeline做爲Response的一個屬性,確定會出如今這裏
  • Timeline.swift 這是它自身的實現
  • ResponseSerialization.swift 在這個文件中,爲Request作了一個擴展,代碼以下:

    extension Request {
          var timeline: Timeline {
              let requestCompletedTime = self.endTime ?? CFAbsoluteTimeGetCurrent()
              let initialResponseTime = self.delegate.initialResponseTime ?? requestCompletedTime
    
              return Timeline(
                  requestStartTime: self.startTime ?? CFAbsoluteTimeGetCurrent(),
                  initialResponseTime: initialResponseTime,
                  requestCompletedTime: requestCompletedTime,
                  serializationCompletedTime: CFAbsoluteTimeGetCurrent()
              )
          }
      }

    這個擴展說明Timeline的值最終是經過getter方法獲取的,獲取的是計算後的值。

對於這樣的設計,可以給咱們一些啓示,咱們在設計某一個功能的時候,儘可能保持這個功能不去污染其餘的程序。咱們應該避免這樣的設計:建立一個對象後,在程序的不少地方給它的屬性賦值

代碼

只是把代碼弄上來:

/// Responsible for computing the timing metrics for the complete lifecycle of a `Request`.
public struct Timeline {
    /// The time the request was initialized.
    public let requestStartTime: CFAbsoluteTime

    /// The time the first bytes were received from or sent to the server.
    public let initialResponseTime: CFAbsoluteTime

    /// The time when the request was completed.
    public let requestCompletedTime: CFAbsoluteTime

    /// The time when the response serialization was completed.
    public let serializationCompletedTime: CFAbsoluteTime

    /// The time interval in seconds from the time the request started to the initial response from the server.
    public let latency: TimeInterval

    /// The time interval in seconds from the time the request started to the time the request completed.
    public let requestDuration: TimeInterval

    /// The time interval in seconds from the time the request completed to the time response serialization completed.
    public let serializationDuration: TimeInterval

    /// The time interval in seconds from the time the request started to the time response serialization completed.
    public let totalDuration: TimeInterval

    /// Creates a new `Timeline` instance with the specified request times.
    ///
    /// - parameter requestStartTime:           The time the request was initialized. Defaults to `0.0`.
    /// - parameter initialResponseTime:        The time the first bytes were received from or sent to the server.
    ///                                         Defaults to `0.0`.
    /// - parameter requestCompletedTime:       The time when the request was completed. Defaults to `0.0`.
    /// - parameter serializationCompletedTime: The time when the response serialization was completed. Defaults
    ///                                         to `0.0`.
    ///
    /// - returns: The new `Timeline` instance.
    public init(
        requestStartTime: CFAbsoluteTime = 0.0,
        initialResponseTime: CFAbsoluteTime = 0.0,
        requestCompletedTime: CFAbsoluteTime = 0.0,
        serializationCompletedTime: CFAbsoluteTime = 0.0)
    {
        self.requestStartTime = requestStartTime
        self.initialResponseTime = initialResponseTime
        self.requestCompletedTime = requestCompletedTime
        self.serializationCompletedTime = serializationCompletedTime

        self.latency = initialResponseTime - requestStartTime
        self.requestDuration = requestCompletedTime - requestStartTime
        self.serializationDuration = serializationCompletedTime - requestCompletedTime
        self.totalDuration = serializationCompletedTime - requestStartTime
    }
}

// MARK: - CustomStringConvertible

extension Timeline: CustomStringConvertible {
    /// The textual representation used when written to an output stream, which includes the latency, the request
    /// duration and the total duration.
    public var description: String {
        let latency = String(format: "%.3f", self.latency)
        let requestDuration = String(format: "%.3f", self.requestDuration)
        let serializationDuration = String(format: "%.3f", self.serializationDuration)
        let totalDuration = String(format: "%.3f", self.totalDuration)

        // NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is
        // fixed, we should move back to string interpolation by reverting commit 7d4a43b1.
        let timings = [
            "\"Latency\": " + latency + " secs",
            "\"Request Duration\": " + requestDuration + " secs",
            "\"Serialization Duration\": " + serializationDuration + " secs",
            "\"Total Duration\": " + totalDuration + " secs"
        ]

        return "Timeline: { " + timings.joined(separator: ", ") + " }"
    }
}
/// 使用timeline 可讓咱們很清楚的查看某個網絡請求過程的耗時,能夠藉此分析服務器端是否是有問題,同時也能夠簡介的得出當前的網絡狀況
// MARK: - CustomDebugStringConvertible

extension Timeline: CustomDebugStringConvertible {
    /// The textual representation used when written to an output stream, which includes the request start time, the
    /// initial response time, the request completed time, the serialization completed time, the latency, the request
    /// duration and the total duration.
    public var debugDescription: String {
        let requestStartTime = String(format: "%.3f", self.requestStartTime)
        let initialResponseTime = String(format: "%.3f", self.initialResponseTime)
        let requestCompletedTime = String(format: "%.3f", self.requestCompletedTime)
        let serializationCompletedTime = String(format: "%.3f", self.serializationCompletedTime)
        let latency = String(format: "%.3f", self.latency)
        let requestDuration = String(format: "%.3f", self.requestDuration)
        let serializationDuration = String(format: "%.3f", self.serializationDuration)
        let totalDuration = String(format: "%.3f", self.totalDuration)

        // NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is
        // fixed, we should move back to string interpolation by reverting commit 7d4a43b1.
        let timings = [
            "\"Request Start Time\": " + requestStartTime,
            "\"Initial Response Time\": " + initialResponseTime,
            "\"Request Completed Time\": " + requestCompletedTime,
            "\"Serialization Completed Time\": " + serializationCompletedTime,
            "\"Latency\": " + latency + " secs",
            "\"Request Duration\": " + requestDuration + " secs",
            "\"Serialization Duration\": " + serializationDuration + " secs",
            "\"Total Duration\": " + totalDuration + " secs"
        ]

        return "Timeline: { " + timings.joined(separator: ", ") + " }"
    }
}

總結

經過解讀源碼學到了不少,除了學到了一些平時不瞭解的技術外,最大的收穫就是學會了從設計的角度去開發程序。也許若干年後,你依然會記得當初某個程序的設計思想。

有時間會寫一個如何管理時間複雜度的文章。

因爲知識水平有限,若有錯誤,還望指出

連接

Alamofire源碼解讀系列(一)之概述和使用 簡書-----博客園

Alamofire源碼解讀系列(二)之錯誤處理(AFError) 簡書-----博客園

Alamofire源碼解讀系列(三)之通知處理(Notification) 簡書-----博客園

Alamofire源碼解讀系列(四)之參數編碼(ParameterEncoding) 簡書-----博客園

Alamofire源碼解讀系列(五)之結果封裝(Result) 簡書-----博客園

Alamofire源碼解讀系列(六)之Task代理(TaskDelegate) 簡書-----博客園

Alamofire源碼解讀系列(七)之網絡監控(NetworkReachabilityManager) 簡書-----博客園

Alamofire源碼解讀系列(八)之安全策略(ServerTrustPolicy) 簡書-----博客園

Alamofire源碼解讀系列(九)之響應封裝(Response) 簡書-----博客園

Alamofire源碼解讀系列(十)之序列化(ResponseSerialization) 簡書-----博客園

Alamofire源碼解讀系列(十一)之多表單(MultipartFormData) 簡書-----博客園

相關文章
相關標籤/搜索