# Quick Guide for API Gateway Switch

## Overview

<div class="docs-note"><span class="docs-admonitions-text">note</span>

The App Framework provided in this documentation is exclusively designed for use within the specific application referenced herein. It is not intended for the development of new tenant applications. Any attempt to extend or modify the framework for use in other projects or environments is not recommended.Please ensure that the framework is only utilized for its intended purpose within the specified application.

</div>

### Why Do We Need this Switchover?

To enable scalable growth, enhance security, and promote ecosystem expansion, we have decided to adopt a new service invocation model and API gateway.

This switchover will allow us to:

- Support flexible deployment option - the multi-namespace solution when we scale up.
    - The service name will not conflict across tenants/namespaces.
    - One physical insureMO site (environment) can host multi-namespace of tenant services, satisfying tenants's multi-state/multi-phase requirements.
- Improve security for platform multi-tenancy services.
    - BFFs can call platform APIs through the API gateway using an authorization token.
    - BFFs can only access dedicated middleware, which will not influence other tenant’s, e.g. RabbitMQ.
- Enable external partner development.
    - Remove dependency of service registry server, i.e. the Eureka Server.
    - Partners can develop the application locally from anywhere, eliminating the need for insureMO's VM and network resources.

![Untitled](image/gateway_switch/Untitled.png)

<aside>

All services share the same service registry center (eureka), but there may be conflicts in service names across tenants. Service calls are based on the Spring Cloud service discovery and client-side load balancing, which may not be flexible for deployment adjustments.

</aside>

![Untitled](image/gateway_switch/Untitled%201.png)

### How Do We Handle the Switchover?

This switch will be done in two stages.

- Preparation stage
    - Changes need to be made in both code and configuration properties.
    - The application continues to work normally in the old model.
- Performing switchover

The switchover mainly involves the following stakeholders.

- Tenant/Project
    - Frontend UI Developers
        - Mainly responsible for checking and modifying the API URL stitching logic within the UI.
    - Backend Service Developers
        - Mainly responsible for checking code in BFF services and making necessary modifications.
        - After switching to the new model, additional environment variables need to be configured when initiating services locally.
    - Tenant Manager/Project Manager
        - Planning and scheduling of changes should be done in the preparation stage.
        - Coordination for the switchover needs to be applied in different environments, such as DEV, TST, UAT, PROD.
- CM/TS/SiteOps
    - Configure static routes for existing BFF services.
    - Setup public-external properties for the tenant. 
    - Perform the switchover to the new model.

### Impact Analysis

The switch will change the API URL under the application domain. Kindly **pay special attention** if you:

- Have shared the API URL with customers or third parties for integration. In this case, please notify the **insureMO SiteOps & PBU Team** accordingly.
- Call the API in Postman collections or API test tools. Please adjust the URL accordingly.

    - Old API URL Format - `https://{app-env-domain}/service-name/api-path`.

        Examples:

        ```bash
        // tenant BFF API
        https://tenantcode***.insuremo.com/pa-bff-app/v1/calculation

        // platform API
        https://tenantcode***.insuremo.com/dd/public/codetable/v1/data/list/byName
        ```

    - New API URL Format - `https://{app-env-domain}/api/{segment}/service-name/api-path`.
   
        <div class="docs-tip"><span class="docs-admonitions-text">tip</span>
        
        The `{segment}` is also referred as the vendor code in API Management.

        </div>

        Examples:

        ```bash
        // tenant BFF API
        https://tenantcode***.insuremo.com/api/tenantCode/pa-bff-app/v1/calculation

        // platform API
        https://tenantcode***.insuremo.com/api/platform/dd/public/codetable/v1/data/list/byName
        ```

## Preparation Stage

### Code Updates of UI App Based on the RainbowUI

Upgrade the RainbowUI component to the latest minor version.

<div class="docs-note"><span class="docs-admonitions-text">note</span>

Compatible with both RainbowUI 4.0 and RainbowUI 5.0.

</div> 

Check the code of the API URL building logic, using `UrlUtil.getConfigUrl`.

