Categories
developer documentation v0.0.27
mimik Developer Documentation
  • Tutorials
  • Working with edge microservices in an iOS project

Working with edge microservices in an iOS project

Objective

The objective of this article is to demonstrate how to use the mimik Client Library interfaces when working with edge microservices in an iOS project.

Intended Readers

The intended readers of this document are iOS software developers, who want to familiarize themselves with the basics of mimik Client Library interfaces, specifically methods for interfacing with edge microservices.

What You'll Be Doing

In this tutorial you are going to learn about topics relevant to working with the mimik Client Library edge microservice interfaces. These topics are:

  • Deploying an edge Microservice
  • Referencing an edge Microservice
  • Calling an edge Microservice
  • Updating an edge Microservice
  • Undeploying an edge Microservice

Technical Prerequisites

In order to get full benefit from this article, the reader should have a working knowledge of the following concepts and techniques:

  • A device running the latest iOS version.
  • A familiarity of working with mimik Client Library components as described in this Key Concepts article.
  • An understanding of the mimik Client Library components integration and initializiation process as layed out in this article.
  • An understanding of how to start the edgeEngine Runtime in an iOS application.
  • An understanding of how to generate an edgeEngine Access Token.
NOTE:

Working with the iOS Simulator and the mimik Client Libraries entails some special consideration. For more more information about iOS Simulator support see this tutorial.

Deploying an edge Microservice

Once the mimik Client Library has been integrated and initialized in your project, edgeEngine Runtime started and Access Token generated, we can get into the specifics of working with edge microservices.

You can think of deploying (installing) edge microservices as spinning up individual micro servers within your application. The code example below in Listing 1 shows you how to do this. A detailed explanation follows.


1: // We pass the edgeEngine Access Token required to deploy the edge microservice as a parameter. See "Creating an Access Token" in the previous tutorial
2: func deployMicroservice(edgeEngineAccessToken: String) async -> Result<EdgeClient.Microservice, NSError> {
3:
4: // Application's bundle reference to the edge microservice tar file
5: guard let imageTarPath = Bundle.main.path(forResource: "randomnumber_v1", ofType: "tar") else {
6: // Tar file not found, returning failing
7: return .failure(NSError.init(domain: "Error", code: 404))
8: }
9:
10: // edge microservice deployment configuration object with example values
11: let config = EdgeClient.Microservice.Config(imageName: "randomnumber-v1", containerName: "randomnumber-v1", basePath: "/randomnumber/v1", envVariables: ["some-key": "some-value"])
12:
13: // Calling mimik Client Library method to deploy the edge microservice
14: switch await self.edgeClient.deployMicroservice(edgeEngineAccessToken: edgeEngineAccessToken, config: config, imageTarPath: imageTarPath) {
15: case .success(let microservice):
16: print("Success", microservice)
17: // Call successful, returning success with the deployed edge microservice object reference
18: return .success(microservice)
19: case .failure(let error):
20: print("Error", error.localizedDescription)
21: // Call unsuccessful, returning failure
22: return .failure(error)
23: }
24: }

Listing 1: Deploying an edge microservice


First, we establish a file path to where the edge microservice is stored within the application's bundle at Lines 5-8. In this example, the edge microservice is represented by a randomnumber_v1.tar file according to the Bundle.main.path(forResource: "randomnumber_v1", ofType: "tar") statement at Line 5.

Next, we create a configuration object using the function EdgeClient.Microservice.Config() at Line 11. This configuration object describes the edge microservice deployment parameters. The example code in Listing 1 is configured with some hard-coded values as shown on Line 11. In a production setting, you'd want to put these values somewhere in a loadable configuration file.

Then, we call the deployMicroservice() method of the mimik Client Library at Line 14 which requires the following parameters:

  • edgeEngineAccessToken
  • config
  • imageTarPath

WHERE

edgeEngineAccessToken is the edgeEngine Access Token we generated in the "Creating an Access Token" section of the previous tutorial.

config is a configuration object describing the edge microservice deployment parameters Line 11.

imageTarPath is a file path to where the edge microservice is stored within the application's bundle Lines 5-8.

After the call, we validate the result at Lines 15-23.

If the deployment was successful, we get a reference object to the deployed edge microservice at Line 15. Developer can either keep a reference to this object or get it again as needed later, as described in the next section below. In the last of Listing 1, we return the reference to the edge microservice as an object at Line 18.

