Skip to content

Commit 9f9753b

Browse files
committed
update cli PAPI interactions
1 parent df611ec commit 9f9753b

File tree

3 files changed

+23
-124
lines changed

3 files changed

+23
-124
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ an Auth token in your Segment workspace.
6262
Reach out to your Customer Support Engineer (CSE) or Customer Success Manager (CSM)
6363
to have them add this feature to your account. Once that is completed, you may continue.
6464

65-
### Uploading Your Analytics Live Plugins to Your Workspace
65+
### Uploading Your Analytics Live Plugins to Your Source
6666

6767
In order to upload your Analytics Live Plugins you'll need the following command:
6868

Sources/segmentcli/Commands/LivePlugins.swift

Lines changed: 17 additions & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -14,23 +14,23 @@ import Segment
1414
class EdgeFnGroup: CommandGroup {
1515
let name = "liveplugins"
1616
let shortDescription = "Work with and develop analytics live plugins"
17-
let children: [Routable] = [EdgeFnLatestCommand(), EdgeFnUpload(), EdgeFnDisable()]
17+
let children: [Routable] = [EdgeFnLatestCommand(), EdgeFnUpload(), EdgeFnDeleteCode()]
1818
init() {}
1919
}
2020

21-
class EdgeFnDisable: Command {
22-
let name = "disable"
23-
let shortDescription = "Disable Live Plugins for a given source ID"
21+
class EdgeFnDeleteCode: Command {
22+
let name = "delete"
23+
let shortDescription = "Deletes Live Plugin code for a given source ID"
2424

2525
@Param var sourceId: String
2626

2727
func execute() throws {
2828
guard let workspace = currentWorkspace else { exitWithError(code: .commandFailed, message: "No authentication tokens found."); return }
2929
executeAndWait { semaphore in
30-
let spinner = Spinner(.dots, "Uploading live plugin ...")
30+
let spinner = Spinner(.dots, "Deleting live plugin code ...")
3131
spinner.start()
3232

33-
PAPI.shared.edgeFunctions.disable(token: workspace.token, sourceId: sourceId) { data, response, error in
33+
PAPI.shared.edgeFunctions.deleteCode(token: workspace.token, sourceId: sourceId) { data, response, error in
3434
spinner.stop()
3535

3636
if let error = error {
@@ -42,7 +42,7 @@ class EdgeFnDisable: Command {
4242
switch statusCode {
4343
case .ok:
4444
// success!
45-
print("Live plugins disabled for \(self.sourceId.italic.bold).")
45+
print("Live plugin code deleted for \(self.sourceId.italic.bold).")
4646

4747
case .unauthorized:
4848
fallthrough
@@ -74,80 +74,24 @@ class EdgeFnUpload: Command {
7474

7575
let fileURL = URL(fileURLWithPath: filePath.expandingTildeInPath)
7676

77-
// generate upload URL
78-
executeAndWait { semaphore in
79-
let spinner = Spinner(.dots, "Generating upload URL ...")
80-
spinner.start()
81-
82-
PAPI.shared.edgeFunctions.generateUploadURL(token: workspace.token, sourceId: sourceId) { data, response, error in
83-
spinner.stop()
84-
85-
if let error = error {
86-
exitWithError(error)
87-
}
88-
89-
let statusCode = PAPI.shared.statusCode(response: response)
90-
91-
switch statusCode {
92-
case .ok:
93-
// success!
94-
if let jsonData = data, let json = try? JSONSerialization.jsonObject(with: jsonData) as? [String: Any] {
95-
if let uploadString = json[keyPath: "data.uploadURL"] as? String {
96-
uploadURL = URL(string: uploadString)
97-
}
98-
}
99-
100-
case .unauthorized:
101-
fallthrough
102-
case .unauthorized2:
103-
exitWithError(code: .commandFailed, message: "Supplied token is not authorized.")
104-
case .notFound:
105-
exitWithError(code: .commandFailed, message: "No live plugins were found.")
106-
default:
107-
exitWithError("An unknown error occurred.")
108-
}
109-
semaphore.signal()
110-
}
77+
// Read file contents
78+
guard let fileContents = try? Data(contentsOf: fileURL) else {
79+
exitWithError(code: .commandFailed, message: "Unable to read file contents from \(filePath)")
80+
return
11181
}
11282

113-
// upload it to the URL we were given.
114-
executeAndWait { semaphore in
115-
let spinner = Spinner(.dots, "Uploading \(fileURL.lastPathComponent) ...")
116-
spinner.start()
117-
118-
PAPI.shared.edgeFunctions.uploadToGeneratedURL(token: workspace.token, url: uploadURL, fileURL: fileURL) { data, response, error in
119-
spinner.stop()
120-
121-
if let error = error {
122-
exitWithError(error)
123-
}
124-
125-
let statusCode = PAPI.shared.statusCode(response: response)
126-
127-
switch statusCode {
128-
case .ok:
129-
// success!
130-
break
131-
132-
case .unauthorized:
133-
fallthrough
134-
case .unauthorized2:
135-
exitWithError(code: .commandFailed, message: "Supplied token is not authorized.")
136-
case .notFound:
137-
exitWithError(code: .commandFailed, message: "No live plugins were found.")
138-
default:
139-
exitWithError("An unknown error occurred.")
140-
}
141-
semaphore.signal()
142-
}
83+
// Convert Data to String
84+
guard let code = String(data: fileContents, encoding: .utf8) else {
85+
exitWithError(code: .commandFailed, message: "Unable to convert file contents to string. File may not be valid UTF-8.")
86+
return
14387
}
14488

14589
// call create to make a new connection to the version we just posted.
14690
executeAndWait { semaphore in
14791
let spinner = Spinner(.dots, "Creating new live plugin version ...")
14892
spinner.start()
149-
150-
PAPI.shared.edgeFunctions.createNewVersion(token: workspace.token, sourceId: sourceId, uploadURL: uploadURL) { data, response, error in
93+
94+
PAPI.shared.edgeFunctions.createNewVersion(token: workspace.token, sourceId: sourceId, code: code) { data, response, error in
15195
spinner.stop()
15296

15397
if let error = error {

Sources/segmentcli/PAPI/PAPIEdgeFunctions.swift

Lines changed: 5 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import Foundation
99

1010
extension PAPI {
1111
class EdgeFunctions: PAPISection {
12-
static let pathEntry = "edge-functions"
12+
static let pathEntry = "live-plugins"
1313

1414
func latest(token: String, sourceId: String, completion: @escaping (Data?, URLResponse?, Error?) -> Void) {
1515
guard var url = URL(string: PAPIEndpoint) else { completion(nil, nil, "Unable to create URL."); return }
@@ -27,47 +27,11 @@ extension PAPI {
2727
task.resume()
2828
}
2929

30-
func disable(token: String, sourceId: String, completion: @escaping (Data?, URLResponse?, Error?) -> Void) {
31-
guard var url = URL(string: PAPIEndpoint) else { completion(nil, nil, "Unable to create URL."); return }
32-
33-
url.appendPathComponent(PAPI.Sources.pathEntry)
34-
url.appendPathComponent(sourceId)
35-
url.appendPathComponent(PAPI.EdgeFunctions.pathEntry)
36-
url.appendPathComponent("disable")
37-
38-
var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 30)
39-
request.httpMethod = "PATCH"
40-
request.addValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
41-
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
42-
request.httpBody = "{ \"sourceId\": \"\(sourceId)\" }".data(using: .utf8)
43-
44-
let task = URLSession.shared.dataTask(with: request, completionHandler: completion)
45-
task.resume()
46-
}
47-
48-
func generateUploadURL(token: String, sourceId: String, completion: @escaping (Data?, URLResponse?, Error?) -> Void) {
49-
guard var url = URL(string: PAPIEndpoint) else { completion(nil, nil, "Unable to create URL."); return }
50-
51-
url.appendPathComponent(PAPI.Sources.pathEntry)
52-
url.appendPathComponent(sourceId)
53-
url.appendPathComponent(PAPI.EdgeFunctions.pathEntry)
54-
url.appendPathComponent("upload-url")
55-
56-
var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 30)
57-
request.httpMethod = "POST"
58-
request.addValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
59-
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
60-
request.httpBody = "{ \"sourceId\": \"\(sourceId)\" }".data(using: .utf8)
61-
62-
let task = URLSession.shared.dataTask(with: request, completionHandler: completion)
63-
task.resume()
64-
}
65-
6630
// http://blah.com/whatever/create?sourceId=1
67-
68-
func createNewVersion(token: String, sourceId: String, uploadURL: URL?, completion: @escaping (Data?, URLResponse?, Error?) -> Void) {
31+
32+
func createNewVersion(token: String, sourceId: String, code: String, completion: @escaping (Data?, URLResponse?, Error?) -> Void) {
6933
guard var url = URL(string: PAPIEndpoint) else { completion(nil, nil, "Unable to create URL."); return }
70-
guard let uploadURL = uploadURL else { completion(nil, nil, "Upload URL is invalid."); return }
34+
guard !code.isEmpty else { completion(nil, nil, "Code cannot be empty."); return }
7135

7236
url.appendPathComponent(PAPI.Sources.pathEntry)
7337
url.appendPathComponent(sourceId)
@@ -77,19 +41,10 @@ extension PAPI {
7741
request.httpMethod = "POST"
7842
request.addValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
7943
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
80-
request.httpBody = "{ \"uploadURL\": \"\(uploadURL.absoluteString)\", \"sourceId\": \"\(sourceId)\" }".data(using: .utf8)
44+
request.httpBody = "{ \"code\": \"\(code)\", \"sourceId\": \"\(sourceId)\" }".data(using: .utf8)
8145

8246
let task = URLSession.shared.dataTask(with: request, completionHandler: completion)
8347
task.resume()
8448
}
85-
86-
func uploadToGeneratedURL(token: String, url: URL?, fileURL: URL?, completion: @escaping (Data?, URLResponse?, Error?) -> Void) {
87-
guard let url = url else { completion(nil, nil, "URL is nil."); return }
88-
guard let fileURL = fileURL else { completion(nil, nil, "File URL is nil."); return }
89-
var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 30)
90-
request.httpMethod = "PUT"
91-
let task = URLSession.shared.uploadTask(with: request, fromFile: fileURL, completionHandler: completion)
92-
task.resume()
93-
}
9449
}
9550
}

0 commit comments

Comments
 (0)