Skip to content

Commit

Permalink
Prepare for 0.3.0
Browse files Browse the repository at this point in the history
  • Loading branch information
fpseverino committed Oct 12, 2024
1 parent 2114c3e commit 11fbe49
Show file tree
Hide file tree
Showing 14 changed files with 51 additions and 47 deletions.
15 changes: 15 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
name: test
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
on:
pull_request: { types: [opened, reopened, synchronize, ready_for_review] }
push: { branches: [ main ] }

jobs:
unit-tests:
uses: vapor/ci/.github/workflows/run-unit-tests.yml@main
with:
with_linting: true
secrets:
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ Use this web-based service to streamline your app’s API by moving georelated s
Use the SPM string to easily include the dependendency in your `Package.swift` file

```swift
.package(url: "https://github.com/fpseverino/apple-maps-kit.git", from: "0.2.0")
.package(url: "https://github.com/fpseverino/apple-maps-kit.git", from: "0.3.0")
```

and add it to your target's dependencies:
Expand Down
2 changes: 1 addition & 1 deletion Sources/AppleMapsKit/AppleMapsKit.docc/AppleMapsKit.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ Use this web-based service to streamline your app’s API by moving georelated s
Use the SPM string to easily include the dependendency in your `Package.swift` file

```swift
.package(url: "https://github.com/fpseverino/apple-maps-kit.git", from: "0.2.0")
.package(url: "https://github.com/fpseverino/apple-maps-kit.git", from: "0.3.0")
```

and add it to your target's dependencies:
Expand Down
2 changes: 1 addition & 1 deletion Sources/AppleMapsKit/AppleMapsKit.docc/Geocode.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ Returns the latitude and longitude of the address you specify.
import AppleMapsKit
import AsyncHTTPClient