If there was an issue, we return a failure at Line 22.

At this point we are done, the edge microservice has been successfully deployed and is now functional and responding to calls.

Take a moment to review the statements in the code above using these comments as your guide.

NOTE:
Once an edge microservice is deployed to the edgeEngine Runtime, its lifecycle gets tied to the edgeEngine Runtime, starting up and shutting down along with it.
NOTE:
Each edge microservice provides a set of interfaces, allowing edge microservice developers to develop and deploy cross-platform solutions. This is because the same edge microservice can be deployed to other platforms as well.

Referencing edge microservice

After edge microservice deployment, we will want to start calling its endpoints to do the work. Since the endpoint uses http communication protocols, we will need to establish a URL to reach it. There are several ways to accomplish this, but for the learning purposes of this tutorial, we will establish this URL using an edge microservice object reference. The code example below in Listing 2 shows how to do this. A detailed explanation follows the code listing.


1: // We pass the edgeEngine Access Token required to list the deployed the edge microservice as a parameter. See "Creating an Access Token" in the previous tutorial
2: func deployedMicroservices(edgeEngineAccessToken: String) async -> Result<[EdgeClient.Microservice], NSError> {
3:
4: // Calling mimik Client Library method to get the deployed edge microservice references
5: switch await self.edgeClient.deployedMicroservices(edgeEngineAccessToken: edgeEngineAccessToken) {
6: case .success(let microservices):
7:
8: // Guarding against the array being empty.
9: guard !microservices.isEmpty else {
10: print("Success, but no deployed edge microservices found")
11: // Call successful, but there were no deployed edge microservices found. Returning a success with the empty array
12: return .success(microservices)
13: }
14:
15: for microservice in microservices {
16: // Attempting to establish a url to the deployed edge microservice /randomNumber endpoint
17: guard let url = microservice.fullPathUrl(withEndpoint: "/randomNumber")?.url else {
18: print("Error")
19: // Unable to establish the full path url to the deployed edge microservice endpoint
20: continue
21: }
22:
23: // Printing the full path url of the deployed edge microservice endpoint
24: print("Success", url)
25: }
26:
27: print("Success")
28: // Call successful, returning a success with an array of deployed edge microservice references
29: return .success(microservices)
30:
31: case .failure(let error):
32: print("Error", error.localizedDescription)
33: // Call unsuccessful, returning error
34: return .failure(error)
35: }
36: }

Listing 2: Referencing an edge microservice


First, we call the deployedMicroservices() method of the mimik Client Library at Line 5, which requires the parameter edgeEngineAccessToken

WHERE

edgeEngineAccessToken is the edgeEngine Access Token we generated in the "Creating an Access Token" section of the previous tutorial.

After the call, we do result-validation checks at Lines 6 and 31.

If the call was successful, but no edge microservices were found, we return a success with an empty array at Line 12. If there was an issue, we return a failure at Line 34.

If some edge microservice were found, we start iterating over the array of their references at Lines 15-25.

For learning purposes of this article, while iterating, we attempt to establish a full path URL to an edge microservice endpoint called /randomNumber at Line 17. For now, we just print the value to the console log at Line 24. In the next section, we will be actively capturing and using this value to make our http call to the edge microservice endpoint.

Take a moment to review the statements in the code above using these comments as your guide.

Calling edge microservice

Once we have established the URL to the deployed edge microservice endpoint, we can start making http calls to it. The code example below in Listing 3 shows how to do this. A detailed explanation follows the code listing.