```bash
//rainbow 4.0
import { UrlUtil } from 'rainbow-desktop-tools';
//rainbow 5.0
import { UrlUtil } from '@insuremo/rainbowui-sugar-tools';

//Common writing method 1 (standard use):
const langUrl = UrlUtil.getConfigUrl('UI_API_GATEWAY_PROXY', 'USER', 'GET_USER_LANG');

//Common writing method 2:
const langUrl = UrlUtil.getConfigUrl('UI_API_GATEWAY_PROXY')+'urp/public/users/v1/getlang';
//update:
const langUrl = UrlUtil.getConfigUrl(UrlUtil.getConfigUrl('UI_API_GATEWAY_PROXY') + 'urp/public/users/v1/getlang');

//Common writing method 3:
const langUrl = config.UI_API_GATEWAY_PROXY+'urp/public/users/v1/getlang';
//update:
const langUrl = UrlUtil.getConfigUrl(config.UI_API_GATEWAY_PROXY + 'urp/public/users/v1/getlang');
```

### Code Updates of Service App Based on App Framework

Because there is a vela version check in the BFF service build job, we suppose you’ve upgraded the vela dependency to the latest major version. 

It is recommended to upgrade **vela.all.version** in BFF `pom.xml` to **23.03.192** or above.

#### Check Configuration Properties

The following configuration properties are intended for platform services (note that they are actually deprecated).

- Search for `container.print` within the BFF services’ source code.

   Configure them in the `application.properties` of BFF services if necessary.

    ```bash
    container.print.task.execute=http://gateway.ebao/eBao/1.0/printtask/execute
    container.print.submit=http://gateway.ebao/eBao/1.0/rendertasks/new
    container.print.content=http://gateway.ebao/eBao/1.0/rendertasks/{id}/result
    container.print.create=http://gateway.ebao/eBao/1.0/reporttemplates/new
    container.print.submitjson=http://gateway.ebao/eBao/1.0/rendertasks/new/json
    container.print.task.create=http://gateway.ebao/eBao/1.0/printtask/create
    ```

- Search for `container.upload` within the BFF services’ source code.

  Configure them in the `application.properties` of BFF services if necessary.

    ```bash
    container.upload=http://gateway.ebao
    container.upload.file.url=http://gateway.ebao/zuul/data-collection-service/dc/pa/file/upload
    container.upload.status.query.url=http://gateway.ebao/zuul/data-collection-service/dc/pa/file/query
    ```

- Search for `container.workflow` within the BFF services’ source code.

  Configure them in the `application.properties` of BFF services if necessary.

    ```java
    container.workflow.assign.service=http://gateway.ebao/v1/tasks/{taskId}/assign
    container.workflow.complete.service=http://gateway.ebao/v1/tasks/{taskId}/complete
    container.workflow.load.service=http://gateway.ebao/v1/tasks/{taskId}
    container.workflow.query.service=http://gateway.ebao/v1/tasks?page={page}&size={size}
    container.workflow.start.service=http://gateway.ebao/v1/process-instances
    container.workflow.update.service=http://gateway.ebao/v1/tasks/variables
    ```

#### Check Tenant Code

Check the tenant code within the properties and code, ensuring that it is not hard code.

Find and update properties inside `bootstrap.properties` to the following format. Replace the tenant code with yours.

```bash
spring.cloud.config.enabled=false
config.server=${CONFIG_SERVER:container}
ebao.tenant.code=${TENANT_CODE:ebaogi}

eureka.client.serviceUrl.defaultZone=${EUREKA_URL:[http://eureka-server.platform/eureka](http://eureka-server.platform/eureka)}
```

<aside>
💡 Replace with your actual tenant code.

</aside>

#### Check Your Service Call API Paths

When constructing your service call API paths, it's crucial to avoid embedding tenant codes or namespaces within them. 

Examples:

-   Incorrect pattern

    ```java
    // call service of platform directly
    http://proposal-v2.platform

    // call service with namespace within the same tenant app
    http://nb-bff-app.tenant
    ```

-   Correct pattern

    ```java
    // call service within the same tenant app
    http://nb-bff-app
    ```

