@ibm-cloud/cloudant 0.5.4 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
  [![Release](https://img.shields.io/github/v/release/IBM/cloudant-node-sdk?include_prereleases&sort=semver)](https://github.com/IBM/cloudant-node-sdk/releases/latest)
3
3
  [![Docs](https://img.shields.io/static/v1?label=TypeDoc&message=latest&color=blue)](https://ibm.github.io/cloudant-node-sdk/)
4
4
 
5
- # IBM Cloudant Node.js SDK Version 0.5.4
5
+ # IBM Cloudant Node.js SDK Version 0.6.0
6
6
 
7
7
  IBM Cloudant Node.js SDK is a client library that interacts with the
8
8
  [IBM Cloudant APIs](https://cloud.ibm.com/apidocs/cloudant?code=node).
@@ -32,14 +32,15 @@ to avoid surprises.
32
32
  - [Features](#features)
33
33
  - [Prerequisites](#prerequisites)
34
34
  - [Installation](#installation)
35
- - [Authentication](#authentication)
36
- * [Authentication with environment variables](#authentication-with-environment-variables)
37
- + [IAM authentication](#iam-authentication)
38
- + [Session cookie authentication](#session-cookie-authentication)
39
- + [Basic authentication](#basic-authentication)
40
- * [Authentication with external configuration](#authentication-with-external-configuration)
41
- * [Programmatic authentication](#programmatic-authentication)
42
35
  - [Using the SDK](#using-the-sdk)
36
+ * [Authentication](#authentication)
37
+ + [Authentication with environment variables](#authentication-with-environment-variables)
38
+ - [IAM API key authentication](#iam-api-key-authentication)
39
+ - [IAM Trusted profile (container) authentication](#iam-trusted-profile-container-authentication)
40
+ - [IAM Trusted profile (VPC) authentication](#iam-trusted-profile-vpc-authentication)
41
+ - [Session cookie authentication](#session-cookie-authentication)
42
+ + [Authentication with external configuration](#authentication-with-external-configuration)
43
+ + [Programmatic authentication](#programmatic-authentication)
43
44
  * [Request timeout configuration](#request-timeout-configuration)
44
45
  * [Code examples](#code-examples)
45
46
  + [1. Create a database and add a document](#1-create-a-database-and-add-a-document)
@@ -50,6 +51,22 @@ to avoid surprises.
50
51
  * [Error handling](#error-handling)
51
52
  * [Raw IO](#raw-io)
52
53
  * [Further resources](#further-resources)
54
+ * [Changes feed follower (beta)](#changes-feed-follower-beta)
55
+ + [Introduction](#introduction)
56
+ + [Modes of operation](#modes-of-operation)
57
+ + [Configuring the changes follower](#configuring-the-changes-follower)
58
+ + [Error suppression](#error-suppression)
59
+ + [Follower operation](#follower-operation)
60
+ + [Checkpointing](#checkpointing)
61
+ + [Code examples](#code-examples-1)
62
+ - [Initializing a changes follower](#initializing-a-changes-follower)
63
+ - [Starting the changes follower](#starting-the-changes-follower)
64
+ * [Start mode for continuous listening](#start-mode-for-continuous-listening)
65
+ * [Start mode for one-off fetching](#start-mode-for-one-off-fetching)
66
+ - [Processing changes](#processing-changes)
67
+ * [Process continuous changes](#process-continuous-changes)
68
+ * [Process one-off changes](#process-one-off-changes)
69
+ - [Stopping the changes follower](#stopping-the-changes-follower)
53
70
  - [Questions](#questions)
54
71
  - [Issues](#issues)
55
72
  - [Open source at IBM](#open-source-at-ibm)
@@ -85,6 +102,7 @@ project:
85
102
  - Handles the authentication.
86
103
  - Familiar user experience with IBM Cloud SDKs.
87
104
  - Flexibility to use either built-in models or byte-based requests and responses for documents.
105
+ - Built-in [Changes feed follower](#changes-feed-follower-beta) (beta)
88
106
  - `Promise` based design with asynchronous HTTP requests.
89
107
  - Use either as native JavaScript or take advantage of TypeScript models.
90
108
  - Transparently compresses request and response bodies.
@@ -98,96 +116,130 @@ project:
98
116
  server.
99
117
  - Node.js 16 or 18.
100
118
 
119
+
101
120
  ## Installation
102
121
 
103
122
  ```sh
104
123
  npm install @ibm-cloud/cloudant
105
124
  ```
106
125
 
107
- ## Authentication
126
+
127
+ ## Using the SDK
128
+
129
+ For fundamental SDK usage information and config options, please see the common [IBM Cloud SDK](https://github.com/IBM/ibm-cloud-sdk-common/blob/main/README.md) documentation.
130
+
131
+ This library requires configuration with a service URL and
132
+ [Cloudant service credentials][service-credentials] to authenticate with your
133
+ account.
134
+
135
+ There are several ways to **set** these authentication properties:
136
+
137
+ 1. As [environment variables](#authentication-with-environment-variables)
138
+ 1. The [programmatic approach](#programmatic-authentication)
139
+ 1. With an [external credentials file](#authentication-with-external-configuration)
140
+
141
+ The following section describes the different authentication types and provides environment variable examples.
142
+ Examples for other configuration methods are available by following the provided links.
143
+
144
+ ### Authentication
108
145
 
109
146
  [service-credentials]: https://cloud.ibm.com/docs/Cloudant?topic=Cloudant-locating-your-service-credentials
110
147
  [cloud-IAM-mgmt]: https://cloud.ibm.com/docs/Cloudant?topic=Cloudant-managing-access-for-cloudant#introduction-iam-ai
111
148
  [couch-cookie-auth]: https://docs.couchdb.org/en/stable/api/server/authn.html#cookie-authentication
112
149
  [cloudant-cookie-auth]: https://cloud.ibm.com/docs/Cloudant?topic=Cloudant-work-with-your-account#cookie-authentication
113
150
  [couch-basic-auth]: https://docs.couchdb.org/en/stable/api/server/authn.html#basic-authentication
151
+ [couch-jwt-auth]: https://docs.couchdb.org/en/stable/api/server/authn.html#jwt-authentication
114
152
  [cloudant-basic-auth]: https://cloud.ibm.com/docs/Cloudant?topic=Cloudant-work-with-your-account#basic-authentication
153
+ [cloudant-legacy-api-keys]: https://cloud.ibm.com/docs/Cloudant?topic=Cloudant-work-with-your-account#api-keys
115
154
 
116
- This library requires some of your
117
- [Cloudant service credentials][service-credentials] to authenticate with your
118
- account.
155
+ This library requires credentials to authenticate with IBM Cloudant. These credentials may be:
156
+ * IBM Cloud IAM credentials (can be used with authentication types `CONTAINER`, `VPC` and `IAM`)
157
+ * [IBM Cloud account][cloud-IAM-mgmt] user, service ID or trusted profile credentials
158
+ that have been granted access to the IBM Cloud Cloudant resource instance.
159
+ * [IBM Cloudant service credentials][service-credentials] generated by the IBM Cloud Cloudant resource instance.
160
+ * Username and password credentials (can be used with authentication types `COUCHDB_SESSION` and `BASIC`)
161
+ * [IBM Cloudant service credentials][service-credentials] generated for an IBM Cloud Cloudant resource instance not configured as `IAM only`.
162
+ * IBM Cloudant [legacy credentials][cloudant-basic-auth] (i.e. username and password) for instances not in IBM Cloud.
163
+ * IBM Cloudant [legacy API keys][cloudant-legacy-api-keys].
119
164
 
120
- 1. `IAM`, `COUCHDB_SESSION`, `BASIC` or `NOAUTH` **authentication type**.
121
- 1. [*IAM authentication*](#iam-authentication) is highly recommended when your
122
- back-end database server is [**Cloudant**][cloud-IAM-mgmt]. This
123
- authentication type requires a server-generated `apikey` instead of a
124
- user-given password. You can create one
125
- [here](https://cloud.ibm.com/iam/apikeys).
126
- 1. [*Session cookie (`COUCHDB_SESSION`) authentication*](#session-cookie-authentication)
127
- is recommended for [Apache CouchDB][couch-cookie-auth] or for
128
- [Cloudant][cloudant-cookie-auth] when IAM is unavailable. It exchanges username
129
- and password credentials for an `AuthSession` cookie from the `/_session`
130
- endpoint.
131
- 1. [*Basic* (or legacy) *authentication*](#basic-authentication) is a fallback
132
- for both [Cloudant][cloudant-basic-auth] and [Apache CouchDB][couch-basic-auth]
133
- back-end database servers. This authentication type requires the good old
134
- `username` and `password` credentials.
135
- 1. *Noauth* authentication does not require credentials. Note that this
136
- authentication type only works with queries against a database with read
137
- access for everyone.
138
- 1. The service `url`.
139
-
140
- There are several ways to **set** these properties:
165
+ For other compatible APIs that are not Cloudant accounts (e.g. Apache CouchDB) non-IAM based authentication types
166
+ must be used.
141
167
 
142
- 1. As [environment variables](#authentication-with-environment-variables)
143
- 1. The [programmatic approach](#programmatic-authentication)
144
- 1. With an [external credentials file](#authentication-with-external-configuration)
168
+ This table summarizes the available authentication types.
169
+ The authentication types are listed in order of recommendation, preferably use the authentication type
170
+ from the first row in the table that is compatible with your environment.
171
+
172
+ | Authenitcation type | Recommended for | `AUTH_TYPE` | Description |
173
+ | --- | --- | --- | --- |
174
+ | IAM Trusted Profiles compute resource ([container](https://github.com/IBM/node-sdk-core/blob/main/Authentication.md#container-authentication)) | Cloudant<BR>(SDK running in IBM Cloud IKS) | `CONTAINER` | Obtains a compute resource (CR) token from the container.<BR>Exchanges the CR token for an IAM `access_token`.<BR>Adds an `Authorization: Bearer <access_token>` header to each HTTP request.<BR>Automatically renews the access token when needed. |
175
+ | IAM Trusted Profiles compute resource ([VPC](https://github.com/IBM/node-sdk-core/blob/main/Authentication.md#vpc-instance-authentication)) | Cloudant<BR>(SDK running in IBM Cloud VPC)| `VPC` | Obtains an identity token from the VPC instance metadata.<BR>Exchanges the identity token for an IAM `access_token`.<BR>Adds an `Authorization: Bearer <access_token>` header to each HTTP request.<BR>Automatically renews the access token when needed. |
176
+ | [IAM API key](https://github.com/IBM/node-sdk-core/blob/main/Authentication.md#identity-and-access-management-iam-authentication) | Cloudant | `IAM` | Exchanges an IAM API key for an IAM `access_token`.<BR>Adds an `Authorization: Bearer <access_token>` header to each HTTP request.<BR>Automatically renews the access token when needed. |
177
+ | [Session cookie](#session-cookie-authentication) | [Cloudant][cloudant-cookie-auth]<BR>(legacy credentials & instances without IAM)<BR><BR>[Apache CouchDB][couch-cookie-auth] | `COUCHDB_SESSION` | Exchanges credentials with `/_session` endpoint to retrieve a cookie.<BR>Adds `Cookie` header and content to each HTTP request.<BR>Automatically renews session when needed. |
178
+ | [Bearer token](https://github.com/IBM/node-sdk-core/blob/main/Authentication.md#bearer-token-authentication) | [Apache CouchDB][couch-jwt-auth]<BR>(using JWT authentication) | `BEARERTOKEN` | Adds an `Authorization: Bearer <token>` to each HTTP request.<BR>No token management or renewal.<BR>Also compatible with IAM access tokens managed independently of the SDK. |
179
+ | [Basic](https://github.com/IBM/node-sdk-core/blob/main/Authentication.md#basic-authentication) | [Apache CouchDB][couch-basic-auth]<BR>(if cookies are not enabled) | `BASIC` | Adds an `Authorization: Basic <encoded username and password>` header to each HTTP request. |
180
+ | [None](https://github.com/IBM/node-sdk-core/blob/main/Authentication.md#no-auth-authentication) | - | `NOAUTH` | Note that this authentication type only works for operations against a database allowing access for unauthenticated users.
145
181
 
146
- ### Authentication with environment variables
182
+ The default authentication type for the SDK is `CONTAINER` unless `APIKEY` configuration is supplied, which changes the default authentication type to `IAM`.
147
183
 
148
- #### IAM authentication
184
+ #### Authentication with environment variables
149
185
 
150
- For Cloudant *IAM authentication*, set the following environmental variables by
186
+ The default service name is `CLOUDANT` so `CLOUDANT_` prefixed names are used in these examples.
187
+
188
+ Any custom service name prefix can be used as long as the matching name is used to instantiate the SDK client
189
+ and the same prefix is used for all configuration options.
190
+
191
+ ##### IAM API key authentication
192
+
193
+ For Cloudant *IAM API key authentication*, set the following environmental variables by
151
194
  replacing the `<url>` and `<apikey>` with your proper
152
195
  [service credentials][service-credentials]. There is no need to set
153
- `CLOUDANT_AUTH_TYPE` to `IAM` because it is the default.
196
+ `CLOUDANT_AUTH_TYPE` to `IAM` because it is the default when an `APIKEY` is set.
154
197
 
155
198
  ```bash
156
199
  CLOUDANT_URL=<url>
157
200
  CLOUDANT_APIKEY=<apikey>
158
201
  ```
159
202
 
160
- #### Session cookie authentication
203
+ ##### IAM Trusted profile (container) authentication
161
204
 
162
- For `COUCHDB_SESSION` authentication, set the following environmental variables
163
- by replacing the `<url>`, `<username>` and `<password>` with your proper
164
- [service credentials][service-credentials].
205
+ For Cloudant *IAM Trusted profile compute resource container authentication*, set the following environmental variables by
206
+ replacing the `<url>` and `<id>` with your values. There is no need to set
207
+ `CLOUDANT_AUTH_TYPE` to `CONTAINER` because it is the default.
165
208
 
166
209
  ```bash
167
- CLOUDANT_AUTH_TYPE=COUCHDB_SESSION
168
210
  CLOUDANT_URL=<url>
169
- CLOUDANT_USERNAME=<username>
170
- CLOUDANT_PASSWORD=<password>
211
+ CLOUDANT_IAM_PROFILE_ID=<id>
171
212
  ```
172
213
 
173
- #### Basic authentication
214
+ Alternatively a profile name may be used instead of an ID by replacing `CLOUDANT_IAM_PROFILE_ID` with `CLOUDANT_IAM_PROFILE_NAME`.
215
+
216
+ ##### IAM Trusted profile (VPC) authentication
174
217
 
175
- For *Basic authentication*, set the following environmental variables by
176
- replacing the `<url>`, `<username>` and `<password>` with your proper
218
+ For Cloudant *IAM Trusted profile compute resource vpc authentication*, set the following environmental variables by
219
+ replacing the `<url>` and `<id>` with your values.
220
+
221
+ ```bash
222
+ CLODUANT_AUTH_TYPE=VPC
223
+ CLOUDANT_URL=<url>
224
+ CLOUDANT_IAM_PROFILE_ID=<id>
225
+ ```
226
+
227
+ Alternatively a profile CRN may be used instead of an ID by replacing `CLOUDANT_IAM_PROFILE_ID` with `CLOUDANT_IAM_PROFILE_CRN`.
228
+
229
+ ##### Session cookie authentication
230
+
231
+ For `COUCHDB_SESSION` authentication, set the following environmental variables
232
+ by replacing the `<url>`, `<username>` and `<password>` with your proper
177
233
  [service credentials][service-credentials].
178
234
 
179
235
  ```bash
180
- CLOUDANT_AUTH_TYPE=BASIC
236
+ CLOUDANT_AUTH_TYPE=COUCHDB_SESSION
181
237
  CLOUDANT_URL=<url>
182
238
  CLOUDANT_USERNAME=<username>
183
239
  CLOUDANT_PASSWORD=<password>
184
240
  ```
185
241
 
186
- **Note**: There are also additional [*Bearer token*](https://github.com/IBM/node-sdk-core/blob/main/Authentication.md#bearer-token-authentication), [*Container*](https://github.com/IBM/node-sdk-core/blob/main/Authentication.md#container-authentication) and [*VPC Instance*](https://github.com/IBM/node-sdk-core/blob/main/Authentication.md#vpc-instance-authentication) authentication methods. For more details, please follow the provided links.
187
- We recommend that you use [IAM](#iam-authentication) for Cloudant and
188
- [Session](#session-cookie-authentication) for CouchDB authentication.
189
-
190
- ### Authentication with external configuration
242
+ #### Authentication with external configuration
191
243
 
192
244
  To use an external configuration file, the
193
245
  [Cloudant API docs](https://cloud.ibm.com/apidocs/cloudant?code=node#authentication-with-external-configuration),
@@ -195,7 +247,7 @@ or the
195
247
  [general SDK usage information](https://github.com/IBM/ibm-cloud-sdk-common#using-external-configuration)
196
248
  will guide you.
197
249
 
198
- ### Programmatic authentication
250
+ #### Programmatic authentication
199
251
 
200
252
  To learn more about how to use programmatic authentication, see the related
201
253
  documentation in the
@@ -203,10 +255,6 @@ documentation in the
203
255
  or in the
204
256
  [Node.js SDK Core document](https://github.com/IBM/node-sdk-core/blob/main/Authentication.md) about authentication.
205
257
 
206
- ## Using the SDK
207
-
208
- For fundamental SDK usage information and config options, please see the common [IBM Cloud SDK](https://github.com/IBM/ibm-cloud-sdk-common/blob/main/README.md) documentation.
209
-
210
258
  ### Request timeout configuration
211
259
 
212
260
  No request timeout is defined, but a 2.5m connect and 2.5m read timeout is set by default. Be sure to set a request timeout appropriate to your application usage and environment.
@@ -241,7 +289,7 @@ Once the environment variables are set, you can try out the code examples.
241
289
  <summary>TypeScript:</summary>
242
290
 
243
291
  ```ts
244
- import {CloudantV1} from "@ibm-cloud/cloudant";
292
+ import { CloudantV1 } from "@ibm-cloud/cloudant";
245
293
  ```
246
294
  [embedmd]:# (test/examples/src/ts/CreateDbAndDoc.ts /interface/ $)
247
295
  ```ts
@@ -422,7 +470,7 @@ database or 'example' document was not found."
422
470
  <summary>TypeScript:</summary>
423
471
 
424
472
  ```ts
425
- import {CloudantV1} from "@ibm-cloud/cloudant";
473
+ import { CloudantV1 } from "@ibm-cloud/cloudant";
426
474
  ```
427
475
  [embedmd]:# (test/examples/src/ts/GetInfoFromExistingDatabase.ts /\/\/ 1./ $)
428
476
  ```ts
@@ -550,7 +598,7 @@ database or 'example' document was not found."
550
598
  <summary>TypeScript:</summary>
551
599
 
552
600
  ```ts
553
- import {CloudantV1} from "@ibm-cloud/cloudant";
601
+ import { CloudantV1 } from "@ibm-cloud/cloudant";
554
602
  ```
555
603
  [embedmd]:# (test/examples/src/ts/UpdateDoc.ts /interface/ $)
556
604
  ```ts
@@ -769,7 +817,7 @@ database or 'example' document was not found."
769
817
  <summary>TypeScript:</summary>
770
818
 
771
819
  ```ts
772
- import {CloudantV1} from "@ibm-cloud/cloudant";
820
+ import { CloudantV1 } from "@ibm-cloud/cloudant";
773
821
  ```
774
822
  [embedmd]:# (test/examples/src/ts/DeleteDoc.ts /interface/ $)
775
823
  ```ts
@@ -918,6 +966,7 @@ Expand them to see examples of:
918
966
  - [Query a list of all documents in a database](https://cloud.ibm.com/apidocs/cloudant?code=node#postalldocs)
919
967
  - [Query the database document changes feed](https://cloud.ibm.com/apidocs/cloudant?code=node#postchanges)
920
968
 
969
+
921
970
  ### Further resources
922
971
 
923
972
  - [Cloudant API docs](https://cloud.ibm.com/apidocs/cloudant?code=node):
@@ -929,6 +978,587 @@ Expand them to see examples of:
929
978
  - [Cloudant blog](https://blog.cloudant.com/):
930
979
  Many useful articles about how to optimize Cloudant for common problems.
931
980
 
981
+ ### Changes feed follower (beta)
982
+
983
+ #### Introduction
984
+
985
+ The SDK provides a changes feed follower utility (currently beta).
986
+ This helper utility connects to the `_changes` endpoint and returns the individual change items.
987
+ It removes some of the complexity of using the `_changes` endpoint by setting some options automatically
988
+ and providing error suppression and retries.
989
+
990
+ *Tip: the changes feed often does not meet user expectations or assumptions.*
991
+
992
+ Consult the [Cloudant changes feed FAQ](https://cloud.ibm.com/docs/Cloudant?topic=Cloudant-faq-using-changes-feed)
993
+ to get a better understanding of the limitations and suitable use-cases before using the changes feed in your application.
994
+
995
+ #### Modes of operation
996
+
997
+ There are two modes of operation:
998
+ * Start mode
999
+ * Fetches the changes from the supplied `since` sequence (by default the feed will start from `now`).
1000
+ * Fetches all available changes and then continues listening for new changes indefinitely unless encountering an end condition.
1001
+ * An example use case for this mode is event driven workloads.
1002
+ * Start one-off mode
1003
+ * Fetches the changes from the supplied `since` sequence (by default the feed will start from the beginning).
1004
+ * Fetches all available changes and then stops when either there are no further changes pending or encountering an end condition.
1005
+ * An example use case for this mode is ETL style workloads.
1006
+
1007
+ #### Configuring the changes follower
1008
+
1009
+ The SDK's model of changes feed options is also used to configure the follower.
1010
+ However, a subset of the options are invalid as they are configured internally by the implementation.
1011
+ Supplying these options when instantiating the follower causes an error.
1012
+ The invalid options are:
1013
+ * `descending`
1014
+ * `feed`
1015
+ * `heartbeat`
1016
+ * `lastEventId` - use `since` instead
1017
+ * `timeout`
1018
+ * Only the value of `_selector` is permitted for the `filter` option. This restriction is because selector
1019
+ based filters perform better than JavaScript backed filters. Configuring a non-selector based filter will
1020
+ cause the follower to error.
1021
+
1022
+ Note that that the `limit` parameter will terminate the follower at the given number of changes in either
1023
+ operating mode.
1024
+
1025
+ The changes follower requires the client to have HTTP timeouts of at least 1 minute and will error during
1026
+ instantiation if it is insufficient. The default client configuration has sufficiently long timeouts.
1027
+
1028
+ For use-cases where these configuration limitations are deemed too restrictive then it is recommended to
1029
+ write code to use the SDK's [POST `_changes` API](examples#postchanges) instead of the follower.
1030
+
1031
+ #### Error suppression
1032
+
1033
+ By default the changes follower will suppress transient errors indefinitely and attempt to run to completion or listen forever as
1034
+ dictated by the opreating mode.
1035
+ For applications where that is not desirable an optional error tolerance duration may be specified to control the time since
1036
+ the last successful response that transient errors will be suppressed. This can be used, for example, by applications as a grace period
1037
+ before reporting an error and requiring intervention.
1038
+
1039
+ There are some additional points to consider for error suppression:
1040
+ * Errors considered terminal, for example, the database not existing or invalid credentials are never suppressed and will error immediately.
1041
+ * The error suppression duration is not guaranteed to fire immediately after lapsing and should be considered a minimum supppression time.
1042
+ * The changes follower will back-off between retries and as such may remain paused for a short while after the transient errors have resolved.
1043
+ * If the underlying SDK client used to initialize the follower also has retries configured then errors could be suppressed for significantly
1044
+ longer than the follower's configured error tolerance duration depending on the configuration options.
1045
+
1046
+ #### Follower operation
1047
+
1048
+ For both modes:
1049
+ * The end conditions are:
1050
+ * A terminal error (HTTP codes `400`, `401`, `403` `404`).
1051
+ * Transient errors occur for longer than the error tolerance duration. Transient errors are all other HTTP status codes and connection errors.
1052
+ * The number of changes received reaches the configured `limit`.
1053
+ * The feed is terminated early by calling stop.
1054
+
1055
+ As is true for the `_changes` endpoint change items have _at least once_ delivery and an individual item
1056
+ may be received multiple times. When using the follower change items may be repeated even within a limited
1057
+ number of changes (i.e. using the `limit` option) this is a minor difference from using `limit` on the HTTP native API.
1058
+
1059
+ The follower is not optimized for some use cases and it is not recommended to use it in cases where:
1060
+ * Setting `include_docs` and larger document sizes (for example > 10 kiB).
1061
+ * The volume of changes is very high (if the rate of changes in the database exceeds the follower's rate of pulling them it will never catch-up).
1062
+
1063
+ In these cases use-case specific control over the number of change requests made and the content size of the responses
1064
+ may be achived by using the SDK's [POST `_changes` API](examples#postchanges).
1065
+
1066
+ #### Checkpointing
1067
+
1068
+ The changes follower does not checkpoint since it has no information about whether a change item has been
1069
+ processed by the consuming application after being received. It is the application developer's responsibility
1070
+ to store the sequence IDs to have appropriate checkpoints and to re-initialize the follower with the required
1071
+ `since` value after, for example, the application restarts.
1072
+
1073
+ The frequency and conditions for checkpointing are application specific and some applications may be tolerant
1074
+ of dropped changes. This section is intended only to provide general guidance on how to avoid missing changes.
1075
+
1076
+ To guarantee processing of all changes the sequence ID from a change item must not be persisted until _after_
1077
+ the processing of the change item by the application has completed. As indicated previously change items are
1078
+ delivered _at least once_ so application code must be able to handle repeated changes already and it is
1079
+ preferable to restart from an older `since` value and receive changes again than risk missing them.
1080
+
1081
+ The sequence IDs are available on each change item by default, but may be ommitted from some change items when
1082
+ using the `seq_interval` configuration option. Infrequent sequence IDs may improve performance by reducing
1083
+ the amount of data that needs to be transferred, but the trade-off is that more changes will be repeated if
1084
+ it is necessary to resume the changes follower.
1085
+
1086
+ Extreme care should be taken with persisting sequences if choosing to process change items in parallel as there
1087
+ is a considerable risk of missing changes on a restart if the sequence is recorded out of order.
1088
+
1089
+ #### Code examples
1090
+
1091
+ ##### Initializing a changes follower
1092
+ <details open>
1093
+ <summary>TypeScript:</summary>
1094
+
1095
+ ```ts
1096
+ import { ChangesFollower, CloudantV1 } from '@ibm-cloud/cloudant';
1097
+ import { PostChangesParams } from '@ibm-cloud/cloudant/cloudant/v1';
1098
+ ```
1099
+ [embedmd]:# (test/examples/src/features/ts/initialize.ts /const client/ $)
1100
+ ```ts
1101
+ const client = CloudantV1.newInstance({});
1102
+ const changesParams: PostChangesParams = {
1103
+ db: 'example', // Required: the database name.
1104
+ limit: 100, // Optional: return only 100 changes (including duplicates).
1105
+ since: '3-g1AG3...' // Optional: start from this sequence ID (e.g. with a value read from persistent storage).
1106
+ };
1107
+ const errorTolerance: number = 10000; // 10 second duration to suppress transient errors
1108
+ const changesFollower: ChangesFollower = new ChangesFollower(
1109
+ client, // Required: the Cloudant service client instance.
1110
+ changesParams, // Required: changes feed configuration options dict.
1111
+ 10000 // Optional: suppress transient errors for at least 10 seconds before terminating.
1112
+ );
1113
+ ```
1114
+ </details>
1115
+
1116
+ <details>
1117
+ <summary>JavaScript:</summary>
1118
+
1119
+ ```js
1120
+ const { ChangesFollower, CloudantV1 } = require('@ibm-cloud/cloudant');
1121
+ ```
1122
+ [embedmd]:# (test/examples/src/features/js/initialize.js /const client/ $)
1123
+ ```js
1124
+ const client = CloudantV1.newInstance();
1125
+ const changesParams = {
1126
+ db: 'example', // Required: the database name.
1127
+ limit: 100, // Optional: return only 100 changes (including duplicates).
1128
+ since: '3-g1AG3...' // Optional: start from this sequence ID (e.g. with a value read from persistent storage).
1129
+ };
1130
+ const changesFollower = new ChangesFollower(
1131
+ client, // Required: the Cloudant service client instance.
1132
+ changesParams, // Required: changes feed configuration options dict.
1133
+ 10000 // Optional: suppress transient errors for at least 10 seconds before terminating.
1134
+ );
1135
+ ```
1136
+ </details>
1137
+
1138
+
1139
+ ##### Starting the changes follower
1140
+
1141
+ ###### Start mode for continuous listening
1142
+ <details open>
1143
+ <summary>TypeScript:</summary>
1144
+
1145
+ ```ts
1146
+ import { ChangesFollower, CloudantV1, Stream } from '@ibm-cloud/cloudant';
1147
+ import { ChangesResultItem, PostChangesParams } from '@ibm-cloud/cloudant/cloudant/v1';
1148
+ ```
1149
+ [embedmd]:# (test/examples/src/features/ts/start.ts /const client/ $)
1150
+ ```ts
1151
+ const client = CloudantV1.newInstance({});
1152
+ const changesParams: PostChangesParams = {
1153
+ db: 'example'
1154
+ };
1155
+ const changesFollower: ChangesFollower = new ChangesFollower(client, changesParams);
1156
+ const changesItemsStream: Stream<ChangesResultItem> = changesFollower.start();
1157
+ // Create for-async-loop or pipeline to begin the flow of changes
1158
+ // e.g. pipeline(changesItemsStream, destinationStream).then(() => { ... }).catch((err) => { ... });
1159
+ ```
1160
+ </details>
1161
+
1162
+ <details>
1163
+ <summary>JavaScript:</summary>
1164
+
1165
+ ```js
1166
+ const { ChangesFollower, CloudantV1 } = require('@ibm-cloud/cloudant');
1167
+ ```
1168
+ [embedmd]:# (test/examples/src/features/js/start.js /const client/ $)
1169
+ ```js
1170
+ const client = CloudantV1.newInstance();
1171
+ const changesParams = {
1172
+ db: 'example'
1173
+ };
1174
+ const changesFollower = new ChangesFollower(client, changesParams);
1175
+ const changesItemsStream = changesFollower.start();
1176
+ // Create for-async-loop or pipeline to begin the flow of changes
1177
+ // e.g. pipeline(changesItemsStream, destinationStream).then(() => { ... }).catch((err) => { ... });
1178
+ ```
1179
+ </details>
1180
+
1181
+
1182
+ ###### Start mode for one-off fetching
1183
+ <details open>
1184
+ <summary>TypeScript:</summary>
1185
+
1186
+ ```ts
1187
+ import { ChangesFollower, CloudantV1, Stream } from '@ibm-cloud/cloudant';
1188
+ import { ChangesResultItem, PostChangesParams } from '@ibm-cloud/cloudant/cloudant/v1';
1189
+ ```
1190
+ [embedmd]:# (test/examples/src/features/ts/startOneOff.ts /const client/ $)
1191
+ ```ts
1192
+ const client = CloudantV1.newInstance({});
1193
+ const changesParams: PostChangesParams = {
1194
+ db: 'example'
1195
+ };
1196
+ const changesFollower: ChangesFollower = new ChangesFollower(client, changesParams);
1197
+ const changesItemsStream: Stream<ChangesResultItem> = changesFollower.startOneOff();
1198
+ // Create for-async-loop or pipeline to begin the flow of changes
1199
+ // e.g. pipeline(changesItemsStream, destinationStream).then(() => { ... }).catch((err) => { ... });
1200
+ ```
1201
+ </details>
1202
+
1203
+ <details>
1204
+ <summary>JavaScript:</summary>
1205
+
1206
+ ```js
1207
+ const { ChangesFollower, CloudantV1 } = require('@ibm-cloud/cloudant');
1208
+ ```
1209
+ [embedmd]:# (test/examples/src/features/js/startOneOff.js /const client/ $)
1210
+ ```js
1211
+ const client = CloudantV1.newInstance();
1212
+ const changesParams = {
1213
+ db: 'example'
1214
+ };
1215
+ const changesFollower = new ChangesFollower(client, changesParams);
1216
+ const changesItemsStream = changesFollower.startOneOff();
1217
+ // Create for-async-loop or pipeline to begin the flow of changes
1218
+ // e.g. pipeline(changesItemsStream, destinationStream).then(() => { ... }).catch((err) => { ... });
1219
+ ```
1220
+ </details>
1221
+
1222
+
1223
+ ##### Processing changes
1224
+
1225
+ ###### Process continuous changes
1226
+ <details open>
1227
+ <summary>TypeScript:</summary>
1228
+
1229
+ ```ts
1230
+ import { ChangesFollower, CloudantV1, Stream } from '@ibm-cloud/cloudant';
1231
+ import { ChangesResultItem, PostChangesParams } from '@ibm-cloud/cloudant/cloudant/v1';
1232
+ import { Writable } from 'node:stream';
1233
+ import { pipeline } from 'node:stream/promises'
1234
+ ```
1235
+ [embedmd]:# (test/examples/src/features/ts/startAndProcess.ts /const client/ $)
1236
+ ```ts
1237
+ const client = CloudantV1.newInstance({});
1238
+ // Start from a previously persisted seq
1239
+ // Normally this would be read by the app from persistent storage
1240
+ // e.g. previouslyPersistedSeq = yourAppPersistenceReadFunc()
1241
+ const previouslyPersistedSeq = '3-g1AG3...'
1242
+ const changesParams: PostChangesParams = {
1243
+ db: 'example',
1244
+ since: previouslyPersistedSeq
1245
+ };
1246
+ const changesFollower = new ChangesFollower(client, changesParams);
1247
+ const changesItemsStream: Stream<ChangesResultItem> = changesFollower.start();
1248
+
1249
+ const destinationStream = new Writable({
1250
+ objectMode: true,
1251
+ write(changesItem: CloudantV1.ChangesResultItem, _, callback) {
1252
+ // do something with change item
1253
+ console.log(changesItem.id);
1254
+ for (const change of changesItem.changes) {
1255
+ console.log(change.rev)
1256
+ }
1257
+ // when change item processing is complete app can store seq
1258
+ const seq = changesItem.seq
1259
+ // write seq to persistent storage for use as since if required to resume later
1260
+ // e.g. yourAppPersistenceWriteFunc()
1261
+ callback();
1262
+ }
1263
+ });
1264
+
1265
+ // A pipeline to keep processing changes until the follower is stopped or some other stop condition is reached
1266
+ pipeline(changesItemsStream, destinationStream)
1267
+ .then(() => {
1268
+ console.log('Stopped');
1269
+ })
1270
+ .catch((err) => {
1271
+ console.log(err);
1272
+ });
1273
+ ```
1274
+ </details>
1275
+
1276
+ <details>
1277
+ <summary>JavaScript:</summary>
1278
+
1279
+ ```js
1280
+ const { ChangesFollower, CloudantV1 } = require('@ibm-cloud/cloudant');
1281
+ const { Writable } = require('node:stream');
1282
+ const { pipeline } = require('node:stream/promises');
1283
+ ```
1284
+ [embedmd]:# (test/examples/src/features/js/startAndProcess.js /const client/ $)
1285
+ ```js
1286
+ const client = CloudantV1.newInstance();
1287
+ // Start from a previously persisted seq
1288
+ // Normally this would be read by the app from persistent storage
1289
+ // e.g. previouslyPersistedSeq = yourAppPersistenceReadFunc()
1290
+ const previouslyPersistedSeq = '3-g1AG3...'
1291
+ const changesParams = {
1292
+ db: 'example',
1293
+ since: previouslyPersistedSeq
1294
+ };
1295
+ const changesFollower = new ChangesFollower(client, changesParams);
1296
+ const changesItemsStream = changesFollower.start();
1297
+
1298
+ const destinationStream = new Writable({
1299
+ objectMode: true,
1300
+ write(changesItem, _, callback) {
1301
+ // do something with change item
1302
+ console.log(changesItem.id);
1303
+ for (const change of changesItem.changes) {
1304
+ console.log(change.rev)
1305
+ }
1306
+ // when change item processing is complete app can store seq
1307
+ const seq = changesItem.seq
1308
+ // write seq to persistent storage for use as since if required to resume later
1309
+ // e.g. yourAppPersistenceWriteFunc()
1310
+ callback();
1311
+ }
1312
+ });
1313
+
1314
+ // A pipeline to keep processing changes until the follower is stopped or some other stop condition is reached
1315
+ pipeline(changesItemsStream, destinationStream)
1316
+ .then(() => {
1317
+ console.log('Stopped');
1318
+ })
1319
+ .catch((err) => {
1320
+ console.log(err);
1321
+ });
1322
+ ```
1323
+ </details>
1324
+
1325
+
1326
+ ###### Process one-off changes
1327
+ <details open>
1328
+ <summary>TypeScript:</summary>
1329
+
1330
+ ```ts
1331
+ import { ChangesFollower, CloudantV1, Stream } from '@ibm-cloud/cloudant';
1332
+ import { ChangesResultItem, PostChangesParams } from '@ibm-cloud/cloudant/cloudant/v1';
1333
+ import { Writable } from 'node:stream';
1334
+ import { pipeline } from 'node:stream/promises'
1335
+ ```
1336
+ [embedmd]:# (test/examples/src/features/ts/startOneOffAndProcess.ts /const client/ $)
1337
+ ```ts
1338
+ const client = CloudantV1.newInstance({});
1339
+ // Start from a previously persisted seq
1340
+ // Normally this would be read by the app from persistent storage
1341
+ // e.g. previouslyPersistedSeq = yourAppPersistenceReadFunc()
1342
+ const previouslyPersistedSeq = '3-g1AG3...'
1343
+ const changesParams: PostChangesParams = {
1344
+ db: 'example',
1345
+ since: previouslyPersistedSeq
1346
+ };
1347
+ const changesFollower: ChangesFollower = new ChangesFollower(client, changesParams);
1348
+ const changesItemsStream: Stream<ChangesResultItem> = changesFollower.startOneOff();
1349
+
1350
+ const destinationStream = new Writable({
1351
+ objectMode: true,
1352
+ write(changesItem: CloudantV1.ChangesResultItem, _, callback) {
1353
+ // do something with change item
1354
+ console.log(changesItem.id);
1355
+ for (const change of changesItem.changes) {
1356
+ console.log(change.rev)
1357
+ }
1358
+ // when change item processing is complete app can store seq
1359
+ const seq = changesItem.seq
1360
+ // write seq to persistent storage for use as since if required to resume later
1361
+ // e.g. yourAppPersistenceWriteFunc()
1362
+ callback();
1363
+ }
1364
+ });
1365
+
1366
+ pipeline(changesItemsStream, destinationStream)
1367
+ .then(() => {
1368
+ console.log('All changes done');
1369
+ })
1370
+ .catch((err) => {
1371
+ console.log(err);
1372
+ });
1373
+
1374
+ // use for-async-loop feature for stream
1375
+ /*
1376
+ getChangesFromFollower(changesItemsStream);
1377
+ async function getChangesFromFollower(changesItemsStream: Stream<CloudantV1.ChangesResultItem>) {
1378
+ for await (const changesItem of changesItemsStream) {
1379
+ // do something with change item
1380
+ // write seq to persistent storage for use as since
1381
+ console.log(changesItem.id);
1382
+ for (const change of changesItem.changes) {
1383
+ console.log(change.rev)
1384
+ }
1385
+ // when change item processing is complete app can store seq
1386
+ seq = changesItem.seq
1387
+ // write seq to persistent storage for use as since if required to resume later
1388
+ // e.g. yourAppPersistenceWriteFunc()
1389
+ }
1390
+ }
1391
+ */
1392
+ ```
1393
+ </details>
1394
+
1395
+ <details>
1396
+ <summary>JavaScript:</summary>
1397
+
1398
+ ```js
1399
+ const { ChangesFollower, CloudantV1 } = require('@ibm-cloud/cloudant');
1400
+ const { Writable } = require('node:stream');
1401
+ const { pipeline } = require('node:stream/promises');
1402
+ ```
1403
+ [embedmd]:# (test/examples/src/features/js/startOneOffAndProcess.js /const client/ $)
1404
+ ```js
1405
+ const client = CloudantV1.newInstance();
1406
+ // Start from a previously persisted seq
1407
+ // Normally this would be read by the app from persistent storage
1408
+ // e.g. previouslyPersistedSeq = yourAppPersistenceReadFunc()
1409
+ const previouslyPersistedSeq = '3-g1AG3...'
1410
+ const changesParams = {
1411
+ db: 'example',
1412
+ since: previouslyPersistedSeq
1413
+ };
1414
+ const changesFollower = new ChangesFollower(client, changesParams);
1415
+ const changesItemsStream = changesFollower.startOneOff();
1416
+
1417
+ const destinationStream = new Writable({
1418
+ objectMode: true,
1419
+ write(changesItem, _, callback) {
1420
+ // do something with change item
1421
+ console.log(changesItem.id);
1422
+ for (const change of changesItem.changes) {
1423
+ console.log(change.rev)
1424
+ }
1425
+ // when change item processing is complete app can store seq
1426
+ const seq = changesItem.seq
1427
+ // write seq to persistent storage for use as since if required to resume later
1428
+ // e.g. yourAppPersistenceWriteFunc()
1429
+ callback();
1430
+ }
1431
+ });
1432
+
1433
+ pipeline(changesItemsStream, destinationStream)
1434
+ .then(() => {
1435
+ console.log('All changes done');
1436
+ })
1437
+ .catch((err) => {
1438
+ console.log(err);
1439
+ });
1440
+
1441
+ // use for-async-loop feature for stream
1442
+ /*
1443
+ getChangesFromFollower(changesItemsStream);
1444
+ async function getChangesFromFollower(changesItemsStream) {
1445
+ for await (const changesItem of changesItemsStream) {
1446
+ // do something with change item
1447
+ // write seq to persistent storage for use as since
1448
+ console.log(changesItem.id);
1449
+ for (const change of changesItem.changes) {
1450
+ console.log(change.rev)
1451
+ }
1452
+ // when change item processing is complete app can store seq
1453
+ seq = changesItem.seq
1454
+ // write seq to persistent storage for use as since if required to resume later
1455
+ // e.g. yourAppPersistenceWriteFunc()
1456
+ }
1457
+ }
1458
+ */
1459
+ ```
1460
+ </details>
1461
+
1462
+
1463
+ ##### Stopping the changes follower
1464
+ <details open>
1465
+ <summary>TypeScript:</summary>
1466
+
1467
+ ```ts
1468
+ import { ChangesFollower, CloudantV1, Stream } from '@ibm-cloud/cloudant';
1469
+ import { ChangesResultItem, PostChangesParams } from '@ibm-cloud/cloudant/cloudant/v1';
1470
+ import { Writable } from 'node:stream';
1471
+ import { pipeline } from 'node:stream/promises'
1472
+ ```
1473
+ [embedmd]:# (test/examples/src/features/ts/stop.ts /const client/ $)
1474
+ ```ts
1475
+ const client = CloudantV1.newInstance({});
1476
+ const changesParams: PostChangesParams = {
1477
+ db: 'example'
1478
+ };
1479
+ const changesFollower: ChangesFollower = new ChangesFollower(client, changesParams);
1480
+ const changesItemsStream: Stream<ChangesResultItem> = changesFollower.start();
1481
+
1482
+ const destinationStream = new Writable({
1483
+ objectMode: true,
1484
+ write(changesItem: CloudantV1.ChangesResultItem, _, callback) {
1485
+ // Option 1: call stop after some condition
1486
+ // Note that at least one item
1487
+ // must be returned to reach to this point.
1488
+ // Additional changes may be processed before the iterator stops.
1489
+ changesFollower.stop();
1490
+ callback();
1491
+ }
1492
+ });
1493
+
1494
+ pipeline(changesItemsStream, destinationStream)
1495
+ .then(() => {
1496
+ console.log('Stopped');
1497
+ })
1498
+ .catch((err) => {
1499
+ console.log(err);
1500
+ });
1501
+
1502
+ // Option 2: call stop method when you want to end the continuous loop from
1503
+ // outside the pipeline.
1504
+ // Normally the call would be made from some other application function
1505
+ // executing later.
1506
+ // For example, stop the changesFollower after 1 minute of listening for changes
1507
+ setTimeout(() => {
1508
+ changesFollower.stop();
1509
+ }, 60000);
1510
+ ```
1511
+ </details>
1512
+
1513
+ <details>
1514
+ <summary>JavaScript:</summary>
1515
+
1516
+ ```js
1517
+ const { ChangesFollower, CloudantV1 } = require('@ibm-cloud/cloudant');
1518
+ const { Writable } = require('node:stream');
1519
+ const { pipeline } = require('node:stream/promises');
1520
+ ```
1521
+ [embedmd]:# (test/examples/src/features/js/stop.js /const client/ $)
1522
+ ```js
1523
+ const client = CloudantV1.newInstance();
1524
+ const changesParams = {
1525
+ db: 'example'
1526
+ };
1527
+ const changesFollower = new ChangesFollower(client, changesParams);
1528
+ const changesItemsStream = changesFollower.start();
1529
+
1530
+ const destinationStream = new Writable({
1531
+ objectMode: true,
1532
+ write(changesItem, _, callback) {
1533
+ // Option 1: call stop after some condition
1534
+ // Note that at least one item
1535
+ // must be returned to reach to this point.
1536
+ // Additional changes may be processed before the iterator stops.
1537
+ changesFollower.stop();
1538
+ callback();
1539
+ }
1540
+ });
1541
+
1542
+ pipeline(changesItemsStream, destinationStream)
1543
+ .then(() =>{
1544
+ console.log('Stopped');
1545
+ })
1546
+ .catch((err) => {
1547
+ console.log(err);
1548
+ });
1549
+
1550
+ // Option 2: call stop method when you want to end the continuous loop from
1551
+ // outside the pipeline.
1552
+ // Normally the call would be made from some other application function
1553
+ // executing later.
1554
+ // For example, stop the changesFollower after 1 minute of listening for changes
1555
+ setTimeout(() => {
1556
+ changesFollower.stop();
1557
+ }, 60000);
1558
+ ```
1559
+ </details>
1560
+
1561
+
932
1562
  ## Questions
933
1563
 
934
1564
  If you are having difficulties using this SDK or have a question about the