1: import Alamofire
2:
3: // We pass the edgeEngine Access Token required to list the deployed edge microservices as a parameter. See "Creating an Access Token" in the previous tutorial
4: func callMicroservice(edgeEngineAccessToken: String) async -> Result<Any, NSError> {
5:
6: // Getting a reference to the full path url of the deployed edge microservice endpoint
7: guard case let .success(microservices) = await self.edgeClient.deployedMicroservices(edgeEngineAccessToken: accessToken),
8: let url = microservices.first?.fullPathUrl(withEndpoint: "/randomNumber")?.url else {
9: print("Error")
10: // Call unsuccessful, returning a failure
11: return .failure(NSError.init(domain: "Error", code: 404))
12: }
13:
14: // In the case of our example edge microservice, the endpoint requires authentication. We will use the edgeEngine Access Token here.
15: let httpHeaders = HTTPHeaders(["Authorization" : "Bearer \(edgeEngineAccessToken)"])
16:
17: // Alamofire request call to the endpoint's full path url, with serialization of a Decodable Int value
18: let dataTask = AF.request(url, headers: httpHeaders).serializingDecodable(Int.self)
19: guard let value = try? await dataTask.value else {
20: print("Error")
21: // Response value serialization unsuccessful, returning a failure
22: return .failure(NSError.init(domain: "Error", code: 500))
23: }
24:
25: // Response value serialization successful, returning success with the serialized value
26: print("Success. value:", value)
27: return .success(value)
28: }

Listing 3: Calling edge microservice


To simplify the code, we will use an established Swift networking library called Alamofire to make the call. Since the Alamofire library is already a dependency of the mimik Client Library, it is made available to our iOS project as part of the CocoaPods dependency manager automatically.

First, we make the Alamofire library available to our class, by importing it on Line 1.

Next, we get a reference to the full path URL of the deployed edge microservice endpoint at Lines 5-10. We are simplifying the example code, by simply getting a reference to the first edge microservice we receive in the array. In a production application, you'd want to do additional checks, to make sure that the correct edge microservice has been selected especially if there are multiple edge microservices deployed.

Then, we setup the http headers on Line 16 to pass the edgeEngine Access Token as the Bearer Authorization http headers parameter.

At this point, we are ready to use the request() method of the Alamofire Library to make the http call to the edge microservice endpoint.

We set the following parameters of the request() method:

  • url
  • headers

WHERE

url is the full path url to the endpoint of the deployed edge microservice. See here

headers are optional HTTP headers values that we might want to include in the http call. In our example, we include the Bearer Authorization header to demonstrate how to pass authorizations to an endpoint

NOTE:
There are other components that you might want to include in your http call. Please see the Alamofire library documentation for more information.

Once the http call is made, we do a validation check to make sure that we get the expected response on Lines 17-25. In our example, we are expecting an Int value in the response.

If there is an issue, we return a failure on Line 20.

When all is good, and an Integer value is received, we return a success with the said value on Line 25.

Take a moment to review the statements in the code above using these comments as your guide.

Updating an edge microservice

As an iOS developer, you might be asked to update an already deployed edge microservice. For example, when the edge microservice developer releases a new version that might include bug fixes or new features.

There are two ways to update an already deployed edge microservice.

You could re-deploy the same edge microservice from a new, changed .tar file. You have to be careful, though, to use exactly the same configuration that was used during the initial deployment. This is so that you don't end up with two instances of the same edge microservice. (You're free to change the environment variables.)

Instead, you should safely use the updateMicroservice() method of the mimik Client Library. Using this method guarantees that only the specifically selected edge microservice is updated.

The code example below in Listing 4 shows you the recommended, safer way of updating an already deployed edge microservice. A detailed explanation follows the code example.


1: // We pass the edgeEngine Access Token required to update the deployed edge microservices as a parameter. See "Creating an Access Token" in the previous tutorial
2: func updateMicroservice(edgeEngineAccessToken: String) async -> Result<EdgeClient.Microservice, NSError> {
3:
4: // Getting a reference to the full path url of the deployed edge microservice endpoint
5: guard case let .success(microservices) = await self.edgeClient.deployedMicroservices(edgeEngineAccessToken: accessToken), let microservice = microservices.first else {
6: // Call unsuccessful, returning a failure
7: print("Error")
8: return .failure(NSError.init(domain: "Error", code: 500))
9: }
10:
11: // Application's bundle reference to the edge microservice tar file
12: guard let imageTarPath = Bundle.main.path(forResource: "randomnumber_v1", ofType: "tar") else {
13: // Tar file not found, returning failing
14: print("Error")
15: return .failure(NSError.init(domain: "Error", code: 404))
16: }
17:
18: // Calling mimik Client Library method to update the selected edge microservice
19: switch await self.edgeClient.updateMicroservice(edgeEngineAccessToken: accessToken, microservice: microservice, imageTarPath: imageTarPath, envVariables: ["some-new-key": "some-new-value"]) {
20: case .success(let microservice):
21: print("Success", microservice)
22: // Call successful, returning success with the updated edge microservice reference
23: return .success(microservice)
24: case .failure(let error):
25: print("Error updating microservice", error.localizedDescription)
26: // Call unsuccessful, returning failure
27: return .failure(NSError.init(domain: "Error", code: 500))
28: }
29: }