let client = try await AppleMapsClient(
let client = AppleMapsClient(
httpClient: HTTPClient(...),
teamID: "DEF123GHIJ",
keyID: "ABC123DEFG",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ Find directions by specific criteria.
import AppleMapsKit
import AsyncHTTPClient

let client = try await AppleMapsClient(
let client = AppleMapsClient(
httpClient: HTTPClient(...),
teamID: "DEF123GHIJ",
keyID: "ABC123DEFG",
Expand Down
2 changes: 1 addition & 1 deletion Sources/AppleMapsKit/AppleMapsKit.docc/GettingETAs.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ Returns the estimated time of arrival (ETA) and distance between starting and en
import AppleMapsKit
import AsyncHTTPClient

let client = try await AppleMapsClient(
let client = AppleMapsClient(
httpClient: HTTPClient(...),
teamID: "DEF123GHIJ",
keyID: "ABC123DEFG",
Expand Down
2 changes: 1 addition & 1 deletion Sources/AppleMapsKit/AppleMapsKit.docc/GettingPlaces.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ Obtain a set of ``Place`` objects for a given set of Place IDs or get a list of
import AppleMapsKit
import AsyncHTTPClient

let client = try await AppleMapsClient(
let client = AppleMapsClient(
httpClient: HTTPClient(...),
teamID: "DEF123GHIJ",
keyID: "ABC123DEFG",
Expand Down
2 changes: 1 addition & 1 deletion Sources/AppleMapsKit/AppleMapsKit.docc/ReverseGeocode.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ Returns an array of addresses present at the coordinates you provide.
import AppleMapsKit
import AsyncHTTPClient

let client = try await AppleMapsClient(
let client = AppleMapsClient(
httpClient: HTTPClient(...),
teamID: "DEF123GHIJ",
keyID: "ABC123DEFG",
Expand Down
2 changes: 1 addition & 1 deletion Sources/AppleMapsKit/AppleMapsKit.docc/Search.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ Find places by name or by specific search criteria.
import AppleMapsKit
import AsyncHTTPClient

let client = try await AppleMapsClient(
let client = AppleMapsClient(
httpClient: HTTPClient(...),
teamID: "DEF123GHIJ",
keyID: "ABC123DEFG",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ Find results that you can use to autocomplete searches.
import AppleMapsKit
import AsyncHTTPClient

let client = try await AppleMapsClient(
let client = AppleMapsClient(
httpClient: HTTPClient(...),
teamID: "DEF123GHIJ",
keyID: "ABC123DEFG",
Expand Down
27 changes: 11 additions & 16 deletions Sources/AppleMapsKit/Authorization/AuthorizationProvider.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,7 @@ import Foundation
import JWTKit
import NIOHTTP1

// MARK: - auth/c & auth/z
internal actor AuthorizationProvider {

actor AuthorizationProvider {
private let httpClient: HTTPClient
private let apiServer: String
private let teamID: String
Expand All @@ -22,7 +20,7 @@ internal actor AuthorizationProvider {
private var currentToken: TokenResponse?
private var refreshTask: Task<TokenResponse, any Error>?

internal init(httpClient: HTTPClient, apiServer: String, teamID: String, keyID: String, key: String) {
init(httpClient: HTTPClient, apiServer: String, teamID: String, keyID: String, key: String) {
self.httpClient = httpClient
self.apiServer = apiServer
self.teamID = teamID
Expand All @@ -32,25 +30,25 @@ internal actor AuthorizationProvider {

func validToken() async throws -> TokenResponse {
// If we're currently refreshing a token, await the value for our refresh task to make sure we return the refreshed token.
if let handle = refreshTask {
return try await handle.value
if let refreshTask {
return try await refreshTask.value
}

// If we don't have a current token, we request a new one.
guard let token = currentToken else {
guard let currentToken else {
return try await refreshToken()
}

if token.isValid {
return token
if currentToken.isValid {
return currentToken
}

// None of the above applies so we'll need to refresh the token.
return try await refreshToken()
}

private func refreshToken() async throws -> TokenResponse {
if let refreshTask = refreshTask {
if let refreshTask {
return try await refreshTask.value
}

Expand All @@ -67,9 +65,7 @@ internal actor AuthorizationProvider {
}
}

// MARK: - HELPERS
extension AuthorizationProvider {

/// Makes an HTTP request to exchange Auth token for Access token.
///
/// - Parameters:
Expand All @@ -79,7 +75,7 @@ extension AuthorizationProvider {
/// - Throws: Error response object.
///
/// - Returns: An access token.
fileprivate func getAccessToken(authToken: String) async throws -> TokenResponse {
private func getAccessToken(authToken: String) async throws -> TokenResponse {
var headers = HTTPHeaders()
headers.add(name: "Authorization", value: "Bearer \(authToken)")

Expand All @@ -89,8 +85,7 @@ extension AuthorizationProvider {
let response = try await httpClient.execute(request, timeout: .seconds(30))

if response.status == .ok {
return try await JSONDecoder()
.decode(TokenResponse.self, from: response.body.collect(upTo: 1024 * 1024))
return try await JSONDecoder().decode(TokenResponse.self, from: response.body.collect(upTo: 1024 * 1024))
} else {
throw try await JSONDecoder().decode(ErrorResponse.self, from: response.body.collect(upTo: 1024 * 1024))
}
Expand All @@ -104,7 +99,7 @@ extension AuthorizationProvider {
/// - key: A MapKit JS private key.
///
/// - Returns: A JWT token represented as `String`.
fileprivate func createJWT(teamID: String, keyID: String, key: String) async throws -> String {
private func createJWT(teamID: String, keyID: String, key: String) async throws -> String {
let keys = try await JWTKeyCollection().add(ecdsa: ES256PrivateKey(pem: key))

var header = JWTHeader()
Expand Down
16 changes: 6 additions & 10 deletions Sources/AppleMapsKit/Authorization/TokenResponse.swift
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import Foundation

/// An object that contains an access token and an expiration time in seconds.
internal struct TokenResponse: Codable {
struct TokenResponse: Codable {
/// A string that represents the access token.
let accessToken: String

Expand All @@ -11,28 +11,24 @@ internal struct TokenResponse: Codable {
/// A date that indicates when then token will expire.
let expirationDate: Date

internal init(from decoder: any Decoder) throws {
init(from decoder: any Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.accessToken = try container.decode(String.self, forKey: .accessToken)
self.expiresInSeconds = try container.decode(Int.self, forKey: .expiresInSeconds)
self.expirationDate = Date.now.addingTimeInterval(TimeInterval(expiresInSeconds))
}

internal init(accessToken: String, expiresInSeconds: Int) {
init(accessToken: String, expiresInSeconds: Int) {
self.accessToken = accessToken
self.expiresInSeconds = expiresInSeconds
self.expirationDate = Date.now.addingTimeInterval(TimeInterval(expiresInSeconds))
}

}

extension TokenResponse {

/// A boolean indicates whether to token is valid 10 seconds before it's actual expiry time.
var isValid: Bool {
let currentDate = Date.now
// we consider a token invalid 10 seconds before it actual expiry time, so we have some time to refresh it.
let expirationBuffer: TimeInterval = 10
return currentDate < (expirationDate - expirationBuffer)
// We consider a token invalid 10 seconds before it actual expiry time,
// so we have some time to refresh it.
return Date.now < (expirationDate - 10)
}
}
1 change: 1 addition & 0 deletions Tests/AppleMapsKitTests/AppleMapsKitTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import AsyncHTTPClient
import Foundation
import Testing

@Suite("AppleMapsKit Tests", .disabled(if: true, "Needs valid credentials"))
struct AppleMapsKitTests {
var client: AppleMapsClient

Expand Down
21 changes: 9 additions & 12 deletions Tests/AppleMapsKitTests/AuthorizationProviderTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,17 @@ import Testing

@testable import AppleMapsKit

@Suite("AuthorizationProvider Tests")
struct AuthorizationProviderTests {
// It's actually 1 second due to the expiration buffer on the token.
let token = TokenResponse(accessToken: "test", expiresInSeconds: 11)

struct TokenValidityTests {
// It's 1 second actually due to the expiration buffer on the token.
let token = TokenResponse(accessToken: "some token", expiresInSeconds: 11)

@Test func tokenInvalidCheck() async {
try? await Task.sleep(for: .seconds(2))
#expect(token.isValid == false)
}

@Test func tokenValidCheck() async {
#expect(token.isValid)
}
@Test("Invalid Access Token") func invalidToken() async throws {
try await Task.sleep(for: .seconds(2))
#expect(!token.isValid)
}

@Test("Valid Access Token") func validToken() {
#expect(token.isValid)
}
}

0 comments on commit 11fbe49

Please sign in to comment.