@openfn/language-collections 0.4.0 → 0.5.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
@@ -1,16 +1,104 @@
1
1
  # language-collections <img src='./assets/square.png' width="30" height="30"/>
2
2
 
3
- An OpenFn **_adaptor_** for building integration jobs for use with the
4
- collections API.
3
+ An **_adaptor_** for using the OpenFn Collections API.
5
4
 
6
- The collections API is not designed to be used alone, but in conjunction with
7
- other adaptors.
5
+ The Collections adaptor is not designed to be used alone, but in conjunction
6
+ with other adaptors. As a result, it's a bit different to other adaptors.
7
+
8
+ The Collections API is a key/value store, which can act as a high performance
9
+ cache, buffer or storage solution. All values are strings (but can contain
10
+ JSON).
11
+
12
+ ## Usage
13
+
14
+ All collections functions are exposed through the `collections` namespace:
15
+
16
+ To iterate over all values with `2024` somewhere in the key
17
+
18
+ ```
19
+ collections.each($.collectionName, '*2024*', (state, value, key) => {
20
+ console.log(value)
21
+ })
22
+ ```
8
23
 
9
24
  ## Documentation
10
25
 
11
26
  View the [docs site](https://docs.openfn.org/adaptors/packages/collections-docs)
12
27
  for full technical documentation.
13
28
 
29
+ ## CLI
30
+
31
+ Collections can be used from the CLI since v1.8.7, but you will need to:
32
+
33
+ - Set the job to use two adaptors
34
+ - Pass a Personal Access Token
35
+ - Set the Collections endpoint
36
+
37
+ You can get a Personal Access Token from any v2 deployment.
38
+
39
+ ### For a single job
40
+
41
+ You can pass multiple adaptors from the CLI:
42
+
43
+ ```
44
+ openfn job.js -a collections -a http -s state.json
45
+ ```
46
+
47
+ You'll need to set configuration on the state.json:
48
+
49
+ ```
50
+ {
51
+ "configuration": {
52
+ "collections_endpoint": "http://localhost:4000/collections",
53
+ "collections_token": "...paste the token from the app..."
54
+ }
55
+ }
56
+
57
+ ```
58
+
59
+ ### For a workflow
60
+
61
+ If you're using `workflow.json`, set the token and endpoint on
62
+ `workflow.credentials`:
63
+
64
+ ```json
65
+ {
66
+ "workflow": {
67
+ "steps": [ ... ],
68
+ "credentials": {
69
+ "collections_endpoint": "http://localhost:4000/collections",
70
+ "collections_token": "...paste the token from the app..."
71
+ }
72
+ }
73
+ }
74
+ ```
75
+
76
+ And make sure that any steps which use collections have multiple adaptors set:
77
+
78
+ ```json
79
+ {
80
+ "workflow": {
81
+ "steps": [
82
+ {
83
+ "expression": "...",
84
+ "adaptors": ["@openfn/language-http", "@openfn/language-collections"]
85
+ }
86
+ ]
87
+ }
88
+ }
89
+ ```
90
+
91
+ Note that steps cannot generally use multiple adaptors. Collections are special
92
+ in this regard.
93
+
94
+ ## Deployments
95
+
96
+ Collections must be configured for your platform instance (v2 only).
97
+
98
+ Set the `WORKER_COLLECTIONS_URL` env var on the Worker instance to enable
99
+ collections for that worker. The URL should point to
100
+ `https://<lightning>/collections`
101
+
14
102
  ## Development
15
103
 
16
104
  Clone the [adaptors monorepo](https://github.com/OpenFn/adaptors). Follow the
package/dist/index.cjs CHANGED
@@ -70,22 +70,36 @@ function API() {
70
70
  }
71
71
  collections[name][key] = value;
72
72
  };
73
- const fetch = (name, key, query) => {
73
+ const fetch = (name, key, query = {}) => {
74
+ const { cursor = 0, limit = Infinity } = query;
74
75
  if (!(name in collections)) {
75
76
  throw new Error(COLLECTION_NOT_FOUND);
76
77
  }
77
78
  const col = collections[name];
78
79
  const items = [];
80
+ let idx = 0;
81
+ let count = 0;
79
82
  const regex = new RegExp(key.replace("*", "(.*)"));
80
83
  for (const key2 in col) {
81
- if (regex.test(key2)) {
82
- items.push({
83
- key: key2,
84
- value: col[key2]
85
- });
84
+ if (idx >= cursor) {
85
+ if (regex.test(key2)) {
86
+ count++;
87
+ items.push({
88
+ key: key2,
89
+ value: col[key2]
90
+ });
91
+ }
92
+ }
93
+ idx++;
94
+ if (count >= limit) {
95
+ break;
86
96
  }
87
97
  }
88
- return { items };
98
+ const result = { items, count };
99
+ if (idx < Object.keys(col).length) {
100
+ result.cursor = idx;
101
+ }
102
+ return result;
89
103
  };
90
104
  const byKey = (name, key) => {
91
105
  return collections[name][key];
@@ -163,9 +177,14 @@ function createServer(url = "https://app.openfn.org") {
163
177
  } else {
164
178
  const params = new URLSearchParams(req.query || req.path.split("?")[1]);
165
179
  key = params.get("key") ?? "*";
166
- const { items } = api.fetch(name, key);
180
+ const limit = params.get("limit") ?? Infinity;
181
+ const cursor = params.get("cursor") ?? 0;
182
+ const { items, cursor: finalCursor } = api.fetch(name, key, {
183
+ limit,
184
+ cursor
185
+ });
167
186
  body = {
168
- cursor: ["xxx"],
187
+ cursor: (finalCursor && `${finalCursor}`) ?? null,
169
188
  items
170
189
  };
171
190
  }
@@ -285,33 +304,40 @@ function get(name, query = {}) {
285
304
  if (typeof resolvedQuery === "string") {
286
305
  resolvedQuery = { key: resolvedQuery };
287
306
  }
288
- const { key, ...rest } = expandQuery(resolvedQuery);
289
- let q;
290
- let path = resolvedName;
291
- if (key.match(/\*/) || Object.keys(rest).length) {
292
- q = resolvedQuery;
293
- } else {
294
- path = `${resolvedName}/${key}`;
295
- }
296
- const response = await request(state, getClient(state), path, { query: q });
307
+ const {
308
+ key = "*",
309
+ limit,
310
+ pageSize,
311
+ ...userQuery
312
+ } = expandQuery(resolvedQuery);
313
+ console.log(`Collections: Downloading data from "${name}"...`);
297
314
  let data;
298
- if (q) {
315
+ if (key.match(/\*/) || Object.keys(userQuery).length) {
299
316
  data = [];
300
- console.log(`Downloading data from collection "${name}"...`);
301
- const cursor = await streamResponse(response, (item) => {
302
- item.value = JSON.parse(item.value);
303
- data.push(item);
304
- });
305
- data.cursor = cursor;
306
- console.log(`Fetched "${data.length}" values from collection "${name}"`);
317
+ const scopedState = {
318
+ ...state,
319
+ data: {}
320
+ };
321
+ await each(name, resolvedQuery, (state2, value, key2) => {
322
+ data.push({ value, key: key2 });
323
+ })(scopedState);
324
+ console.log(
325
+ `Collections: Fetched total of ${data.length} values from "${name}"`
326
+ );
327
+ data.cursor = scopedState.data.cursor;
307
328
  } else {
329
+ const response = await request(
330
+ state,
331
+ getClient(state),
332
+ `${resolvedName}/${key}`
333
+ );
308
334
  const body = await response.body.json();
309
335
  if (body.value) {
310
336
  data = JSON.parse(body.value);
311
- console.log(`Fetched "${key}" from collection "${name}"`);
337
+ console.log(`Collections: Fetched "${key}" from "${name}"`);
312
338
  } else {
313
339
  data = {};
314
- console.warn(`Key "${key}" not found in collection "${name}"`);
340
+ console.warn(`Collections: Key "${key}" not found in "${name}"`);
315
341
  }
316
342
  }
317
343
  state.data = data;
@@ -340,7 +366,7 @@ function set(name, keyGen, values) {
340
366
  });
341
367
  if (response.statusCode >= 400) {
342
368
  console.log(
343
- `Error setting ${pairs.length} values in collection "${name}"`
369
+ `Collections: Error setting ${pairs.length} values in "${name}"`
344
370
  );
345
371
  const text = await response.body.text();
346
372
  const e = new Error("ERROR from collections server:" + 400);
@@ -348,9 +374,9 @@ function set(name, keyGen, values) {
348
374
  throw e;
349
375
  }
350
376
  const result = await response.body.json();
351
- console.log(`Set ${result.upserted} values in collection "${name}"`);
377
+ console.log(`Collections: set ${result.upserted} values in "${name}"`);
352
378
  if (result.error) {
353
- console.log(`Errors reported on set:`, result.error);
379
+ console.log(`Collections: errors reported on set:`, result.error);
354
380
  }
355
381
  return state;
356
382
  };
@@ -374,7 +400,7 @@ function remove(name, query = {}, options = {}) {
374
400
  query: q
375
401
  });
376
402
  const result = await response.body.json();
377
- console.log(`Removed ${result.deleted} values in collection "${name}"`);
403
+ console.log(`Collections: Removed ${result.deleted} values in "${name}"`);
378
404
  return state;
379
405
  };
380
406
  }
@@ -388,13 +414,36 @@ function each(name, query = {}, callback = () => {
388
414
  } else {
389
415
  q = resolvedQuery;
390
416
  }
391
- const { key, ...rest } = expandQuery(resolvedQuery);
392
- const response = await request(state, getClient(state), resolvedName, {
393
- query: q
394
- });
395
- const cursor = await streamResponse(response, async ({ value, key: key2 }) => {
396
- await callback(state, JSON.parse(value), key2);
397
- });
417
+ const {
418
+ key = "*",
419
+ pageSize = 1e3,
420
+ limit = Infinity,
421
+ ...finalQuery
422
+ } = expandQuery(resolvedQuery);
423
+ let { cursor } = resolvedQuery;
424
+ let count = 0;
425
+ do {
426
+ let batchSize = 0;
427
+ const q2 = {
428
+ ...finalQuery,
429
+ key,
430
+ limit: limit < Infinity ? Math.min(pageSize, limit - count) : pageSize
431
+ };
432
+ if (cursor) {
433
+ q2.cursor = cursor;
434
+ }
435
+ const response = await request(state, getClient(state), resolvedName, {
436
+ query: q2
437
+ });
438
+ cursor = await streamResponse(response, async ({ key: key2, value }) => {
439
+ batchSize++;
440
+ await callback(state, JSON.parse(value), key2);
441
+ });
442
+ count += batchSize;
443
+ console.log(
444
+ `Collections: fetched chunk of ${batchSize} values from "${name}"`
445
+ );
446
+ } while (cursor && count < limit);
398
447
  state.data = {
399
448
  cursor
400
449
  };
@@ -423,6 +472,7 @@ var streamResponse = async (response, onValue) => {
423
472
  if (next.value.value === "cursor") {
424
473
  const strValue = await waitFor("stringChunk", "nullValue");
425
474
  if (strValue.name === "nullValue") {
475
+ cursor = null;
426
476
  continue;
427
477
  }
428
478
  cursor = strValue.value.value;
@@ -468,9 +518,7 @@ var expandQuery = (query) => {
468
518
  };
469
519
  var queryMaps = {
470
520
  createdBefore: "created_before",
471
- createdAfter: "created_after",
472
- updatedBefore: "updated_before",
473
- updatedAfter: "updated_after"
521
+ createdAfter: "created_after"
474
522
  };
475
523
  var parseQuery = (options = {}) => {
476
524
  return Object.keys(options.query ?? {}).reduce((result, next) => {
package/dist/index.js CHANGED
@@ -45,22 +45,36 @@ function API() {
45
45
  }
46
46
  collections[name][key] = value;
47
47
  };
48
- const fetch = (name, key, query) => {
48
+ const fetch = (name, key, query = {}) => {
49
+ const { cursor = 0, limit = Infinity } = query;
49
50
  if (!(name in collections)) {
50
51
  throw new Error(COLLECTION_NOT_FOUND);
51
52
  }
52
53
  const col = collections[name];
53
54
  const items = [];
55
+ let idx = 0;
56
+ let count = 0;
54
57
  const regex = new RegExp(key.replace("*", "(.*)"));
55
58
  for (const key2 in col) {
56
- if (regex.test(key2)) {
57
- items.push({
58
- key: key2,
59
- value: col[key2]
60
- });
59
+ if (idx >= cursor) {
60
+ if (regex.test(key2)) {
61
+ count++;
62
+ items.push({
63
+ key: key2,
64
+ value: col[key2]
65
+ });
66
+ }
67
+ }
68
+ idx++;
69
+ if (count >= limit) {
70
+ break;
61
71
  }
62
72
  }
63
- return { items };
73
+ const result = { items, count };
74
+ if (idx < Object.keys(col).length) {
75
+ result.cursor = idx;
76
+ }
77
+ return result;
64
78
  };
65
79
  const byKey = (name, key) => {
66
80
  return collections[name][key];
@@ -138,9 +152,14 @@ function createServer(url = "https://app.openfn.org") {
138
152
  } else {
139
153
  const params = new URLSearchParams(req.query || req.path.split("?")[1]);
140
154
  key = params.get("key") ?? "*";
141
- const { items } = api.fetch(name, key);
155
+ const limit = params.get("limit") ?? Infinity;
156
+ const cursor = params.get("cursor") ?? 0;
157
+ const { items, cursor: finalCursor } = api.fetch(name, key, {
158
+ limit,
159
+ cursor
160
+ });
142
161
  body = {
143
- cursor: ["xxx"],
162
+ cursor: (finalCursor && `${finalCursor}`) ?? null,
144
163
  items
145
164
  };
146
165
  }
@@ -260,33 +279,40 @@ function get(name, query = {}) {
260
279
  if (typeof resolvedQuery === "string") {
261
280
  resolvedQuery = { key: resolvedQuery };
262
281
  }
263
- const { key, ...rest } = expandQuery(resolvedQuery);
264
- let q;
265
- let path = resolvedName;
266
- if (key.match(/\*/) || Object.keys(rest).length) {
267
- q = resolvedQuery;
268
- } else {
269
- path = `${resolvedName}/${key}`;
270
- }
271
- const response = await request(state, getClient(state), path, { query: q });
282
+ const {
283
+ key = "*",
284
+ limit,
285
+ pageSize,
286
+ ...userQuery
287
+ } = expandQuery(resolvedQuery);
288
+ console.log(`Collections: Downloading data from "${name}"...`);
272
289
  let data;
273
- if (q) {
290
+ if (key.match(/\*/) || Object.keys(userQuery).length) {
274
291
  data = [];
275
- console.log(`Downloading data from collection "${name}"...`);
276
- const cursor = await streamResponse(response, (item) => {
277
- item.value = JSON.parse(item.value);
278
- data.push(item);
279
- });
280
- data.cursor = cursor;
281
- console.log(`Fetched "${data.length}" values from collection "${name}"`);
292
+ const scopedState = {
293
+ ...state,
294
+ data: {}
295
+ };
296
+ await each(name, resolvedQuery, (state2, value, key2) => {
297
+ data.push({ value, key: key2 });
298
+ })(scopedState);
299
+ console.log(
300
+ `Collections: Fetched total of ${data.length} values from "${name}"`
301
+ );
302
+ data.cursor = scopedState.data.cursor;
282
303
  } else {
304
+ const response = await request(
305
+ state,
306
+ getClient(state),
307
+ `${resolvedName}/${key}`
308
+ );
283
309
  const body = await response.body.json();
284
310
  if (body.value) {
285
311
  data = JSON.parse(body.value);
286
- console.log(`Fetched "${key}" from collection "${name}"`);
312
+ console.log(`Collections: Fetched "${key}" from "${name}"`);
287
313
  } else {
288
314
  data = {};
289
- console.warn(`Key "${key}" not found in collection "${name}"`);
315
+ console.warn(`Collections: Key "${key}" not found in "${name}"`);
290
316
  }
291
317
  }
292
318
  state.data = data;
@@ -315,7 +341,7 @@ function set(name, keyGen, values) {
315
341
  });
316
342
  if (response.statusCode >= 400) {
317
343
  console.log(
318
- `Error setting ${pairs.length} values in collection "${name}"`
344
+ `Collections: Error setting ${pairs.length} values in "${name}"`
319
345
  );
320
346
  const text = await response.body.text();
321
347
  const e = new Error("ERROR from collections server:" + 400);
@@ -323,9 +349,9 @@ function set(name, keyGen, values) {
323
349
  throw e;
324
350
  }
325
351
  const result = await response.body.json();
326
- console.log(`Set ${result.upserted} values in collection "${name}"`);
352
+ console.log(`Collections: set ${result.upserted} values in "${name}"`);
327
353
  if (result.error) {
328
- console.log(`Errors reported on set:`, result.error);
354
+ console.log(`Collections: errors reported on set:`, result.error);
329
355
  }
330
356
  return state;
331
357
  };
@@ -349,7 +375,7 @@ function remove(name, query = {}, options = {}) {
349
375
  query: q
350
376
  });
351
377
  const result = await response.body.json();
352
- console.log(`Removed ${result.deleted} values in collection "${name}"`);
378
+ console.log(`Collections: Removed ${result.deleted} values in "${name}"`);
353
379
  return state;
354
380
  };
355
381
  }
@@ -363,13 +389,36 @@ function each(name, query = {}, callback = () => {
363
389
  } else {
364
390
  q = resolvedQuery;
365
391
  }
366
- const { key, ...rest } = expandQuery(resolvedQuery);
367
- const response = await request(state, getClient(state), resolvedName, {
368
- query: q
369
- });
370
- const cursor = await streamResponse(response, async ({ value, key: key2 }) => {
371
- await callback(state, JSON.parse(value), key2);
372
- });
392
+ const {
393
+ key = "*",
394
+ pageSize = 1e3,
395
+ limit = Infinity,
396
+ ...finalQuery
397
+ } = expandQuery(resolvedQuery);
398
+ let { cursor } = resolvedQuery;
399
+ let count = 0;
400
+ do {
401
+ let batchSize = 0;
402
+ const q2 = {
403
+ ...finalQuery,
404
+ key,
405
+ limit: limit < Infinity ? Math.min(pageSize, limit - count) : pageSize
406
+ };
407
+ if (cursor) {
408
+ q2.cursor = cursor;
409
+ }
410
+ const response = await request(state, getClient(state), resolvedName, {
411
+ query: q2
412
+ });
413
+ cursor = await streamResponse(response, async ({ key: key2, value }) => {
414
+ batchSize++;
415
+ await callback(state, JSON.parse(value), key2);
416
+ });
417
+ count += batchSize;
418
+ console.log(
419
+ `Collections: fetched chunk of ${batchSize} values from "${name}"`
420
+ );
421
+ } while (cursor && count < limit);
373
422
  state.data = {
374
423
  cursor
375
424
  };
@@ -398,6 +447,7 @@ var streamResponse = async (response, onValue) => {
398
447
  if (next.value.value === "cursor") {
399
448
  const strValue = await waitFor("stringChunk", "nullValue");
400
449
  if (strValue.name === "nullValue") {
450
+ cursor = null;
401
451
  continue;
402
452
  }
403
453
  cursor = strValue.value.value;
@@ -443,9 +493,7 @@ var expandQuery = (query) => {
443
493
  };
444
494
  var queryMaps = {
445
495
  createdBefore: "created_before",
446
- createdAfter: "created_after",
447
- updatedBefore: "updated_before",
448
- updatedAfter: "updated_after"
496
+ createdAfter: "created_after"
449
497
  };
450
498
  var parseQuery = (options = {}) => {
451
499
  return Object.keys(options.query ?? {}).reduce((result, next) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openfn/language-collections",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "OpenFn collections adaptor",
5
5
  "type": "module",
6
6
  "exports": {
@@ -5,9 +5,8 @@
5
5
  * @property {string} key - key or key pattern to match against. Patterns support wildcards, eg `2024-01*`
6
6
  * @property {string} createdBefore - matches values that were created before the start of the provided date
7
7
  * @property {string} createdAfter - matches values that were created after the end of the provided date
8
- * @property {string} updatedBefore - matches values that were updated before the start of the provided date
9
- * @property {string} updatedAfter - matches values that were updated after the end of the provided date*
10
- * @property {number} limit - limit the maximum amount of results. Defaults to 1000.
8
+ * @property {number} limit - limit the maximum amount of results. If Infinity or unset, all items will be fetched. Default: Infnity.
9
+ * @property {number} pageSize - specify the number of values downloaded per page (or chunk). Default 1000.
11
10
  * @property {string} cursor - set the cursor position to start searching from a specific index.
12
11
  */
13
12
  /**
@@ -69,6 +68,8 @@ export function remove(name: string, query?: string | QueryOptions, options?: {}
69
68
  * You can pass a string key-pattern as a query, or pass a query object.
70
69
  * The callback function will be invoked for each value with three parameters:
71
70
  * `state`, `value` and `key`.
71
+ * Changing the page size does not affect the callback function (only one item is
72
+ * ever passed at a time).
72
73
  * @public
73
74
  * @function
74
75
  * @param {string} name - The name of the collection to remove from
@@ -80,7 +81,7 @@ export function remove(name: string, query?: string | QueryOptions, options?: {}
80
81
  * state.cumulativeCost += value.cost;
81
82
  * })
82
83
  * @example <caption>Iterate over a range of values with date filters</caption>
83
- * collections.each('my-collection', { updatedBefore: new Date().toString() }, (state, value, key) => {
84
+ * collections.each('my-collection', { createdBefore: new Date().toString() }, (state, value, key) => {
84
85
  * state.cumulativeCost += value.cost;
85
86
  * })
86
87
  */
package/types/mock.d.ts CHANGED
@@ -3,11 +3,12 @@ export function API(): {
3
3
  createCollection: (name: any, values?: {}) => void;
4
4
  reset: () => void;
5
5
  upsert: (name: any, key: any, value: any) => void;
6
- fetch: (name: any, key: any, query: any) => {
6
+ fetch: (name: any, key: any, query?: {}) => {
7
7
  items: {
8
8
  key: string;
9
9
  value: any;
10
10
  }[];
11
+ count: number;
11
12
  };
12
13
  remove: (name: any, key: any) => string[];
13
14
  byKey: (name: any, key: any) => any;