@jskit-ai/connectors-core 0.2.22 → 0.2.24

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/CHANGELOG.md CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - A connection's status reads its row without a transaction or lock, and no longer creates an empty row for every person and integration whose status is viewed. `status()` calls `withConnection(slot, work, { readOnly: true })`; the SQL store reads the row with a plain get for such work, and the file store and a custom store that ignores the option still answer correctly.
5
6
  - connector_authorization_attempts declares its foreign key, connection_key to connector_connections.connection_key (`foreignKeys`), so json-rest-api 3.1.0 can skip the visibility query a system-context read makes for a record such a key guarantees exists. `jskit test --databases` checks each against an app's test database. `knexConnectionStore.test.js` proves it matches the migration on the connector test database.
6
7
  - `@jskit-ai/database-runtime` and `@jskit-ai/resource-runtime` are optional peer dependencies, as they are of assistant-runtime, instead of dependencies: an app without a database installs, composes and starts the package without them, where installing them made boot refuse it for want of a database driver. An app that uses its knex connection store (`./server/storage`) has them through its database.
7
8
  - `createKnexConnectionStore` owns the connector tables through resource-runtime's `createStandaloneResources`, with the connection store's declared system scope, instead of building a resource runtime and host of its own.
package/README.md CHANGED
@@ -479,6 +479,10 @@ consuming it. Consumption must
479
479
  affect only the current owner and slot. Removal also invalidates pending
480
480
  attempts. Failures returned by the runtime are thrown after commit so failed
481
481
  API requests do not roll back rotated refresh tokens or restore consumed codes.
482
+ A status read calls `withConnection(slot, work, { readOnly: true })`: its work
483
+ only reads `connection`, so a store may skip the lock and must not create the
484
+ connection; the SQL store reads the row without a transaction, and a store that
485
+ ignores the option still answers correctly.
482
486
 
483
487
  ## Current limits and proof
484
488
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/connectors-core",
3
- "version": "0.2.22",
3
+ "version": "0.2.24",
4
4
  "description": "Portable integration configuration and server-side account connection runtime.",
5
5
  "type": "module",
6
6
  "scripts": {
@@ -15,9 +15,9 @@
15
15
  "./locales/en.json": "./locales/en.json"
16
16
  },
17
17
  "dependencies": {
18
- "@jskit-ai/resource-core": "0.1.208",
18
+ "@jskit-ai/resource-core": "0.1.209",
19
19
  "jose": "^6.1.3",
20
- "json-rest-schema": "^1.0.17",
20
+ "json-rest-schema": "^1.0.20",
21
21
  "oauth4webapi": "3.8.8",
22
22
  "proper-lockfile": "4.1.2"
23
23
  },
@@ -56,10 +56,10 @@
56
56
  }
57
57
  },
58
58
  "peerDependencies": {
59
- "@jskit-ai/database-runtime": "0.1.266",
60
- "@jskit-ai/http-runtime": "0.2.17",
61
- "@jskit-ai/kernel": "0.2.17",
62
- "@jskit-ai/resource-runtime": "0.2.19"
59
+ "@jskit-ai/database-runtime": "0.1.267",
60
+ "@jskit-ai/http-runtime": "0.2.18",
61
+ "@jskit-ai/kernel": "0.2.18",
62
+ "@jskit-ai/resource-runtime": "0.2.21"
63
63
  },
64
64
  "peerDependenciesMeta": {
65
65
  "@jskit-ai/database-runtime": {
@@ -486,7 +486,7 @@ function createConnectionService({
486
486
  return publicConnection({ ...connection, status: "reconnect-required" });
487
487
  }
488
488
  return { ...publicConnection(connection), ...(callbackUrl ? { callbackUrl } : {}) };
489
- });
489
+ }, { readOnly: true });
490
490
  }
491
491
 
492
492
  /** @param {import("./types.js").IntegrationRequest} request */
