Microservice

Microservice is a piece of independent service which can be be host on a remove server. Microservice must have a communication API.

Turn on/off microservice feature

`Admin panel/System/Settings/Option`

Example-01: Call local or remote microservice

At first create a microservice from admin panel `Admin panel/Extensions/Microservices`

<?php
try {
        $customer_info = $this->microservice->from('backend')->call('module_customer',
                function($server, $seo_url) { // Remote
                        $request_data = array(
                                'customer_id' => 1,
                        );
                        return $this->api->for('backend')->url($server, 'extension/module/customer/api/index/getCustomer', $request_data, $seo_url)->simplePost()->json()['payload'];
                },
                function($server, $seo_url) { // Fallback in Local
                        $this->load->modelFrom('module', 'customer', 'customer');
                        return $this->model_customer->getCustomer(1);
                },
        );

        dd($customer_info);

} catch (Exception $e) {

        dd($e->getMessage());
}

Example-02: Call microservice fron javascript

$http({
    url: API_URL + "index.php?route=common/microservice/request&user_token=" + token,
    method: "POST",
    data: "for=backend&method=post&service=module_customer&url=extension/module/customer/api/index/getCustomFieldValues&customer_id=" + customer.id,
    cache: false,
    processData: false,
    contentType: false,
    dataType: "json"
}).
then(function(res) {
    console.log(res);
}, function(res) {
    window.toastr.error(res.data.errorMsg, "Oops!");
});

Extension vs Microservice Extension always installed on local server and called from local. Microservice installed on local or remote server.

Request to a python microservice

How to run: `FLASK_APP=application.py flask run`

At first create a microservice from admin panel `Admin panel/Extensions/Microservices`

Type: module
Code: python
Name: Module Paython

Backend
        Seo Url: Yes
        Server: http://127.0.0.1:5000/backend

Frontend
        Seo Url: Yes
        Server: http://127.0.0.1:5000

Calling microservice from PHP

try {
        $res = $this->microservice->from('backend')->call('module_python',
                function($server, $seo_url) { // Remote
                        $input = array('id' => 99);
                        $api_res = $this->api->for('backend')->url($server, '/UserInfo', $input, $seo_url)->simplePost()->json();
                        dd($api_res);                           },
                function($server, $seo_url) { // Fallback in Local
                        dd('No data from microservice');
                },
        );
        dd($res);
} catch (Exception $e) {
        dd($e->getMessage());
}
```File name: application.py```

import random
from flask import Flask, render_template, request, jsonify

import base64
import hmac
import hashlib
import time

app = Flask(__name__)

@app.route("/")
def index():
    number = random.randint(0,1)
    return render_template("index.html", name="Najmul", number=number)

@app.route("/goodbye")
def bye():
    return "Goodbye!"

@app.route("/hello")
def hello():
    name = request.args.get("name")
    if not name:
        return render_template("failure.html")
    return render_template("hello.html", name=name)

@app.route("/backend/UserInfo", methods=["POST"])
def UserInfo():
    id = request.form.get("id")

    domain = request.args.get("domain")
    version = request.args.get("version")
    time = request.args.get("time")
    signature = request.args.get("signature")
    secret = "7p3Qyf3BeCXUD2wsd5vUsVdXwiNBFM4oo1lWE8hPu27KZn6OXC6fXQoAHaEE0VWWtkKHx8tXgfTAT0PaplSEzca8US1oKgZ2KHCAdXlMbICcsAaQyngRO5p62WdmMI2ZzKQB3aOMt5VpM0tekA9yYQ0iZIE6RKxQhqxloRM3iQXZB7BJWtubzNye10pkjqfoxIoOvSnUdpO43TJhzZDwjPNEv3sr3eVruANj3qGHRqL23MEBqqbJh6ig8GEAM3RinpnlSJEWKjmCUWxqnBA885DNg38pAOTzYPrWpUa1IhHFylBuKl5QaE4iIL7OT19cOJJLIDFzsR4mXzsLNG8RjJ5GHvkpNGI4yMfYR3I5a1P1oPkhNt9rXf2mM2EE5G9vm5V7bpqFeruBxKKfArp2bwT06mS3W94dVywZMhUApqHkTuz9e24CJTHmghmB8ARCpIiLbpX0tDZ0AS1vvLixkvWqnIKYk7aNQW3RQLOzPEPKV5fDg4G87Aw8Hr02mPKG"

    uri = "/UserInfo";
    sign = uri + "\n" + domain + "\n" + str(version) + "\n" + str(time) + "\n"
    new_signature = base64.b64encode(hmac.new(secret.encode(), sign.encode(), hashlib.sha1).digest()).decode()
    if not hmac.compare_digest(signature, new_signature):
        return jsonify(status='error',text='Un-authorized request!')
    return jsonify(
        id=id,
        username='Najmul',
        email='techbuzz69@gmail.com',
        domain=domain,
        version=version,
        time=time,
        signature=signature,
        new_signature=new_signature,
    )

Response

"{\"domain\":\"127.0.0.1:8888\",\"email\":\"techbuzz69@gmail.com\",\"id\":\"99\",\"new_signature\":\"r6GcJ8DvH+RtqpM0d63OMgrYgDI=\",\"signature\":\"r6GcJ8DvH+RtqpM0d63OMgrYgDI=\",\"time\":\"1654770656\",\"username\":\"Najmul\",\"version\":\"1.0.0\"}\n"

Breathing

`php cli app:breathing backend` `php cli app:breathing frontend`

Use breathing while calling microservice

Enale status checking before calling microservic `Admin panel/System/Settings/Option`