#### Check Your RESTful API Client

Ensure proper utilization of the App Framework's RestTemplate in your RESTful API client. Avoid specifying tokens in request headers.

```java

// For platform API, e.g. http://urp/xxx
@Qualifier("restTemplateWithLoadBalance")

// For container API, e.g. http://gateway.ebao/eBao/1.0/email/xxx
@Qualifier("origRestTemplateForContainerCall")

```

#### Update Dockerfile-Dbasset

Update the Dockerfile-dbasset to remove the tenant code and ensure its proper deployment as follows.

```bash
FROM docker-all.repo.ebaotech.com/platform/lambda-dbasset-dispatcher:2.2.0
COPY target/*-dbasset.zip /exec/data/
```

#### Deploy Code Updates and Properties

Ensure that all code changes and Config Center properties are properly deployed.

### Configuration Onboarding Tasks

#### Static Route Configuration and Deployment

- Platform static routes have been deployed. → PBU.

  To learn more about static route configuration, see [Static Route Guide](https://docs.insuremo.com/common/doc_00000321). 

- Tenant static routes have been configured and deployed. → TS/Tenant.

    To verify the static routes in the runtime environment, use the following requests:

    ```bash
    // verify platform static routes, replace the domain with **runtime gateway domain**
    curl --location 'https://tenantcode***.insuremo.com/platform/platform-pub/public/cache/v1/all'

    // verify tenant static routes, replace the domain with **runtime gateway domain**, and replace the trialzone6 with **tenant** **code**,
    curl --location 'https://tenantcode***.insuremo.com/**trialzone6**/appframework-bff-app/public/cache/v1/all'
    ```

    <div class="docs-tip"><span class="docs-admonitions-text">tip</span>

    If the above requests do not return a 404 response (they may return a 401), then the static route is working correctly.

    </div>

#### Public-external Onboarding and API Permissions

The dedicated MQ virtual host, username, password for the tenant have been created. → TS

A tenant-related placeholder (shadow) has been added under the public-external onboarding. → CM/TS

MQ-related parameters/env variables have been set to the tenant. → TS

The above configuration properties have been deployed into the runtime environment. → CM

The platform tenant-common APIs have been granted to the tenant in the runtime environment.  → CM

The container configuration API (`/api/key`) have been granted to the tenant in the DEV environment. → CM

To verify the public-external onboarding and API permissions, use the following requests:

```bash
// check configuration properties of platform tenant common, replace the authorization token with the tenant long token.
curl --location 'https://tenantcode***.insuremo.com/platform/1.0/config/v1/tenant/common' \
--header 'Authorization: Bearer ****'

```

#### Boot-Admin Deployment

Boot-admin k8s have been deployed to tenant namespace. → TS

Boot-admin can be accessed through tenant app domain. → TS


## Performing Switchover

The switchover will be executed by TS, adhering to the following steps.

1. Add the tenant into the platform's configuration env values: `/platform/env_values/{env}/platform/TENANT_GATEWAY_SWITCHED`.
2. Traefik routing to the platform service and UI.
3. Append the `insuremo_gw_url` and `insuremo_access_token` to the environment info.
4. Deploy the platform configuration data into the runtime environment.
5. Re-deploy the tenant services.

To verify the successful execution of the switchover, use the following request:

```bash
// verify platform api, replace the domain with **runtime tenant app domain**
curl --location 'https://tenantcode***.insuremo.com/api/platform/platform-pub/public/cache/v1/all'
```

<div class="docs-tip"><span class="docs-admonitions-text">tip</span>

If the above request does not return a 404 response (it may return a 401), then the switchover is complete.

</div>

Furthermore, if you log in to and access the application's UI page, open the developer tools and check the network. There, you will see the API request URL that include the `/api/segment`. 

![Untitled](image/gateway_switch/Untitled%205.png)


## Development Locally

The switchover will not impact the local development. For back-end app developers, the only prerequisite is the configuration of a few environment variables.

For further details, see [Development Locally](https://docs.insuremo.com/common/doc_00000007)