@@ -16,7 +16,8 @@ function requireProtection(protection) {
16
16
 
17
17
  /**
18
18
  * Connections kept encrypted in the connector tables, on their table resources' handles, each locked in a transaction
19
- * while it is used. Every call works in a system context, because a row's scope is its key.
19
+ * while it is used, unless the work only reads it. Every call works in a system context, because a row's scope is
20
+ * its key.
20
21
  * @param {object} dependencies
21
22
  * @param {Record<string, import("@jskit-ai/resource-runtime/server/types").ResourceHandle>} dependencies.resources The handles of CONNECTOR_TABLES.
22
23
  * @param {(reason: string) => import("@jskit-ai/resource-runtime/server/types").SystemContext} dependencies.systemContext
@@ -28,9 +29,14 @@ function createConnectionStore({ resources, systemContext, protection }) {
28
29
  const connectionOptions = Object.freeze({ context: systemContext("a connection and its attempts are read and changed by their owner and integration key") });
29
30
  const pruneOptions = Object.freeze({ context: systemContext("maintenance prunes every connection's expired authorization attempts") });
30
31
 
31
- async function withConnection({ owner, integrationId }, work) {
32
+ async function withConnection({ owner, integrationId }, work, { readOnly = false } = {}) {
32
33
  const connectionKey = hash(JSON.stringify([owner.applicationId, owner.subjectId, integrationId]));
33
34
  const connectionBinding = `connection:${connectionKey}`;
35
+ if (readOnly) {
36
+ // Work that only reads takes no lock and creates no row.
37
+ const row = await connections.get(connectionKey, {}, { ...connectionOptions, missing: "skip" });
38
+ return work({ connection: row?.payload ? await protection.open(row.payload, connectionBinding) : null });
39
+ }
34
40
  // Retain this row on disconnect so other processes continue to lock the same identity.
35
41
  return connections.lockOrCreate({ id: connectionKey, payload: null }, connectionOptions, async (row, txOptions) => {
36
42
  const writeOptions = { ...txOptions, returning: "none" };
@@ -38,8 +38,8 @@ function createKnexConnectionStore({ knex, protection }) {
38
38
  return ready;
39
39
  }
40
40
 
41
- async function withConnection(slot, work) {
42
- return (await store()).withConnection(slot, work);
41
+ async function withConnection(slot, work, options) {
42
+ return (await store()).withConnection(slot, work, options);
43
43
  }
44
44
  async function pruneExpiredAttempts(options) {
45
45
  return (await store()).pruneExpiredAttempts(options);
@@ -70,7 +70,9 @@
70
70
  * Where connections are kept: createKnexConnectionStore(),
71
71
  * createFileConnectionStore() or the application's own store.
72
72
  * @typedef {object} ConnectionStore
73
- * @property {<T>(slot: { owner: ConnectionOwner, integrationId: string }, work: (record: ConnectionRecord) => Promise<T>) => Promise<T>} withConnection
73
+ * @property {<T>(slot: { owner: ConnectionOwner, integrationId: string }, work: (record: ConnectionRecord) => Promise<T>, options?: { readOnly?: boolean }) => Promise<T>} withConnection
74
+ * Runs the work with the connection locked. With `readOnly`, the work only reads `connection`, and the store may
75
+ * skip the lock and the row it would otherwise create.
74
76
  */
75
77
 
76
78
  /**
@@ -9,9 +9,33 @@ import { createCapabilityRuntime, defineProvider } from "@jskit-ai/kernel/shared
9
9
  import { createTestResourceRuntime } from "@jskit-ai/resource-runtime/test";
10
10
  import migration from "../migrations/connectors_core_initial.cjs";
11
11
  import { createConnectionStoreFeature, createCredentialProtection } from "../src/server/storage.js";
12
+ import { createConnectionService } from "../src/server/index.js";
13
+ import { clickhouseProvider } from "../../connectors-catalog/src/server/clickhouse.js";
12
14
 
13
15
  const owner = Object.freeze({ applicationId: "app", subjectId: "user-1" });
14
16
 
17
+ async function startStore(t) {
18
+ const knex = knexLib({ client: "better-sqlite3", connection: { filename: ":memory:" }, useNullAsDefault: true, pool: { min: 1, max: 1 } });
19
+ t.after(() => knex.destroy());
20
+ await migration.up(knex);
21
+ const resources = await createTestResourceRuntime({ knex });
22
+ const protection = createCredentialProtection({ keys: { current: randomBytes(32) }, activeKeyId: "current" });
23
+ let store = null;
24
+ const runtime = createCapabilityRuntime({
25
+ inputs: { "runtime.logger": silentLogger },
26
+ providers: [
27
+ EventProvider,
28
+ ActionProvider,
29
+ defineProvider({ id: "test.resources", provides: { resources: "runtime.resources" }, setup: () => ({ resources }) }),
30
+ createConnectionStoreFeature({ protection }),
31
+ defineProvider({ id: "test.connections", requires: { connections: "connectors.store" }, setup({ connections }) { store = connections; } })
32
+ ]
33
+ });
34
+ await runtime.start();
35
+ t.after(() => runtime.shutdown());
36
+ return { knex, store };
37
+ }
38
+
15
39
  test("createConnectionStoreFeature owns the connector tables and provides the store on their handles as connectors.store", async (t) => {
16
40
  const knex = knexLib({ client: "better-sqlite3", connection: { filename: ":memory:" }, useNullAsDefault: true, pool: { min: 1, max: 1 } });
17
41
  t.after(() => knex.destroy());
@@ -51,3 +75,33 @@ test("createConnectionStoreFeature owns the connector tables and provides the st
51
75
  await store.withConnection(slot, ({ putAttempt }) => putAttempt({ state: "s2", expiresAt: 3_000 }));
52
76
  assert.equal(await store.pruneExpiredAttempts({ before: 3_000 }), 1);
53
77
  });
78
+
79
+ test("a status read takes no lock and creates no connection row", async (t) => {
80
+ const { knex, store } = await startStore(t);
81
+ const statements = [];
82
+ const record = ({ sql }) => statements.push(sql);
83
+ knex.on("query", record);
84
+ t.after(() => knex.off("query", record));
85
+ const service = createConnectionService({
86
+ configuration: { schemaVersion: 1, registrations: {}, integrations: { database: {
87
+ provider: "clickhouse", accountMode: "shared", scopes: [], authentication: { method: "none" },
88
+ settings: { httpUrl: "https://database.example:8443/" }
89
+ } } },
90
+ providers: [clickhouseProvider],
91
+ store,
92
+ authorize: async (context) => context,
93
+ resolveReference: async () => "",
94
+ fetchImpl: async () => Response.json({ meta: [], data: [{ ok: 1, user: "default" }], rows: 1 })
95
+ });
96
+ const input = { context: owner, integrationId: "database" };
97
+ const rowCount = async () => Number((await knex("connector_connections").count({ count: "*" }).first()).count);
98
+
99
+ const before = await service.status(input);
100
+ assert.notEqual(before.status, "connected");
101
+ assert.equal(await rowCount(), 0);
102
+ await service.connectWithoutCredentials(input);
103
+ statements.length = 0;
104
+ assert.equal((await service.status(input)).status, "connected");
105
+ assert.equal(await rowCount(), 1);
106
+ assert.deepEqual(statements.filter((sql) => !/^select/iu.test(sql)), [], statements.join("\n"));
107
+ });