Listing 4: Updating an edge microservice


First, we get an object reference to the already deployed edge microservice on Lines 5-10. We are simplifying the example code, by simply getting a reference to the first edge microservice we receive in the array. In a production application, you'd want to do additional checks, to make sure that the correct edge microservice has been selected. Especially, if there are multiple edge microservices deployed.

Next, we establish a file path to where the new, updated edge microservice is stored within the application bundle at Lines 13-17. This example edge microservice is represented by a new, updated randomnumber_v2.tar file.

Then, we call the updateMicroservice() method of the mimik Client Library, which requires the following parameters:

  • edgeEngineAccessToken
  • microservice
  • imageTarPath
  • envVariables

WHERE

edgeEngineAccessToken is the edgeEngine Access Token we generated in the "Creating an Access Token" section of the previous tutorial.

microservice is the object reference to the deployed edge microservice Lines 5-8 in Listing 4 above.

imageTarPath is a file path to where the new, updated edge microservice is stored within the application's bundle Lines 12-17

envVariables are any environment configuration values for the edge microservice. All need to be explicitly set, every time.

After the call, we validate the result at Lines 17-27.

If the edge microservice update is successful, we get a reference object to the updated edge microservice at Line 22. You can either keep a reference to this object or get it again as needed. We return a success with this reference at Line 24.

If there is an issue, we return an failure at Line 27.

At this point we are done, the edge microservice has been successfully updated.

Take a moment to review the statements in the code above using these comments as your guide.

Undeploying an edge microservice

Sometimes there is a need to undeploy (uninstall) an edge microservice from the edgeEngine Runtime. The code example below in Listing 5 shows how to accomplish this. A detailed discussion follows the code example.


1: // We pass the edgeEngine Access Token required to update the deployed edge microservices as a parameter. See "Creating an Access Token" in the previous tutorial
2: func undeployMicroservice(edgeEngineAccessToken: String) async -> Result<Void, NSError> {
3:
4: // Getting a reference to the full path url of the deployed edge microservice endpoint
5: guard case let .success(microservices) = await self.edgeClient.deployedMicroservices(edgeEngineAccessToken: accessToken), let microservice = microservices.first else {
6: // Call unsuccessful, returning a failure
7: print("Error")
8: return .failure(NSError.init(domain: "Error", code: 500))
9: }
10:
11: // Calling mimik Client Library method to undeploy the selected edge microservice
12: switch await self.edgeClient.undeployMicroservice(edgeEngineAccessToken: accessToken, microservice: microservice) {
13: case .success:
14: print("Success")
15: // Call successful, returning a success
16: return .success(())
17: case .failure(let error):
18: print("Error", error.localizedDescription)
19: // Call unsuccessful, returning a failure
20: return .failure(NSError.init(domain: "Error", code: 500))
21: }
22: }

Listing 5: Undeploying an edge microservice


First, we get an object reference to the deployed edge microservice on Lines 3-8. We are simplifying the example code, by simply getting a reference to the first edge microservice we receive in the array. In a production application, you'd want to do additional checks to make sure that the correct edge microservice has been selected especially if there are multiple edge microservices deployed.

Then, we call the undeployMicroservice() method of the mimik Client Library, which requires the following parameters:

  • edgeEngineAccessToken
  • microservice

WHERE

edgeEngineAccessToken is the edgeEngine Access Token we generated in the "Creating an Access Token" section of the previous tutorial.

microservice is the object reference to the deployed edge microservice Line 4

After the call, we validate the result at Lines 10-20

If the edge microservice undeployment is successful, we return a success at Line 15. If there is an issue, we return a failure at Line 19.

At this point we are done, the edge microservice has been successfully undeployed and is no longer functional.

Take a moment to review the statements in the code above using these comments as your guide.

Example Xcode project

You can download a fully functional example of an iOS application, showing all the functions discussed in the three iOS tutorials here. Download the project, run it on your iOS device and see all functions in action right away!

Was this article helpful?

© mimik technology, Inc. all rights reserved