@sema-agent/core-stores-sql 7.74.0 → 7.74.1-main.gb6563676503c99e9b20ede6bb7f4c5992b87e841
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 +43 -12
- package/dist/backend.d.ts +2 -3
- package/dist/driver-runtime.d.ts +10 -0
- package/dist/driver-runtime.js +377 -0
- package/dist/driver.d.ts +13 -4
- package/dist/driver.js +7 -3
- package/dist/notice.d.ts +4 -2
- package/dist/refusal.d.ts +4 -2
- package/dist/refusal.js +1 -1
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -8,16 +8,15 @@ make once over that pool, its words, its notices and the codes every refusal of
|
|
|
8
8
|
ships only in-memory and file-backed stores, so a database-backed backend is built behind this face rather than inside
|
|
9
9
|
core. Ships its own types; ES modules only.
|
|
10
10
|
|
|
11
|
-
## Read this first: this release carries no SQL stores
|
|
11
|
+
## Read this first: this release carries the driver and no SQL stores
|
|
12
12
|
|
|
13
|
-
The published versions so far fix the package's public face and how it is built, checked and released
|
|
14
|
-
carry the stores yet. `
|
|
15
|
-
(refusing each wrong value by name) and
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
release notes, the same as for core's own exports.
|
|
13
|
+
The published versions so far fix the package's public face and how it is built, checked and released, and this one
|
|
14
|
+
carries the driver; they do not carry the stores yet. `createSqlDriver` checks the version pairing, reads its options
|
|
15
|
+
(refusing each wrong value by name) and returns the driver it made. `createSqlStorageBackend` checks the pairing and
|
|
16
|
+
reads its options the same way — the backend reads a driver `createSqlDriver` made and then refuses: it does not return
|
|
17
|
+
an object without its stores (`core-stores-sql.release.not-carried`). `baselineDdl(dialect)` resolves to an empty list
|
|
18
|
+
and `publishedColumns()` returns an empty list. A later release fills the face in; a removed or re-kinded name is called
|
|
19
|
+
out as breaking in the `@sema-agent/core` release notes, the same as for core's own exports.
|
|
21
20
|
|
|
22
21
|
## How a deployment wires it
|
|
23
22
|
|
|
@@ -54,11 +53,27 @@ try {
|
|
|
54
53
|
member of the sink's third argument (`SqlNoticeFacts`), never a word read out of the detail: `seat`, the store seat
|
|
55
54
|
the step was taken for (`SqlNoticeSeat`, a member name of core's storage backend contract — `"sessionStore"`, …),
|
|
56
55
|
on every store's notice and absent on the driver's. A detail
|
|
57
|
-
never repeats a cell's content or an error's text. The
|
|
58
|
-
|
|
59
|
-
`createSqlDriver` made, and
|
|
56
|
+
never repeats a cell's content or an error's text. The driver tells its two wall reads (`driver.tidb-row-cap-unread`,
|
|
57
|
+
`driver.packet-cap-unread`); the other tags are declared here and arrive with the stores. The backend takes only a
|
|
58
|
+
driver `createSqlDriver` made, and
|
|
60
59
|
`isSqlDriver(value)` answers whether a value is one — an object of the same shape is not. A statement's third
|
|
61
60
|
argument, `{ deadlineMs }`, is the longest it may run.
|
|
61
|
+
- **What the driver does.** A connection is lent only once its session reads back what the driver set, and every
|
|
62
|
+
statement — `driver.query` and a lent connection's `query` — runs on such a connection. The first time a pooled
|
|
63
|
+
connection is lent, the driver sets its isolation level and reads it back (REPEATABLE READ on the MySQL protocol, with
|
|
64
|
+
TiDB switched to its pessimistic transaction mode; READ COMMITTED on PostgreSQL), then reads the engine's facts; a later
|
|
65
|
+
lending reads the session back in one statement (the isolation, TiDB's mode, the packet wall when one was read) and initializes again if
|
|
66
|
+
it was reset or the wall moved (mysql2's `resetOnRelease`, a `DISCARD ALL`) — one round trip per lending is the price.
|
|
67
|
+
`affected` counts a write only where the answer says it was one; where it does not, a statement that answers rows reports 0 (read
|
|
68
|
+
`rows.length`). `driver.query` borrows such a connection for the one
|
|
69
|
+
statement and returns it; the pool's own `query` is not called. Borrowing, initializing and reading back refuse
|
|
70
|
+
`driver.init-unreached` (transient) when the connection broke, timed out or there is no connection to give now, and
|
|
71
|
+
`driver.init-refused` (terminal) otherwise, the driver's error as the `cause`; a refused initialization or read-back empties `driver.facts` until the
|
|
72
|
+
next lending succeeds. A lent connection whose statement fails because the connection is gone — or, on node-postgres, a
|
|
73
|
+
client that emits `error` while lent — is destroyed, never returned to your pool. A statement past its `deadlineMs`
|
|
74
|
+
(counted from when it is sent) destroys its connection and refuses `statement.deadline`: the database may already have
|
|
75
|
+
applied it, so a write that is not idempotent can be applied twice if you retry it. A wall the engine will not report
|
|
76
|
+
takes the engine family's documented default (`wallSources` says `assumed`) and tells the sink.
|
|
62
77
|
- **A refusal** of this package — any of its calls, at startup or later — is an `Error` whose `code` is one key of
|
|
63
78
|
`SQL_ERROR_CODES`; the table's value says whether repeating the same call can succeed (`transient`) or not until
|
|
64
79
|
something named changes (`terminal`). Read it with `sqlFaultOf(caught)`, which reads the `code` member and nothing
|
|
@@ -119,6 +134,22 @@ The planned consumer is a deployment that already owns SQL stores: `@sema-agent/
|
|
|
119
134
|
is the first use in view (planned, not shipped). It would build the backend from its own pool and hand the result to
|
|
120
135
|
core's storage seats. Nothing in this package depends on that.
|
|
121
136
|
|
|
137
|
+
## Published columns
|
|
138
|
+
|
|
139
|
+
A deployment that reads this package's tables in its own SQL — a join, a subquery, a cleanup predicate, a foreign key —
|
|
140
|
+
reads only the columns listed here; every other column of every table the package creates is the package's own and
|
|
141
|
+
may change in any release. Each listed column is a projection of the core face named beside it, never a second way
|
|
142
|
+
to answer that question. A listed column's meaning and its declaration (its type and nullability, the table
|
|
143
|
+
constraints and unique indexes that name it, the table's options such as its collation) are part of the package's
|
|
144
|
+
public face: removing
|
|
145
|
+
one, or changing any of these, is named column by column in the `@sema-agent/core` release notes and in the package's
|
|
146
|
+
wire-change manifest (a lost member of `publishedColumns`). A write to these tables goes through core's contracts
|
|
147
|
+
only. `publishedColumns()` returns this list.
|
|
148
|
+
|
|
149
|
+
<!-- published-columns:begin -->
|
|
150
|
+
This release publishes no column: no column of a table this package creates is one a deployment may read.
|
|
151
|
+
<!-- published-columns:end -->
|
|
152
|
+
|
|
122
153
|
## Install
|
|
123
154
|
|
|
124
155
|
```sh
|
package/dist/backend.d.ts
CHANGED
|
@@ -5,9 +5,8 @@
|
|
|
5
5
|
* the backend-level managed-retention executor, creates and migrates its own tables, and runs the age and orphan
|
|
6
6
|
* sweeps over them. Releasing it is the contract's `dispose()`; there is no second release verb.
|
|
7
7
|
*
|
|
8
|
-
* In this version the package carries
|
|
9
|
-
* refused by name, the driver last) and then refuses:
|
|
10
|
-
* call, and a backend whose seats are missing is never returned.
|
|
8
|
+
* In this version the package carries the driver and no SQL stores, so the factory reads its options (each wrong value
|
|
9
|
+
* refused by name, the driver last) and then refuses: a backend whose seats are missing is never returned.
|
|
11
10
|
*/
|
|
12
11
|
import type { EngineStorageBackend, ManagedRetentionCapability, SessionLogTransfer, SessionStore } from "@sema-agent/core";
|
|
13
12
|
import { type SqlSessionCall, type SqlStorageBackendOptions } from "./options.js";
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { MysqlPoolLike, PgPoolLike, SqlDriver } from "./driver.js";
|
|
2
|
+
import type { SqlNoticeSink } from "./notice.js";
|
|
3
|
+
/** Whether `error` is one of the table's: the connection is gone, or there is no connection to give now. */
|
|
4
|
+
export declare function isConnectionGone(error: unknown): boolean;
|
|
5
|
+
/** The MySQL-protocol driver. A mysql2 checkout is a fresh wrapper each time; the pooled connection it wraps (its
|
|
6
|
+
* `connection` member) names the connection across lendings. Transaction verbs are mysql2's own methods. */
|
|
7
|
+
export declare function mysqlDriver(pool: MysqlPoolLike, sink: SqlNoticeSink | undefined): SqlDriver;
|
|
8
|
+
/** The PostgreSQL driver. node-postgres hands back the same client object for the same pooled connection; transaction
|
|
9
|
+
* verbs are statements; `release(true)` destroys the client. */
|
|
10
|
+
export declare function pgDriver(pool: PgPoolLike, sink: SqlNoticeSink | undefined): SqlDriver;
|
|
@@ -0,0 +1,377 @@
|
|
|
1
|
+
import { callerText } from "@sema-agent/core";
|
|
2
|
+
import { memberOf, refusal, sqlFaultOf } from "./refusal.js";
|
|
3
|
+
import { refuseUnknownKeys } from "./driver.js";
|
|
4
|
+
const GONE_CODES = new Set([
|
|
5
|
+
"ECONNRESET", "ECONNREFUSED", "ECONNABORTED", "EPIPE", "ETIMEDOUT", "EHOSTUNREACH", "ENETUNREACH", "EAI_AGAIN",
|
|
6
|
+
"PROTOCOL_CONNECTION_LOST",
|
|
7
|
+
"ER_CON_COUNT_ERROR", "ER_SERVER_SHUTDOWN", "ER_ABORTING_CONNECTION", "ER_NET_PACKET_TOO_LARGE", "ER_NET_READ_ERROR", "ER_NET_READ_INTERRUPTED",
|
|
8
|
+
"ER_NET_ERROR_ON_WRITE", "ER_NET_WRITE_INTERRUPTED", "ER_CONNECTION_KILLED", "ER_CLIENT_INTERACTION_TIMEOUT",
|
|
9
|
+
"ER_OPTION_PREVENTS_STATEMENT", "ER_CANT_EXECUTE_IN_READ_ONLY_TRANSACTION", "ER_READ_ONLY_MODE",
|
|
10
|
+
"08000", "08001", "08003", "08006", "57P01", "57P02", "57P03", "53300", "25006",
|
|
11
|
+
]);
|
|
12
|
+
const GONE_ERRNOS = new Set([1040, 1053, 1152, 1153, 1158, 1159, 1160, 1161, 1927, 4031, 1290, 1792, 1836]);
|
|
13
|
+
const GONE_SENTENCES = new Set([
|
|
14
|
+
"Connection terminated unexpectedly",
|
|
15
|
+
"Client has encountered a connection error and is not queryable",
|
|
16
|
+
"Connection terminated due to connection timeout",
|
|
17
|
+
"timeout exceeded when trying to connect",
|
|
18
|
+
"Can't add new command when connection is in closed state",
|
|
19
|
+
"No connections available.",
|
|
20
|
+
"Queue limit reached.",
|
|
21
|
+
]);
|
|
22
|
+
export function isConnectionGone(error) {
|
|
23
|
+
const code = memberOf(error, "code");
|
|
24
|
+
const errno = memberOf(error, "errno");
|
|
25
|
+
if (typeof code === "string" && GONE_CODES.has(code))
|
|
26
|
+
return true;
|
|
27
|
+
if (typeof errno === "number" && GONE_ERRNOS.has(errno))
|
|
28
|
+
return true;
|
|
29
|
+
return error instanceof Error && code === undefined && GONE_SENTENCES.has(error.message);
|
|
30
|
+
}
|
|
31
|
+
const MAX_TIMER_MS = 2_147_483_647;
|
|
32
|
+
function readDeadline(entry, opts) {
|
|
33
|
+
if (opts === undefined)
|
|
34
|
+
return undefined;
|
|
35
|
+
if (typeof opts !== "object" || opts === null || Array.isArray(opts))
|
|
36
|
+
throw refusal("core-stores-sql.options.invalid", entry, `the statement's options must be an object when given (got ${callerText(opts)})`);
|
|
37
|
+
refuseUnknownKeys(entry, "the statement's options", opts, ["deadlineMs"]);
|
|
38
|
+
const ms = opts.deadlineMs;
|
|
39
|
+
if (ms === undefined)
|
|
40
|
+
return undefined;
|
|
41
|
+
if (typeof ms !== "number" || !Number.isInteger(ms) || ms <= 0 || ms > MAX_TIMER_MS) {
|
|
42
|
+
throw refusal("core-stores-sql.options.invalid", entry, `deadlineMs must be a positive integer of milliseconds no larger than ${MAX_TIMER_MS} (got ${callerText(ms)})`);
|
|
43
|
+
}
|
|
44
|
+
return ms;
|
|
45
|
+
}
|
|
46
|
+
function leaseOf(raw) {
|
|
47
|
+
let destroyed = false;
|
|
48
|
+
let released = false;
|
|
49
|
+
let returned = false;
|
|
50
|
+
let pending = 0;
|
|
51
|
+
let leaveQueue = () => undefined;
|
|
52
|
+
const gone = new Promise((resolve) => {
|
|
53
|
+
leaveQueue = resolve;
|
|
54
|
+
});
|
|
55
|
+
let turn = Promise.resolve();
|
|
56
|
+
const destroy = () => {
|
|
57
|
+
if (destroyed || returned)
|
|
58
|
+
return;
|
|
59
|
+
destroyed = true;
|
|
60
|
+
leaveQueue();
|
|
61
|
+
raw.destroy();
|
|
62
|
+
};
|
|
63
|
+
const unwatch = raw.watch?.(destroy);
|
|
64
|
+
const giveBackIfIdle = () => {
|
|
65
|
+
if (!released || destroyed || returned || pending > 0)
|
|
66
|
+
return;
|
|
67
|
+
returned = true;
|
|
68
|
+
unwatch?.();
|
|
69
|
+
raw.release();
|
|
70
|
+
};
|
|
71
|
+
const serial = (run) => {
|
|
72
|
+
pending += 1;
|
|
73
|
+
const result = Promise.race([turn, gone])
|
|
74
|
+
.then(async () => {
|
|
75
|
+
try {
|
|
76
|
+
return await run();
|
|
77
|
+
}
|
|
78
|
+
catch (error) {
|
|
79
|
+
if (isConnectionGone(error))
|
|
80
|
+
destroy();
|
|
81
|
+
throw error;
|
|
82
|
+
}
|
|
83
|
+
})
|
|
84
|
+
.finally(() => {
|
|
85
|
+
pending -= 1;
|
|
86
|
+
giveBackIfIdle();
|
|
87
|
+
});
|
|
88
|
+
turn = result.then(() => undefined, () => undefined);
|
|
89
|
+
return result;
|
|
90
|
+
};
|
|
91
|
+
return {
|
|
92
|
+
run: (entry, sql, params, deadlineMs) => serial(() => (deadlineMs === undefined ? raw.run(sql, params) : withDeadline(entry, raw.run(sql, params), deadlineMs, destroy))),
|
|
93
|
+
verb: (name) => serial(async () => {
|
|
94
|
+
if (name === "rollback" && destroyed)
|
|
95
|
+
return;
|
|
96
|
+
await raw[name]();
|
|
97
|
+
}),
|
|
98
|
+
release: () => {
|
|
99
|
+
released = true;
|
|
100
|
+
giveBackIfIdle();
|
|
101
|
+
},
|
|
102
|
+
destroy,
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
function withDeadline(entry, running, deadlineMs, destroy) {
|
|
106
|
+
running.catch(() => undefined);
|
|
107
|
+
let timer;
|
|
108
|
+
const expired = new Promise((_, reject) => {
|
|
109
|
+
timer = setTimeout(() => {
|
|
110
|
+
destroy();
|
|
111
|
+
reject(refusal("core-stores-sql.statement.deadline", entry, `the statement did not settle within ${deadlineMs}ms — its connection was destroyed (an open transaction rolls back when it closes); the database may still have applied it`));
|
|
112
|
+
}, deadlineMs);
|
|
113
|
+
});
|
|
114
|
+
return Promise.race([running, expired]).finally(() => clearTimeout(timer));
|
|
115
|
+
}
|
|
116
|
+
const POOL_SESSIONS = new WeakMap();
|
|
117
|
+
function poolSession(pool) {
|
|
118
|
+
let session = POOL_SESSIONS.get(pool);
|
|
119
|
+
if (session === undefined)
|
|
120
|
+
POOL_SESSIONS.set(pool, (session = { facts: null, records: new WeakMap() }));
|
|
121
|
+
return session;
|
|
122
|
+
}
|
|
123
|
+
async function readsBack(lease, record) {
|
|
124
|
+
const row = (await lease.run(CONNECT, record.check.sql, [])).rows[0];
|
|
125
|
+
return Object.entries(record.check.expect).every(([column, value]) => row !== undefined && String(row[column]) === value);
|
|
126
|
+
}
|
|
127
|
+
function tellerOf(sink) {
|
|
128
|
+
return (tag, detail) => {
|
|
129
|
+
if (sink === undefined)
|
|
130
|
+
return;
|
|
131
|
+
try {
|
|
132
|
+
sink(tag, detail, {});
|
|
133
|
+
}
|
|
134
|
+
catch {
|
|
135
|
+
}
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
const CONNECT = "SqlDriver.connect";
|
|
139
|
+
function lentOver(lease, facts) {
|
|
140
|
+
const run = async (entry, sql, params, opts) => lease.run(entry, sql, params ?? [], readDeadline(entry, opts));
|
|
141
|
+
const conn = Object.freeze({
|
|
142
|
+
query: (sql, params, opts) => run("SqlTxConn.query", sql, params, opts),
|
|
143
|
+
begin: () => lease.verb("begin"),
|
|
144
|
+
commit: () => lease.verb("commit"),
|
|
145
|
+
rollback: () => lease.verb("rollback"),
|
|
146
|
+
release: lease.release,
|
|
147
|
+
facts,
|
|
148
|
+
});
|
|
149
|
+
return { conn, run };
|
|
150
|
+
}
|
|
151
|
+
function driverOver(dialect, pool, borrow, initialize, tell) {
|
|
152
|
+
const session = poolSession(pool);
|
|
153
|
+
const lend = async () => {
|
|
154
|
+
let lease;
|
|
155
|
+
try {
|
|
156
|
+
const borrowed = await borrow();
|
|
157
|
+
lease = leaseOf(borrowed.raw);
|
|
158
|
+
let record = session.records.get(borrowed.identity);
|
|
159
|
+
if (record === undefined || !(await readsBack(lease, record))) {
|
|
160
|
+
record = await initialize(lease, tell);
|
|
161
|
+
session.records.set(borrowed.identity, record);
|
|
162
|
+
session.facts = record.facts;
|
|
163
|
+
}
|
|
164
|
+
return lentOver(lease, record.facts);
|
|
165
|
+
}
|
|
166
|
+
catch (error) {
|
|
167
|
+
if (lease !== undefined) {
|
|
168
|
+
session.facts = null;
|
|
169
|
+
session.records = new WeakMap();
|
|
170
|
+
lease.destroy();
|
|
171
|
+
}
|
|
172
|
+
if (sqlFaultOf(error) !== undefined)
|
|
173
|
+
throw error;
|
|
174
|
+
const what = lease === undefined ? "the pool could not lend a connection" : "the database did not complete this connection's initialization";
|
|
175
|
+
if (isConnectionGone(error))
|
|
176
|
+
throw refusal("core-stores-sql.driver.init-unreached", CONNECT, `${what}: the connection broke, timed out, or there is no connection to give now — a later try can succeed (the driver's error is the cause)`, error);
|
|
177
|
+
throw refusal("core-stores-sql.driver.init-refused", CONNECT, `${what}: the database refused it (the driver's error is the cause)`, error);
|
|
178
|
+
}
|
|
179
|
+
};
|
|
180
|
+
return Object.freeze({
|
|
181
|
+
dialect,
|
|
182
|
+
get facts() {
|
|
183
|
+
return session.facts;
|
|
184
|
+
},
|
|
185
|
+
query: async (sql, params, opts) => {
|
|
186
|
+
readDeadline("SqlDriver.query", opts);
|
|
187
|
+
const lent = await lend();
|
|
188
|
+
try {
|
|
189
|
+
return await lent.run("SqlDriver.query", sql, params, opts);
|
|
190
|
+
}
|
|
191
|
+
finally {
|
|
192
|
+
lent.conn.release();
|
|
193
|
+
}
|
|
194
|
+
},
|
|
195
|
+
connect: async () => (await lend()).conn,
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
function positiveIntOf(value) {
|
|
199
|
+
const n = typeof value === "number" ? value : typeof value === "string" && /^\d+$/.test(value.trim()) ? Number(value.trim()) : Number.NaN;
|
|
200
|
+
return Number.isSafeInteger(n) && n > 0 ? n : undefined;
|
|
201
|
+
}
|
|
202
|
+
const NO_WALL_SOURCES = Object.freeze({ maxRowBytes: "reported", maxPacketBytes: "reported" });
|
|
203
|
+
const TIDB_DEFAULT_ROW_BYTES = 6_291_456;
|
|
204
|
+
const PACKET_DEFAULT_BYTES = Object.freeze({ tidb: 67_108_864, innodb: 16_777_216 });
|
|
205
|
+
function mysqlResult(answer) {
|
|
206
|
+
const first = Array.isArray(answer) ? answer[0] : undefined;
|
|
207
|
+
if (Array.isArray(first))
|
|
208
|
+
return { rows: first, affected: 0 };
|
|
209
|
+
return { rows: [], affected: Number(memberOf(first, "affectedRows") ?? 0) || 0 };
|
|
210
|
+
}
|
|
211
|
+
function isUnknownVariable(error) {
|
|
212
|
+
return memberOf(error, "errno") === 1193 || memberOf(error, "code") === "ER_UNKNOWN_SYSTEM_VARIABLE";
|
|
213
|
+
}
|
|
214
|
+
async function variable(lease, sql) {
|
|
215
|
+
try {
|
|
216
|
+
const value = (await lease.run(CONNECT, sql, [])).rows[0]?.["v"];
|
|
217
|
+
return value === null || value === undefined ? "" : String(value);
|
|
218
|
+
}
|
|
219
|
+
catch (error) {
|
|
220
|
+
if (isUnknownVariable(error))
|
|
221
|
+
return null;
|
|
222
|
+
throw error;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
async function tidbRowWall(lease, tell) {
|
|
226
|
+
const unread = [];
|
|
227
|
+
try {
|
|
228
|
+
const value = await variable(lease, "SELECT @@tidb_txn_entry_size_limit AS v");
|
|
229
|
+
const n = positiveIntOf(value);
|
|
230
|
+
if (n !== undefined)
|
|
231
|
+
return { bytes: n, source: "reported" };
|
|
232
|
+
unread.push(`@@tidb_txn_entry_size_limit: ${value === null ? "unknown (TiDB before 7.6)" : "0 or not a positive integer (the config item applies)"}`);
|
|
233
|
+
}
|
|
234
|
+
catch (error) {
|
|
235
|
+
if (isConnectionGone(error))
|
|
236
|
+
throw error;
|
|
237
|
+
unread.push("@@tidb_txn_entry_size_limit: the read failed");
|
|
238
|
+
}
|
|
239
|
+
try {
|
|
240
|
+
const { rows } = await lease.run(CONNECT, "SHOW CONFIG WHERE type = 'tidb' AND name = 'performance.txn-entry-size-limit'", []);
|
|
241
|
+
const values = rows.map((row) => positiveIntOf(row["Value"] ?? row["value"])).filter((n) => n !== undefined);
|
|
242
|
+
if (values.length > 0)
|
|
243
|
+
return { bytes: Math.min(...values), source: "reported" };
|
|
244
|
+
unread.push(`SHOW CONFIG: no readable performance.txn-entry-size-limit in ${rows.length} row(s)`);
|
|
245
|
+
}
|
|
246
|
+
catch (error) {
|
|
247
|
+
if (isConnectionGone(error))
|
|
248
|
+
throw error;
|
|
249
|
+
unread.push("SHOW CONFIG: the read failed");
|
|
250
|
+
}
|
|
251
|
+
tell("core-stores-sql.driver.tidb-row-cap-unread", `assumed=${TIDB_DEFAULT_ROW_BYTES} ${unread.join("; ")}`);
|
|
252
|
+
return { bytes: TIDB_DEFAULT_ROW_BYTES, source: "assumed" };
|
|
253
|
+
}
|
|
254
|
+
async function packetWall(lease, engine, tell) {
|
|
255
|
+
const landing = PACKET_DEFAULT_BYTES[engine];
|
|
256
|
+
let unread;
|
|
257
|
+
let answered;
|
|
258
|
+
try {
|
|
259
|
+
const value = await variable(lease, "SELECT @@max_allowed_packet AS v");
|
|
260
|
+
answered = value;
|
|
261
|
+
const n = positiveIntOf(value);
|
|
262
|
+
if (n !== undefined)
|
|
263
|
+
return { bytes: n, source: "reported", answered };
|
|
264
|
+
unread = `@@max_allowed_packet: ${value === null ? "unknown" : "not a positive integer"}`;
|
|
265
|
+
}
|
|
266
|
+
catch (error) {
|
|
267
|
+
if (isConnectionGone(error))
|
|
268
|
+
throw error;
|
|
269
|
+
answered = null;
|
|
270
|
+
unread = "@@max_allowed_packet: the read failed";
|
|
271
|
+
}
|
|
272
|
+
tell("core-stores-sql.driver.packet-cap-unread", `assumed=${landing} engine=${engine} ${unread}`);
|
|
273
|
+
return { bytes: landing, source: "assumed", answered };
|
|
274
|
+
}
|
|
275
|
+
const MYSQL_ISOLATION = "REPEATABLE-READ";
|
|
276
|
+
async function initializeMysql(lease, tell) {
|
|
277
|
+
await lease.run(CONNECT, "SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ", []);
|
|
278
|
+
let mode = await variable(lease, "SELECT @@tidb_txn_mode AS v");
|
|
279
|
+
const engine = mode === null ? "innodb" : "tidb";
|
|
280
|
+
if (engine === "tidb" && mode !== "pessimistic") {
|
|
281
|
+
await lease.run(CONNECT, "SET SESSION tidb_txn_mode = 'pessimistic'", []);
|
|
282
|
+
mode = await variable(lease, "SELECT @@tidb_txn_mode AS v");
|
|
283
|
+
if (mode !== "pessimistic")
|
|
284
|
+
throw refusal("core-stores-sql.driver.init-refused", CONNECT, "this TiDB session does not read back the pessimistic transaction mode after SET SESSION tidb_txn_mode = 'pessimistic' — a connection whose locking reads are not current reads is not lent");
|
|
285
|
+
}
|
|
286
|
+
let isolationVariable = "transaction_isolation";
|
|
287
|
+
let isolation = await variable(lease, "SELECT @@transaction_isolation AS v");
|
|
288
|
+
if (isolation === null) {
|
|
289
|
+
isolationVariable = "tx_isolation";
|
|
290
|
+
isolation = await variable(lease, "SELECT @@tx_isolation AS v");
|
|
291
|
+
}
|
|
292
|
+
if (isolation === null)
|
|
293
|
+
throw refusal("core-stores-sql.driver.init-refused", CONNECT, "this server has neither @@transaction_isolation nor @@tx_isolation, so the isolation level it was set to cannot be read back — a connection whose locking reads are not known to be current reads is not lent");
|
|
294
|
+
if (isolation !== MYSQL_ISOLATION)
|
|
295
|
+
throw refusal("core-stores-sql.driver.init-refused", CONNECT, "this session does not read back REPEATABLE-READ after SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ — a connection whose locking reads are not current reads is not lent");
|
|
296
|
+
const version = (await variable(lease, "SELECT VERSION() AS v")) ?? "";
|
|
297
|
+
const rowWall = engine === "tidb" ? await tidbRowWall(lease, tell) : null;
|
|
298
|
+
const packet = await packetWall(lease, engine, tell);
|
|
299
|
+
const facts = Object.freeze({
|
|
300
|
+
engine,
|
|
301
|
+
version,
|
|
302
|
+
isolation,
|
|
303
|
+
txnMode: engine === "tidb" ? "pessimistic" : null,
|
|
304
|
+
maxRowBytes: rowWall === null ? null : rowWall.bytes,
|
|
305
|
+
maxPacketBytes: packet.bytes,
|
|
306
|
+
wallSources: Object.freeze({ maxRowBytes: rowWall === null ? "reported" : rowWall.source, maxPacketBytes: packet.source }),
|
|
307
|
+
});
|
|
308
|
+
const columns = [[`@@${isolationVariable}`, "iso", MYSQL_ISOLATION]];
|
|
309
|
+
if (engine === "tidb")
|
|
310
|
+
columns.push(["@@tidb_txn_mode", "mode", "pessimistic"]);
|
|
311
|
+
if (packet.answered !== null)
|
|
312
|
+
columns.push(["@@max_allowed_packet", "packet", packet.answered]);
|
|
313
|
+
const check = {
|
|
314
|
+
sql: `SELECT ${columns.map(([variable, column]) => `${variable} AS ${column}`).join(", ")}`,
|
|
315
|
+
expect: Object.fromEntries(columns.map(([, column, value]) => [column, value])),
|
|
316
|
+
};
|
|
317
|
+
return { facts, check };
|
|
318
|
+
}
|
|
319
|
+
export function mysqlDriver(pool, sink) {
|
|
320
|
+
const borrow = async () => {
|
|
321
|
+
const c = await pool.getConnection();
|
|
322
|
+
const inner = memberOf(c, "connection");
|
|
323
|
+
const raw = {
|
|
324
|
+
run: async (sql, params) => mysqlResult(await c.query(sql, params)),
|
|
325
|
+
begin: () => c.beginTransaction(),
|
|
326
|
+
commit: () => c.commit(),
|
|
327
|
+
rollback: () => c.rollback(),
|
|
328
|
+
release: () => c.release(),
|
|
329
|
+
destroy: () => c.destroy(),
|
|
330
|
+
};
|
|
331
|
+
return { raw, identity: typeof inner === "object" && inner !== null ? inner : c };
|
|
332
|
+
};
|
|
333
|
+
return driverOver("mysql", pool, borrow, initializeMysql, tellerOf(sink));
|
|
334
|
+
}
|
|
335
|
+
const PG_ISOLATION = "read committed";
|
|
336
|
+
const PG_WRITE_COMMANDS = new Set(["INSERT", "UPDATE", "DELETE", "MERGE"]);
|
|
337
|
+
function pgResult(answer) {
|
|
338
|
+
const rows = (answer.rows ?? []);
|
|
339
|
+
const command = memberOf(answer, "command");
|
|
340
|
+
const write = typeof command === "string" ? PG_WRITE_COMMANDS.has(command) : rows.length === 0;
|
|
341
|
+
return { rows, affected: write ? (answer.rowCount ?? 0) : 0 };
|
|
342
|
+
}
|
|
343
|
+
async function initializePg(lease) {
|
|
344
|
+
await lease.run(CONNECT, "SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL READ COMMITTED", []);
|
|
345
|
+
const isolation = String((await lease.run(CONNECT, "SHOW transaction_isolation", [])).rows[0]?.["transaction_isolation"] ?? "");
|
|
346
|
+
if (isolation !== PG_ISOLATION)
|
|
347
|
+
throw refusal("core-stores-sql.driver.init-refused", CONNECT, "this PostgreSQL session does not read back read committed after SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL READ COMMITTED — a connection whose locking reads are not current reads is not lent");
|
|
348
|
+
const version = String((await lease.run(CONNECT, "SHOW server_version", [])).rows[0]?.["server_version"] ?? "");
|
|
349
|
+
const facts = Object.freeze({ engine: "pg", version, isolation, txnMode: null, maxRowBytes: null, maxPacketBytes: null, wallSources: NO_WALL_SOURCES });
|
|
350
|
+
return { facts, check: { sql: "SHOW transaction_isolation", expect: { transaction_isolation: PG_ISOLATION } } };
|
|
351
|
+
}
|
|
352
|
+
export function pgDriver(pool, sink) {
|
|
353
|
+
const borrow = async () => {
|
|
354
|
+
const c = await pool.connect();
|
|
355
|
+
const on = memberOf(c, "on");
|
|
356
|
+
const off = memberOf(c, "removeListener");
|
|
357
|
+
const raw = {
|
|
358
|
+
run: async (sql, params) => pgResult(await c.query(sql, params)),
|
|
359
|
+
begin: () => c.query("BEGIN"),
|
|
360
|
+
commit: () => c.query("COMMIT"),
|
|
361
|
+
rollback: () => c.query("ROLLBACK"),
|
|
362
|
+
release: () => c.release(),
|
|
363
|
+
destroy: () => c.release(true),
|
|
364
|
+
...(typeof on === "function" && typeof off === "function"
|
|
365
|
+
? {
|
|
366
|
+
watch: (onError) => {
|
|
367
|
+
const listener = () => onError();
|
|
368
|
+
on.call(c, "error", listener);
|
|
369
|
+
return () => void off.call(c, "error", listener);
|
|
370
|
+
},
|
|
371
|
+
}
|
|
372
|
+
: {}),
|
|
373
|
+
};
|
|
374
|
+
return { raw, identity: c };
|
|
375
|
+
};
|
|
376
|
+
return driverOver("pg", pool, borrow, initializePg, tellerOf(sink));
|
|
377
|
+
}
|
package/dist/driver.d.ts
CHANGED
|
@@ -33,6 +33,9 @@ export interface SqlEngineFacts {
|
|
|
33
33
|
interface PgResultLike {
|
|
34
34
|
readonly rows: unknown[];
|
|
35
35
|
readonly rowCount: number | null;
|
|
36
|
+
/** node-postgres' statement kind (`"SELECT"`, `"UPDATE"`, …): how the driver tells a write from a read. An adapter that
|
|
37
|
+
* leaves it out gets `affected` by the rule on {@link SqlResult.affected} for a statement whose kind is not said. */
|
|
38
|
+
readonly command?: string;
|
|
36
39
|
}
|
|
37
40
|
interface PgClientLike {
|
|
38
41
|
query(text: string, values?: unknown[]): Promise<PgResultLike>;
|
|
@@ -65,7 +68,11 @@ export type SqlRow = Record<string, unknown>;
|
|
|
65
68
|
/** What a statement answered, the same shape over both dialects. */
|
|
66
69
|
export interface SqlResult {
|
|
67
70
|
rows: SqlRow[];
|
|
68
|
-
/** Rows
|
|
71
|
+
/** Rows a write touched — only where the pool's answer says the statement was a write; otherwise 0, and a caller that
|
|
72
|
+
* wants a count of what came back reads `rows.length`. The MySQL family: a statement that answers rows (a SELECT, and a
|
|
73
|
+
* MariaDB `INSERT … RETURNING` alike) is 0, a write's answer header gives its count. PostgreSQL: with node-postgres'
|
|
74
|
+
* `command`, `INSERT` / `UPDATE` / `DELETE` / `MERGE` give `rowCount` and any other 0; without it, `rowCount` when no row
|
|
75
|
+
* came back and 0 when rows did (a write with `RETURNING` on such an adapter is 0). */
|
|
69
76
|
affected: number;
|
|
70
77
|
}
|
|
71
78
|
/** How one statement is sent. */
|
|
@@ -113,9 +120,11 @@ export declare function readRecord(entry: string, where: string, value: unknown)
|
|
|
113
120
|
/**
|
|
114
121
|
* The SQL driver over one pool: `dialect` is which SQL text the stores write, `pool` is the caller's pool of that
|
|
115
122
|
* dialect (borrowed, never ended), and `onSqlNotice` is told once per notice the package gives — the driver's and
|
|
116
|
-
* every store's, a fail-open read, a self-heal or a refusal that stands ({@link SqlNoticeSink}).
|
|
117
|
-
*
|
|
118
|
-
*
|
|
123
|
+
* every store's, a fail-open read, a self-heal or a refusal that stands ({@link SqlNoticeSink}). The options are read
|
|
124
|
+
* first (version, dialect, pool, sink — each refused by name when wrong). Every statement the driver sends — the pool
|
|
125
|
+
* form and a lent connection's — runs on a connection whose session reads back what the driver set; how, and how it
|
|
126
|
+
* refuses, is `driver-runtime.ts`.
|
|
127
|
+
* The pool is borrowed through `connect()` / `getConnection()` only: the pool's own `query` is not called.
|
|
119
128
|
*/
|
|
120
129
|
export declare function createSqlDriver(opts: {
|
|
121
130
|
dialect: SqlDialect;
|
package/dist/driver.js
CHANGED
|
@@ -2,6 +2,7 @@ import { assertCoreVersion } from "./version-check.js";
|
|
|
2
2
|
import { refusal } from "./refusal.js";
|
|
3
3
|
import { callerKey, callerText } from "@sema-agent/core";
|
|
4
4
|
import { readNoticeSink } from "./notice.js";
|
|
5
|
+
import { mysqlDriver, pgDriver } from "./driver-runtime.js";
|
|
5
6
|
const SQL_DIALECTS = Object.freeze(["pg", "mysql"]);
|
|
6
7
|
const MADE_DRIVERS = new WeakSet();
|
|
7
8
|
export function isSqlDriver(value) {
|
|
@@ -50,7 +51,10 @@ export function createSqlDriver(opts) {
|
|
|
50
51
|
assertCoreVersion(entry);
|
|
51
52
|
const record = readRecord(entry, "options", opts);
|
|
52
53
|
refuseUnknownKeys(entry, "options", record, DRIVER_OPTION_KEYS, RENAMED_DRIVER_OPTIONS);
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
54
|
+
const dialect = readDialect(entry, record["dialect"]);
|
|
55
|
+
const pool = readPool(entry, dialect, record["pool"]);
|
|
56
|
+
const sink = readNoticeSink(entry, record["onSqlNotice"]);
|
|
57
|
+
const driver = dialect === "pg" ? pgDriver(pool, sink) : mysqlDriver(pool, sink);
|
|
58
|
+
MADE_DRIVERS.add(driver);
|
|
59
|
+
return driver;
|
|
56
60
|
}
|
package/dist/notice.d.ts
CHANGED
|
@@ -25,8 +25,10 @@
|
|
|
25
25
|
* of the global packet wall on the connection that was refused —, the stores' one: `store.row-unreadable`, a row a
|
|
26
26
|
* store read and could not decode, answered as absent (the read-back posture "an absence that discloses"; a store that
|
|
27
27
|
* refuses such a row instead throws, and tells nothing here), and the session seat's one: `session.after-commit-threw`,
|
|
28
|
-
* a deployment's after-commit hook that threw, the commit's writes standing committed. The driver
|
|
29
|
-
*
|
|
28
|
+
* a deployment's after-commit hook that threw, the commit's writes standing committed. The driver mints its two wall reads
|
|
29
|
+
* (`tidb-row-cap-unread`, `packet-cap-unread`) at a connection's initialization; the packet wall's self-heal, its global read
|
|
30
|
+
* and its log line arrive with the first store that judges a write against that wall, and the stores' tags with the stores —
|
|
31
|
+
* until then the table is their declaration. A step a store takes that no tag here names brings its tag into
|
|
30
32
|
* the table in the commit that moves the store in.
|
|
31
33
|
*/
|
|
32
34
|
import type { EngineStorageBackend } from "@sema-agent/core";
|
package/dist/refusal.d.ts
CHANGED
|
@@ -27,8 +27,8 @@ export declare const SQL_ERROR_CODES: Readonly<{
|
|
|
27
27
|
readonly "core-stores-sql.version.unreadable": "terminal";
|
|
28
28
|
/** A table the package ships is malformed — its migration registry, its ensure roster, its published columns. */
|
|
29
29
|
readonly "core-stores-sql.package.defect": "terminal";
|
|
30
|
-
/** This release of the package does not carry what the call makes —
|
|
31
|
-
*
|
|
30
|
+
/** This release of the package does not carry what the call makes — the stores: the call was valid, and there is
|
|
31
|
+
* nothing to return. */
|
|
32
32
|
readonly "core-stores-sql.release.not-carried": "terminal";
|
|
33
33
|
/** Core's tables are not there, or are not this version's: the backend's `ensureSchema()` has not run on this database. */
|
|
34
34
|
readonly "core-stores-sql.schema.not-ready": "terminal";
|
|
@@ -53,6 +53,8 @@ export declare const SQL_ERROR_CODES: Readonly<{
|
|
|
53
53
|
}>;
|
|
54
54
|
/** A code of a refusal of this package: one key of {@link SQL_ERROR_CODES}. */
|
|
55
55
|
export type SqlErrorCode = keyof typeof SQL_ERROR_CODES;
|
|
56
|
+
/** A member of a caught value, read once; a member that throws when read (a getter, a revoked proxy) is absent. */
|
|
57
|
+
export declare function memberOf(value: unknown, key: string): unknown;
|
|
56
58
|
/**
|
|
57
59
|
* The one reading of a caught value: a refusal of this package — its code, whether repeating the call can succeed, and
|
|
58
60
|
* on `hook.refused` the hook's own code — or `undefined` for anything else. It reads the value's `code` member only:
|
package/dist/refusal.js
CHANGED
|
@@ -12,7 +12,7 @@ export const SQL_ERROR_CODES = Object.freeze({
|
|
|
12
12
|
"core-stores-sql.driver.init-unreached": "transient",
|
|
13
13
|
"core-stores-sql.hook.refused": "terminal",
|
|
14
14
|
});
|
|
15
|
-
function memberOf(value, key) {
|
|
15
|
+
export function memberOf(value, key) {
|
|
16
16
|
if ((typeof value !== "object" && typeof value !== "function") || value === null)
|
|
17
17
|
return undefined;
|
|
18
18
|
try {
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sema-agent/core-stores-sql",
|
|
3
|
-
"version": "7.74.
|
|
3
|
+
"version": "7.74.1-main.gb6563676503c99e9b20ede6bb7f4c5992b87e841",
|
|
4
4
|
"private": false,
|
|
5
|
-
"description": "Core's storage seats over PostgreSQL and the MySQL protocol family (MySQL, MariaDB, TiDB): neutral factories over a caller's pool. This version carries no SQL stores yet
|
|
5
|
+
"description": "Core's storage seats over PostgreSQL and the MySQL protocol family (MySQL, MariaDB, TiDB): neutral factories over a caller's pool. This version carries the driver and no SQL stores yet.",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"license": "BUSL-1.1",
|
|
8
8
|
"repository": {
|
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
"node": ">=20.18.1"
|
|
27
27
|
},
|
|
28
28
|
"peerDependencies": {
|
|
29
|
-
"@sema-agent/core": "7.74.
|
|
29
|
+
"@sema-agent/core": "7.74.1-main.gb6563676503c99e9b20ede6bb7f4c5992b87e841"
|
|
30
30
|
},
|
|
31
31
|
"publishConfig": {
|
|
32
32
|
"access": "public"
|
|
@@ -34,5 +34,5 @@
|
|
|
34
34
|
"scripts": {
|
|
35
35
|
"build": "tsc -p tsconfig.json && tsc -p tsconfig.json --emitDeclarationOnly --removeComments false"
|
|
36
36
|
},
|
|
37
|
-
"gitHead": "
|
|
37
|
+
"gitHead": "b6563676503c99e9b20ede6bb7f4c5992b87e841"
|
|
38
38
|
}
|