new-clients.mdx (SetUp - Implementing a Flipper Client)

Summary: Restyle of the page, including changes to spelling, grammar, links, and structure (where relevant).

Reviewed By: nikoant

Differential Revision: D36312999

fbshipit-source-id: 737a1f8a9dc659c7351ac55e0ccc1d4083393aa5
This commit is contained in:
Kevin Strider
2022-05-11 08:36:41 -07:00
committed by Facebook GitHub Bot
parent 242d26e199
commit 6cdda85ec9

View File

@@ -7,18 +7,19 @@ In the GitHub repo, you'll find Flipper clients for Android, iOS and C++ code, b
Flipper clients communicate with the Flipper desktop app using JSON RPC messages over a [WebSocket](https://datatracker.ietf.org/doc/html/rfc6455) connection. Flipper clients communicate with the Flipper desktop app using JSON RPC messages over a [WebSocket](https://datatracker.ietf.org/doc/html/rfc6455) connection.
This page documents the API, and you can use [FlipperConnectionManagerImpl.cpp](https://github.com/facebook/flipper/blob/main/xplat/Flipper/FlipperConnectionManagerImpl.cpp) for reference. This page documents the API. For reference, use the [FlipperConnectionManagerImpl.cpp](https://github.com/facebook/flipper/blob/main/xplat/Flipper/FlipperConnectionManagerImpl.cpp).
## Establishing a connection ## Establishing a connection
Start by connecting to the Flipper server running within the desktop app. Connecting to the server registers your application with Flipper and enables plugins to interact with it. As the Flipper desktop has a different lifecycle than your app and may connect and disconnect at any time it is important that you attempt to reconnect to the Flipper server until it accepts your connection.
We use the WebSocket protocol for communication between desktop and client, because it allows for easy certificate pinning and functionality like request-response messages. Start by connecting to the Flipper server running within the desktop app. Connecting to the server registers your application with Flipper and enables plugins to interact with it. As the Flipper desktop has a different lifecycle than your app and may connect and disconnect at any time, it's important that you continue to attempt to reconnect to the Flipper server until it accepts your connection.
The WebSocket protocol is used for communication between desktop and client because it enables easy certificate pinning and functionality, such as with request-response messages.
In order to securely connect to Flipper, your client should first [obtain a certificate](establishing-a-connection.mdx). In order to securely connect to Flipper, your client should first [obtain a certificate](establishing-a-connection.mdx).
After the client certificate has been obtained, connect to the following URL with a WebSocket client: After the client certificate has been obtained, connect to the following URL with a WebSocket client:
``` ```bash
localhost:9088/sonar?os={OS} localhost:9088/sonar?os={OS}
&device={DEVICE} &device={DEVICE}
&device_id={DEVICE_ID} &device_id={DEVICE_ID}
@@ -27,35 +28,36 @@ localhost:9088/sonar?os={OS}
&foreground={FOREGROUND} &foreground={FOREGROUND}
``` ```
**OS**: The OS which the connecting is being established from. For example `os=Android` if your client is running on Android. This is usually hard-coded into the FlipperClient implementation. This string may be used by the Flipper desktop app to identify valid plugins as well as present in the UI to the user. The URL parameters are detailed in the following table.
**DEVICE**: The name of the device running the application. For example `device=iPhone7`. | Parameter | Detail | Example |
| :-- | :-- | :-- |
**DEVICE_ID**: A unique identifier for the device. The Flipper server / desktop app may use this to coalesce multiple connections originating from the save device or present the string in the UI to differentiate between connections to different clients. | `OS` | The OS from which the connection is being established. This is usually hard coded into the FlipperClient implementation. This string may be used by the Flipper desktop app to identify valid plugins as well as present in the UI to the user. | `os=Android` (*If your client is running on Android*). |
| `DEVICE` | The name of the device running the application. | `device=iPhone7` |
**APP**: The name of the app running this client instance. For example `app=Facebook` when connecting to a running facebook app. OS + DEVICE_ID + APP should together uniquely identify a connection. | `DEVICE_ID` | A unique identifier for the device. The Flipper server / desktop app may use this to coalesce multiple connections originating from the save device or present the string in the UI to differentiate between connections to different clients. | |
| `APP` | The name of the app running this client instance. The combination of `OS` + `DEVICE_ID` + `APP` uniquely identifies a connection. | `app=Facebook` (*When connecting to a running facebook app*). |
**FOREGROUND**: A boolean indicating whether this connection was established with a foreground process. This is a hint to the Flipper desktop app of whether to re-focus on this connection or not. For example `foreground=true`. This parameter is recommended but optional. | `FOREGROUND` (Optional) | A Boolean indicating whether this connection was established with a foreground process. This is a hint to the Flipper desktop app of whether to re-focus on this connection or not. Though optional, this paramater is recommended. | `foreground=true` |
| `SDK_VERSION` | A number indicating the latest protocol version with which the client is compatible. You can find the current version in the [C++ connection implementation](https://github.com/facebook/flipper/blob/main/xplat/Flipper/FlipperConnectionManagerImpl.cpp#L37). Usually stored as a constant in the client code, this allows protocol changes to be made whilst still preserving connectivity with old clients. When Flipper desktop encounters an old SDK version, it may attempt to communicate using a matching protocol. However, backwards compatibility is not guaranteed, and you should strive to update clients on the rare occasion that the protocol version advances. | |
**SDK_VERSION**: A number indicating the latest protocol version this client is compatible with. You can find the current version in our [C++ connection implementation](https://github.com/facebook/flipper/blob/main/xplat/Flipper/FlipperConnectionManagerImpl.cpp#L37). Usually stored as a constant in the client code, this allows protocol changes to be made whilst still preserving connectivity with old clients. When Flipper desktop encounters an old SDK version, it may attempt to communicate using a matching protocol. However, backwards compatibility is not guaranteed and you should strive to update clients on the rare occasion that the protocol version advances.
## Responding to messages ## Responding to messages
Flipper uses a simple Remote Procedure Call protocol using JSON-formatted payloads. Flipper uses a simple Remote Procedure Call (RPC) protocol using JSON-formatted payloads:
The `method` field of the payload indicates which method of the FlipperClient is being called. This will always be present. * The `method` field of the payload indicates which method of the FlipperClient is being called. This will always be present.
* The `payload` field contains the JSON parameters for the method call. This may be omitted when no parameters are used.
The `payload` field contains the JSON parameters for the method call. This may be omitted when no parameters are used.
It is recommended that implementations gracefully ignore extra fields for the sake of backwards and forwards compatibility. It is recommended that implementations gracefully ignore extra fields for the sake of backwards and forwards compatibility.
Responses contain either a success object representing the return value of the RPC invocation or an error object indicating that an error occurred. Responses contain either a success object representing the return value of the RPC invocation or an error object indicating that an error occurred.
**The following methods must be implemented by all FlipperClient implementations**: ### Methods
The methods detailed in the following sub-sections must be implemented by all FlipperClient implementations.
The syntax used for these type definitions is [Flow](https://flow.org/en/docs/types/objects/). All requests/responses are JSON objects. Where no Response type is specified, it's a void call - no response is expected. The syntax used for these type definitions is [Flow](https://flow.org/en/docs/types/objects/). All requests/responses are JSON objects. Where no Response type is specified, it's a void call - no response is expected.
### getPlugins #### getPlugins
Return the available plugins as a list of identifiers. A plugin identifier is a string which is matched with the plugin identifier of desktop javascript plugins. This allows the client to specify the plugins it supports. Return the available plugins as a list of identifiers. A plugin identifier is a string which is matched with the plugin identifier of desktop javascript plugins. This allows the client to specify the plugins it supports.
```js ```js
@@ -70,8 +72,7 @@ Response = {
} }
``` ```
#### getBackgroundPlugins
### getBackgroundPlugins
Returns a subset of the available plugins returned by `getPlugin`. The background connections will automatically receive a connection from Flipper once it starts (and if the plugins are enabled), rather than waiting for the user to open the plugin. Returns a subset of the available plugins returned by `getPlugin`. The background connections will automatically receive a connection from Flipper once it starts (and if the plugins are enabled), rather than waiting for the user to open the plugin.
@@ -87,8 +88,10 @@ Response = {
} }
``` ```
### init #### init
Initialize a plugin. This should result in an onConnected call on the appropriate plugin. Plugins should by nature be lazy and should not be initialized up front as this may incur significant cost. The Flipper desktop client knows when a plugin is needed and should control when to initialize them. Initialize a plugin. This should result in an onConnected call on the appropriate plugin. Plugins should by nature be lazy and should not be initialized up front as this may incur significant cost. The Flipper desktop client knows when a plugin is needed and should control when to initialize them.
```js ```js
Request = { Request = {
"method": "init", "method": "init",
@@ -98,8 +101,10 @@ Request = {
} }
``` ```
### deinit #### deinit
Opposite of init. A call to deinit is made when a plugin is no longer needed and should release any resources. Don't rely only on deinit to release plugin resources as Flipper may quit without having the chance to issue a deinit call. In those cases, you should also rely on the WebSocket disconnect callbacks. This call is mainly for allowing the desktop app to control the lifecycle of plugins.
This is the opposite of [init](#init). A call to deinit is made when a plugin is no longer needed and should release any resources. Don't rely only on deinit to release plugin resources as Flipper may quit without having the chance to issue a deinit call. In such ases, you should also rely on the WebSocket disconnect callbacks. This call is mainly for allowing the desktop app to control the lifecycle of plugins.
```js ```js
Request = { Request = {
"method": "deinit", "method": "deinit",
@@ -109,11 +114,13 @@ Request = {
} }
``` ```
### execute #### execute
This is the main call and how the Flipper desktop plugins and client plugins communicate. When a javascript desktop plugin issues a client request it will be wrapped in one of these execute calls. This execute indicates that the call should be redirected to a plugin.
request.params.api is the plugin id. This is the main call and how the Flipper desktop plugins and client plugins communicate. When a javascript desktop plugin issues a client request, it will be wrapped in one of these execute calls. This execute indicates that the call should be redirected to a plugin:
request.params.method is the method within the plugin to execute.
request.params.params is an optional params object containing the parameters to the RPC invocation. * `request.params.api` - the plugin id.
* `request.params.method` - the method within the plugin to execute.
* `request.params.params` - an optional params object containing the parameters to the RPC invocation.
```js ```js
Request = { Request = {
@@ -134,9 +141,10 @@ Response = {
## Error Reporting ## Error Reporting
The Flipper desktop app handles error reporting so you don't have to. If an error occurs during the execution of an RPC invocation, return a serialization of it in the response so it can be attributed to the method call. The Flipper desktop app handles error reporting. If an error occurs during the execution of an RPC invocation, it returns a serialization of it in the response so it can be attributed to the method call.
If an error occurs in some other context, you can proactively send it to Flipper with the following request structure: If an error occurs in some other context, you can proactively send it to Flipper with the following request structure:
```js ```js
Request = { Request = {
error: { error: {
@@ -145,10 +153,12 @@ Request = {
} }
} }
``` ```
While in development mode, Flipper will display any client errors next to javascript errors in the Electron/Chrome DevTools console. While in development mode, Flipper will display any client errors next to javascript errors in the Electron/Chrome DevTools console.
## Testing ## Testing
Testing is incredibly important when building core infrastructure and tools. The following is pseudo code for tests we would expect any new FlipperClient implementation to implement and correctly execute. To run tests we strongly encourage you to build a mock for the WebSocket connection to mock out the desktop side of the protocol and to not have any network dependencies in your test code.
Testing is incredibly important when building core infrastructure and tools. The following is pseudocode for tests any new FlipperClient implementation is expected to implement and correctly execute. To run tests, it's strongly recommended that you to build a mock for the WebSocket connection to mock out the desktop side of the protocol and to not have any network dependencies in your test code.
```js ```js
test("GetPlugins", { test("GetPlugins", {
@@ -172,6 +182,7 @@ test("GetPlugins", {
})); }));
}); });
``` ```
```js ```js
test("InitDeinit", { test("InitDeinit", {
let connection = new MockConnection(); let connection = new MockConnection();
@@ -204,6 +215,7 @@ test("InitDeinit", {
assertFalse(plugin.connected); assertFalse(plugin.connected);
}); });
``` ```
```js ```js
test("Disconnect", { test("Disconnect", {
let connection = new MockConnection(); let connection = new MockConnection();
@@ -228,6 +240,7 @@ test("Disconnect", {
assertFalse(plugin.connected); assertFalse(plugin.connected);
}); });
``` ```
```js ```js
test("Execute", { test("Execute", {
let connection = new MockConnection(); let connection = new MockConnection();