@tinyshed/tinystore 0.1.0-rc.5 → 0.1.0-rc.6

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.
Files changed (122) hide show
  1. package/README.md +37 -37
  2. package/bin/tinystore.js +12 -1
  3. package/dist/backup.d.ts +33 -0
  4. package/dist/backup.js +49 -0
  5. package/dist/blobs.d.ts +160 -79
  6. package/dist/blobs.js +510 -217
  7. package/dist/channels.d.ts +90 -0
  8. package/dist/channels.js +291 -0
  9. package/dist/clock.js +3 -3
  10. package/dist/config.d.ts +209 -86
  11. package/dist/config.js +581 -538
  12. package/dist/connection.d.ts +64 -2
  13. package/dist/connection.js +201 -16
  14. package/dist/console.d.ts +27 -3
  15. package/dist/console.js +165 -12
  16. package/dist/dotenv.d.ts +7 -0
  17. package/dist/dotenv.js +79 -0
  18. package/dist/errors.d.ts +61 -1
  19. package/dist/errors.js +81 -1
  20. package/dist/handles.d.ts +44 -2
  21. package/dist/handles.js +81 -2
  22. package/dist/index.d.ts +17 -11
  23. package/dist/index.js +5 -3
  24. package/dist/instruments.d.ts +177 -0
  25. package/dist/instruments.js +819 -0
  26. package/dist/jobs.d.ts +335 -239
  27. package/dist/jobs.js +716 -536
  28. package/dist/json.d.ts +2 -0
  29. package/dist/json.js +122 -0
  30. package/dist/kv.d.ts +130 -243
  31. package/dist/kv.js +273 -640
  32. package/dist/limits.d.ts +80 -0
  33. package/dist/limits.js +139 -0
  34. package/dist/locks.d.ts +62 -0
  35. package/dist/locks.js +237 -0
  36. package/dist/logger.d.ts +45 -9
  37. package/dist/logger.js +150 -38
  38. package/dist/metrics.d.ts +210 -209
  39. package/dist/metrics.js +319 -556
  40. package/dist/once.d.ts +19 -18
  41. package/dist/once.js +74 -63
  42. package/dist/query.d.ts +181 -0
  43. package/dist/query.js +788 -0
  44. package/dist/records.d.ts +241 -150
  45. package/dist/records.js +507 -291
  46. package/dist/runtime/addon.d.ts +14 -0
  47. package/dist/runtime/addon.js +69 -0
  48. package/dist/runtime/bun.js +5 -7
  49. package/dist/runtime/node.js +5 -7
  50. package/dist/runtime/pipe.d.ts +17 -0
  51. package/dist/runtime/pipe.js +133 -0
  52. package/dist/runtime/shared.d.ts +6 -0
  53. package/dist/runtime/shared.js +19 -0
  54. package/dist/runtime.d.ts +5 -2
  55. package/dist/search.d.ts +189 -0
  56. package/dist/search.js +281 -0
  57. package/dist/session.d.ts +31 -3
  58. package/dist/session.js +153 -41
  59. package/dist/sql.d.ts +228 -78
  60. package/dist/sql.js +745 -240
  61. package/dist/store.d.ts +244 -24
  62. package/dist/store.js +270 -67
  63. package/dist/time.d.ts +5 -1
  64. package/dist/time.js +22 -2
  65. package/dist/tx.d.ts +61 -0
  66. package/dist/tx.js +314 -0
  67. package/dist/wire/codec.d.ts +23 -7
  68. package/dist/wire/codec.js +56 -35
  69. package/dist/wire/frame.d.ts +2 -0
  70. package/dist/wire/frame.js +31 -14
  71. package/dist/wire/messages.d.ts +259 -0
  72. package/dist/wire/messages.js +22 -0
  73. package/dist/wire/msgpack.d.ts +49 -1
  74. package/dist/wire/msgpack.js +293 -56
  75. package/dist/wire/protocol.d.ts +2683 -0
  76. package/dist/wire/protocol.js +10846 -0
  77. package/package.json +39 -38
  78. package/src/backup.ts +81 -0
  79. package/src/blobs.ts +678 -301
  80. package/src/channels.ts +377 -0
  81. package/src/clock.ts +4 -4
  82. package/src/config.ts +902 -612
  83. package/src/connection.ts +279 -21
  84. package/src/console.ts +180 -12
  85. package/src/dotenv.ts +82 -0
  86. package/src/errors.ts +105 -0
  87. package/src/handles.ts +157 -8
  88. package/src/index.ts +158 -52
  89. package/src/instruments.ts +1042 -0
  90. package/src/jobs.ts +1017 -733
  91. package/src/json.ts +133 -0
  92. package/src/kv.ts +424 -847
  93. package/src/limits.ts +202 -0
  94. package/src/locks.ts +320 -0
  95. package/src/logger.ts +209 -40
  96. package/src/metrics.ts +557 -752
  97. package/src/once.ts +86 -83
  98. package/src/query.ts +1005 -0
  99. package/src/records.ts +795 -418
  100. package/src/runtime/addon.ts +99 -0
  101. package/src/runtime/bun.ts +5 -7
  102. package/src/runtime/node.ts +5 -7
  103. package/src/runtime/pipe.ts +178 -0
  104. package/src/runtime/shared.ts +20 -0
  105. package/src/runtime.ts +5 -2
  106. package/src/search.ts +480 -0
  107. package/src/session.ts +187 -41
  108. package/src/sql.ts +993 -306
  109. package/src/store.ts +473 -78
  110. package/src/time.ts +48 -3
  111. package/src/tx.ts +426 -0
  112. package/src/wire/codec.ts +78 -37
  113. package/src/wire/frame.ts +44 -14
  114. package/src/wire/messages.ts +25 -0
  115. package/src/wire/msgpack.ts +327 -56
  116. package/src/wire/protocol.ts +11709 -0
  117. package/dist/limiter.d.ts +0 -45
  118. package/dist/limiter.js +0 -68
  119. package/dist/quota.d.ts +0 -44
  120. package/dist/quota.js +0 -98
  121. package/src/limiter.ts +0 -99
  122. package/src/quota.ts +0 -137
@@ -0,0 +1,7 @@
1
+ /**
2
+ * The variables of a .env file, as Go's and Python's configs read one: NAME=value
3
+ * lines, export before a name, # comments, a comment after a space, double
4
+ * quotes reading \n \r \t \" and \\, single quotes reading nothing, a quoted
5
+ * value over lines; a later name wins.
6
+ */
7
+ export declare function parseDotenv(text: string): Record<string, string>;
package/dist/dotenv.js ADDED
@@ -0,0 +1,79 @@
1
+ // A .env file's variables, as a store-less logger reads them for LOG_LEVEL and
2
+ // the rest; a config sends its .env files to the core, which reads them with
3
+ // the same rules (testdata/config/env.json).
4
+ import { InvalidError } from './errors.js';
5
+ /**
6
+ * The variables of a .env file, as Go's and Python's configs read one: NAME=value
7
+ * lines, export before a name, # comments, a comment after a space, double
8
+ * quotes reading \n \r \t \" and \\, single quotes reading nothing, a quoted
9
+ * value over lines; a later name wins.
10
+ */
11
+ export function parseDotenv(text) {
12
+ const values = {};
13
+ let line = 1;
14
+ let rest = text;
15
+ while (rest !== '') {
16
+ const [name, value, after] = dotenvAssignment(rest, line);
17
+ line += rest.slice(0, rest.length - after.length).split('\n').length - 1;
18
+ if (name !== '') {
19
+ values[name] = value;
20
+ }
21
+ rest = after;
22
+ }
23
+ return values;
24
+ }
25
+ function dotenvAssignment(text, number) {
26
+ const end = text.indexOf('\n');
27
+ const line = end < 0 ? text : text.slice(0, end);
28
+ const rest = end < 0 ? '' : text.slice(end + 1);
29
+ const trimmed = line.trim();
30
+ if (trimmed === '' || trimmed.startsWith('#')) {
31
+ return ['', '', rest];
32
+ }
33
+ const equals = line.indexOf('=');
34
+ if (equals < 0) {
35
+ throw new InvalidError(`line ${number}: ${JSON.stringify(line)} is no NAME=value`);
36
+ }
37
+ let name = line.slice(0, equals).trim();
38
+ if (name.startsWith('export ')) {
39
+ name = name.slice('export '.length).trim();
40
+ }
41
+ if (!/^[\p{L}_][\p{L}\p{Nd}_]*$/u.test(name)) {
42
+ throw new InvalidError(`line ${number}: ${JSON.stringify(name)} is no variable's name`);
43
+ }
44
+ let start = equals + 1;
45
+ while (line[start] === ' ' || line[start] === '\t') {
46
+ start++;
47
+ }
48
+ if (line[start] === '"' || line[start] === "'") {
49
+ return [name, ...dotenvQuoted(text.slice(start), number)];
50
+ }
51
+ let value = line.slice(start);
52
+ const comment = value.indexOf(' #');
53
+ if (comment >= 0) {
54
+ value = value.slice(0, comment);
55
+ }
56
+ return [name, value.replace(/[ \t\r]+$/, ''), rest];
57
+ }
58
+ function dotenvQuoted(text, number) {
59
+ const quote = text[0];
60
+ let out = '';
61
+ for (let i = 1; i < text.length; i++) {
62
+ const c = text[i];
63
+ if (c === quote) {
64
+ const end = text.indexOf('\n', i + 1);
65
+ return [out, end < 0 ? '' : text.slice(end + 1)];
66
+ }
67
+ if (c === '\\' && quote === '"' && i + 1 < text.length) {
68
+ i++;
69
+ const escaped = text[i];
70
+ // only the five escapes are read: "D:\dev" keeps its backslash
71
+ const read = { n: '\n', r: '\r', t: '\t', '"': '"', '\\': '\\' };
72
+ out += read[escaped] ?? `\\${escaped}`;
73
+ }
74
+ else {
75
+ out += c;
76
+ }
77
+ }
78
+ throw new InvalidError(`line ${number}: a value opened with ${quote} is never closed`);
79
+ }
package/dist/errors.d.ts CHANGED
@@ -3,16 +3,33 @@
3
3
  * class of its own, so a caller catches `ConflictError` as a Go program asks
4
4
  * `errors.Is(err, tinystore.ErrConflict)`.
5
5
  */
6
- export type Code = 'invalid' | 'limit' | 'closed' | 'in_use' | 'conflict' | 'corrupt' | 'too_old' | 'too_new' | 'suspended' | 'outcome_unknown' | 'permission' | 'unimplemented' | 'cancelled' | 'unavailable' | 'internal' | 'protocol' | 'unauthenticated';
6
+ export type Code = 'invalid' | 'not_found' | 'limit' | 'closed' | 'in_use' | 'conflict' | 'corrupt' | 'too_old' | 'too_new' | 'suspended' | 'outcome_unknown' | 'committed_locally' | 'lost' | 'permission' | 'unimplemented' | 'cancelled' | 'unavailable' | 'internal' | 'protocol' | 'unauthenticated';
7
7
  /**
8
8
  * The item a failure is about, by the names the server gives: a bucket and a
9
9
  * key, a queue and a key, a series' labels, a table and a constraint. A value
10
10
  * whose bytes are not UTF-8, as a key of bytes may be, comes as its bytes.
11
11
  */
12
12
  export type What = Record<string, string | Uint8Array>;
13
+ /**
14
+ * A constraint a database's write broke, as SQLite names it: a unique or a
15
+ * primary key already held is a ConflictError, any other an InvalidError.
16
+ *
17
+ * if (err instanceof ConflictError && err.constraint?.columns.includes('email')) return 'that email is taken'
18
+ */
19
+ export interface Constraint {
20
+ kind: 'unique' | 'primaryKey' | 'foreignKey' | 'check' | 'notNull';
21
+ /** the table, when SQLite names it */
22
+ table: string | undefined;
23
+ /** the columns, when SQLite names them */
24
+ columns: string[];
25
+ /** a check's name, or its text when it has none; the index of a unique key on an expression */
26
+ name: string | undefined;
27
+ }
13
28
  export declare class TinystoreError extends Error {
14
29
  readonly code: Code;
15
30
  readonly what: What;
31
+ /** the constraint a database's write broke; undefined for any other failure */
32
+ readonly constraint: Constraint | undefined;
16
33
  constructor(code: Code, message: string, what?: What);
17
34
  }
18
35
  /** The request cannot be done as asked. */
@@ -30,6 +47,34 @@ export declare class LimitError extends TinystoreError {
30
47
  readonly bound: number | undefined;
31
48
  constructor(message: string, what?: What);
32
49
  }
50
+ /**
51
+ * The names a LimitError's `limit` holds, as Go's constants and Python's
52
+ * `tinystore.limits` spell them, to map a limit without matching its text.
53
+ *
54
+ * ```ts
55
+ * if (err instanceof LimitError && err.limit === limits.decodedSamples) { … }
56
+ * ```
57
+ */
58
+ export declare const limits: Readonly<{
59
+ readonly storeMemory: 'store memory';
60
+ readonly storeMemoryNow: 'store memory, now';
61
+ readonly matchedSeries: 'matched series';
62
+ readonly decodedBlocks: 'decoded blocks';
63
+ readonly fetchedBytes: 'fetched bytes';
64
+ readonly decodedSamples: 'decoded samples';
65
+ readonly outputSamples: 'output samples';
66
+ readonly outputBuckets: 'output buckets';
67
+ readonly recordBytes: "bytes of a record, a block's";
68
+ readonly appendBytes: "bytes of records in one Append, a segment's; split it";
69
+ readonly jobValueBytes: "bytes of a job's value";
70
+ readonly stepBytes: "bytes of a step's answer";
71
+ readonly objectBytes: "bytes of an object, the bucket's MaxSize";
72
+ readonly rowBytes: "bytes of a call's rows";
73
+ }>;
74
+ /** What the call needs is not there: a file to copy or rename. */
75
+ export declare class NotFoundError extends TinystoreError {
76
+ constructor(message: string, what?: What);
77
+ }
33
78
  /** The store, the handle or the connection closed. */
34
79
  export declare class ClosedError extends TinystoreError {
35
80
  constructor(message: string, what?: What);
@@ -66,6 +111,13 @@ export declare class SuspendedError extends TinystoreError {
66
111
  export declare class OutcomeUnknownError extends TinystoreError {
67
112
  constructor(message: string, what?: What);
68
113
  }
114
+ /**
115
+ * A synchronous commit its home made that no copy it waits for held in time:
116
+ * the write stands, and losing that home's disk would lose it.
117
+ */
118
+ export declare class CommittedLocallyError extends TinystoreError {
119
+ constructor(message: string, what?: What);
120
+ }
69
121
  /** The connection's capability does not allow it: a data token changing a schema. */
70
122
  export declare class PermissionDeniedError extends TinystoreError {
71
123
  constructor(message: string, what?: What);
@@ -86,6 +138,14 @@ export declare class UnavailableError extends TinystoreError {
86
138
  export declare class InternalError extends TinystoreError {
87
139
  constructor(message: string, what?: What);
88
140
  }
141
+ /**
142
+ * A lease that ran out or was revoked at its maxHold while its function ran:
143
+ * another holder may have run beside it. The function's work stands, and a
144
+ * system that compares fences refused what came late.
145
+ */
146
+ export declare class LostError extends TinystoreError {
147
+ constructor(message: string, what?: What);
148
+ }
89
149
  /** A frame or a message that breaks the protocol; the connection ends with it. */
90
150
  export declare class ProtocolError extends TinystoreError {
91
151
  constructor(message: string, what?: What);
package/dist/errors.js CHANGED
@@ -1,12 +1,40 @@
1
+ const constraintKinds = [
2
+ 'unique',
3
+ 'primaryKey',
4
+ 'foreignKey',
5
+ 'check',
6
+ 'notNull',
7
+ ];
1
8
  export class TinystoreError extends Error {
2
9
  code;
3
10
  what;
11
+ /** the constraint a database's write broke; undefined for any other failure */
12
+ constraint;
4
13
  constructor(code, message, what = {}) {
5
14
  super(message);
6
15
  this.name = new.target.name;
7
16
  this.code = code;
8
17
  this.what = what;
9
- }
18
+ this.constraint = constraintOf(what);
19
+ }
20
+ }
21
+ /** The constraint the server named in what, by its constraint, table, columns and name. */
22
+ function constraintOf(what) {
23
+ const text = (name) => {
24
+ const value = what[name];
25
+ return typeof value === 'string' ? value : undefined;
26
+ };
27
+ const kind = text('constraint');
28
+ if (kind === undefined || !constraintKinds.includes(kind)) {
29
+ return undefined;
30
+ }
31
+ const columns = text('columns');
32
+ return {
33
+ kind: kind,
34
+ table: text('table'),
35
+ columns: columns === undefined ? [] : columns.split(', '),
36
+ name: text('name'),
37
+ };
10
38
  }
11
39
  /** The request cannot be done as asked. */
12
40
  export class InvalidError extends TinystoreError {
@@ -30,6 +58,36 @@ export class LimitError extends TinystoreError {
30
58
  this.bound = typeof what?.bound === 'string' ? Number(what.bound) : undefined;
31
59
  }
32
60
  }
61
+ /**
62
+ * The names a LimitError's `limit` holds, as Go's constants and Python's
63
+ * `tinystore.limits` spell them, to map a limit without matching its text.
64
+ *
65
+ * ```ts
66
+ * if (err instanceof LimitError && err.limit === limits.decodedSamples) { … }
67
+ * ```
68
+ */
69
+ export const limits = Object.freeze({
70
+ storeMemory: 'store memory',
71
+ storeMemoryNow: 'store memory, now',
72
+ matchedSeries: 'matched series',
73
+ decodedBlocks: 'decoded blocks',
74
+ fetchedBytes: 'fetched bytes',
75
+ decodedSamples: 'decoded samples',
76
+ outputSamples: 'output samples',
77
+ outputBuckets: 'output buckets',
78
+ recordBytes: "bytes of a record, a block's",
79
+ appendBytes: "bytes of records in one Append, a segment's; split it",
80
+ jobValueBytes: "bytes of a job's value",
81
+ stepBytes: "bytes of a step's answer",
82
+ objectBytes: "bytes of an object, the bucket's MaxSize",
83
+ rowBytes: "bytes of a call's rows",
84
+ });
85
+ /** What the call needs is not there: a file to copy or rename. */
86
+ export class NotFoundError extends TinystoreError {
87
+ constructor(message, what) {
88
+ super('not_found', message, what);
89
+ }
90
+ }
33
91
  /** The store, the handle or the connection closed. */
34
92
  export class ClosedError extends TinystoreError {
35
93
  constructor(message, what) {
@@ -82,6 +140,15 @@ export class OutcomeUnknownError extends TinystoreError {
82
140
  super('outcome_unknown', message, what);
83
141
  }
84
142
  }
143
+ /**
144
+ * A synchronous commit its home made that no copy it waits for held in time:
145
+ * the write stands, and losing that home's disk would lose it.
146
+ */
147
+ export class CommittedLocallyError extends TinystoreError {
148
+ constructor(message, what) {
149
+ super('committed_locally', message, what);
150
+ }
151
+ }
85
152
  /** The connection's capability does not allow it: a data token changing a schema. */
86
153
  export class PermissionDeniedError extends TinystoreError {
87
154
  constructor(message, what) {
@@ -112,6 +179,16 @@ export class InternalError extends TinystoreError {
112
179
  super('internal', message, what);
113
180
  }
114
181
  }
182
+ /**
183
+ * A lease that ran out or was revoked at its maxHold while its function ran:
184
+ * another holder may have run beside it. The function's work stands, and a
185
+ * system that compares fences refused what came late.
186
+ */
187
+ export class LostError extends TinystoreError {
188
+ constructor(message, what) {
189
+ super('lost', message, what);
190
+ }
191
+ }
115
192
  /** A frame or a message that breaks the protocol; the connection ends with it. */
116
193
  export class ProtocolError extends TinystoreError {
117
194
  constructor(message, what) {
@@ -126,6 +203,7 @@ export class UnauthenticatedError extends TinystoreError {
126
203
  }
127
204
  const classes = {
128
205
  invalid: InvalidError,
206
+ not_found: NotFoundError,
129
207
  limit: LimitError,
130
208
  closed: ClosedError,
131
209
  in_use: InUseError,
@@ -135,6 +213,8 @@ const classes = {
135
213
  too_new: TooNewError,
136
214
  suspended: SuspendedError,
137
215
  outcome_unknown: OutcomeUnknownError,
216
+ committed_locally: CommittedLocallyError,
217
+ lost: LostError,
138
218
  permission: PermissionDeniedError,
139
219
  unimplemented: UnimplementedError,
140
220
  cancelled: CancelledError,
package/dist/handles.d.ts CHANGED
@@ -1,11 +1,53 @@
1
- import type { Connection } from './connection.ts';
1
+ import { type Connection, type Idempotence, type Link } from './connection.ts';
2
2
  import type { Key } from './wire/codec.ts';
3
+ import { Reader, Writer } from './wire/msgpack.ts';
4
+ /**
5
+ * What opens a handle: its open's bytes, or, for a bucket or a queue kept in
6
+ * a database's file, what makes them once the database is open on the
7
+ * connection, since the open names the database by its handle there.
8
+ */
9
+ export type Open = Uint8Array | ((connection: Connection) => Promise<Uint8Array>);
10
+ /** A database a bucket or a queue is kept in: its handle on a connection, and its name as errors say it. */
11
+ export interface Home {
12
+ readonly describe: string;
13
+ handle(connection: Connection): Promise<number>;
14
+ /**
15
+ * The opener of a handle kept in the database's file: the one made first
16
+ * for the same open, so that the database's transaction opens each once,
17
+ * before it holds the writer, and knows the handles it opened.
18
+ */
19
+ keep(method: number, bytes: Uint8Array, make: (connection: Connection) => Promise<Uint8Array>): Open;
20
+ /**
21
+ * How a handle kept in the database's file reaches the server outside a
22
+ * transaction: on the link's connection, and refused from inside the
23
+ * database's own transaction, where it would wait for the writer the
24
+ * transaction holds.
25
+ */
26
+ via(what: string): Via;
27
+ }
28
+ /**
29
+ * How a handle's calls reach the server: on the link's connection, the handle
30
+ * opened there first, or inside a database's transaction, on its stream.
31
+ */
32
+ export interface Via {
33
+ call(openMethod: number, open: Open, method: number, body: (handle: number) => Uint8Array, idempotence: Idempotence): Promise<Uint8Array>;
34
+ /**
35
+ * The same call, its body written by `write` and its answer read by `read`
36
+ * where the bytes are: on a connection that takes it at once it costs a
37
+ * promise and no copy. What `read` returns holds none of the bytes it read.
38
+ */
39
+ ask<T>(openMethod: number, open: Open, method: number, write: (w: Writer, handle: number) => void, read: (r: Reader) => T, idempotence: Idempotence): Promise<T>;
40
+ }
41
+ /** Asks through `call`, the body and the answer each in bytes of their own. */
42
+ export declare function askByCall<T>(call: Via['call'], openMethod: number, open: Open, method: number, write: (w: Writer, handle: number) => void, read: (r: Reader) => T, idempotence: Idempotence): Promise<T>;
43
+ /** Calls on whichever connection the link has, dialled again as it says. */
44
+ export declare function viaLink(link: Link): Via;
3
45
  /**
4
46
  * The handle an open answers on a connection, opened once a connection: the
5
47
  * open's own bytes name it, so a bucket opened twice with the same options
6
48
  * shares its handle. An open that fails is tried again by the next call.
7
49
  */
8
- export declare function handleOn(connection: Connection, method: number, open: Uint8Array): Promise<number>;
50
+ export declare function handleOn(connection: Connection, method: number, open: Open): Promise<number>;
9
51
  /** A bucket's or a queue's name, as every engine takes it: [a-z0-9][a-z0-9_-]{0,63}. */
10
52
  export declare function checkName(name: string, of: string): void;
11
53
  /**
package/dist/handles.js CHANGED
@@ -1,18 +1,97 @@
1
+ import { goesAgain } from './connection.js';
1
2
  import { InvalidError } from './errors.js';
2
- import { Handle } from './wire/messages.js';
3
+ import { Reader, Writer } from './wire/msgpack.js';
4
+ import { Handle } from './wire/protocol.js';
5
+ /** Asks through `call`, the body and the answer each in bytes of their own. */
6
+ export function askByCall(call, openMethod, open, method, write, read, idempotence) {
7
+ const body = (handle) => {
8
+ const w = new Writer();
9
+ write(w, handle);
10
+ return w.bytes();
11
+ };
12
+ return call(openMethod, open, method, body, idempotence).then(answer => {
13
+ const r = new Reader(answer);
14
+ const value = read(r);
15
+ r.end();
16
+ return value;
17
+ });
18
+ }
19
+ /** Calls on whichever connection the link has, dialled again as it says. */
20
+ export function viaLink(link) {
21
+ const call = (openMethod, open, method, body, idempotence) => link.run(idempotence, async (connection) => {
22
+ const handle = await handleOn(connection, openMethod, open);
23
+ return connection.session.call(method, body(handle));
24
+ });
25
+ return {
26
+ call,
27
+ ask: (openMethod, open, method, write, read, idempotence) => {
28
+ const waiting = () => askByCall(call, openMethod, open, method, write, read, idempotence);
29
+ const connection = link.ready();
30
+ const handle = connection?.opened.get(open);
31
+ if (connection === undefined || handle === undefined) {
32
+ return waiting();
33
+ }
34
+ return new Promise((resolve, reject) => {
35
+ // a call that fails here goes on as its first try through the link would
36
+ const failed = (err) => {
37
+ try {
38
+ if (!goesAgain(err, idempotence)) {
39
+ return reject(err);
40
+ }
41
+ }
42
+ catch (unknown) {
43
+ return reject(unknown);
44
+ }
45
+ waiting().then(resolve, reject);
46
+ };
47
+ if (!connection.session.direct(method, w => write(w, handle), read, resolve, failed)) {
48
+ waiting().then(resolve, reject);
49
+ }
50
+ });
51
+ },
52
+ };
53
+ }
54
+ // the base64 of an open's bytes, made once: a database's open holds its migrations
55
+ const openKeys = new WeakMap();
56
+ // what an opener of a database's file opened, by connection
57
+ const opened = new WeakMap();
3
58
  /**
4
59
  * The handle an open answers on a connection, opened once a connection: the
5
60
  * open's own bytes name it, so a bucket opened twice with the same options
6
61
  * shares its handle. An open that fails is tried again by the next call.
7
62
  */
8
63
  export function handleOn(connection, method, open) {
9
- const key = `${method}:${Buffer.from(open).toString('base64')}`;
64
+ if (typeof open === 'function') {
65
+ let byConnection = opened.get(open);
66
+ if (byConnection === undefined) {
67
+ byConnection = new WeakMap();
68
+ opened.set(open, byConnection);
69
+ }
70
+ let opening = byConnection.get(connection);
71
+ if (opening === undefined) {
72
+ const kept = byConnection;
73
+ opening = open(connection).then(bytes => handleOn(connection, method, bytes));
74
+ kept.set(connection, opening);
75
+ opening.then(handle => connection.opened.set(open, handle), () => kept.delete(connection));
76
+ }
77
+ return opening;
78
+ }
79
+ let encoded = openKeys.get(open);
80
+ if (encoded === undefined) {
81
+ encoded = Buffer.from(open).toString('base64');
82
+ openKeys.set(open, encoded);
83
+ }
84
+ const key = `${method}:${encoded}`;
10
85
  let opening = connection.handles.get(key);
11
86
  if (opening === undefined) {
12
87
  opening = connection.session.call(method, open).then(body => Handle.decode(body).handle ?? 0);
13
88
  connection.handles.set(key, opening);
14
89
  opening.catch(() => connection.handles.delete(key));
15
90
  }
91
+ // by these bytes themselves too: a second handle of the same open has bytes of its own
92
+ if (!connection.opened.has(open)) {
93
+ opening.then(handle => connection.opened.set(open, handle), () => { });
94
+ }
16
95
  return opening;
17
96
  }
18
97
  /** A bucket's or a queue's name, as every engine takes it: [a-z0-9][a-z0-9_-]{0,63}. */
package/dist/index.d.ts CHANGED
@@ -1,21 +1,27 @@
1
- export type { BlobBucket, BlobObject, Blobs, Body, Download, PutOptions } from './blobs.ts';
1
+ export type { Backup, BackupOptions } from './backup.ts';
2
+ export type { Body, FileBytes, FileInfo, FileListOptions, FileOptions, FilePage, Files, FilesOptions, Size, StoredFile, Upload, } from './blobs.ts';
2
3
  export { withSignal } from './cancel.ts';
4
+ export type { Channel, EachOptions, Message as ChannelMessage, Missed, SubscribeOptions, Subscription, TxChannel, } from './channels.ts';
3
5
  export type { Clock } from './clock.ts';
4
- export { type Config, type ConfigLayer, type ConfigValue, type DeepPartial, type FromEnv, fromEnv, required, type Setting, type Source, secret, type Validate, validate, } from './config.ts';
5
- export type { ConsoleFormat, ConsoleTime } from './console.ts';
6
+ export { type Bounds, type Changes, type Config, type ConfigOptions, type DurationBounds, duration, type EnvLayer, type EnvOptions, type Explained, type ExplainLine, env, type FileLayer, file, int, type Layer, list, live, type Overlay, oneOf, required, Secret, type Setting, secret, type UpdateOptions, type Value, type Vars, } from './config.ts';
7
+ export type { Durability, SelfMetrics } from './connection.ts';
8
+ export { type ConsoleFormat, type ConsoleTime, secrets } from './console.ts';
6
9
  export * from './errors.ts';
7
10
  export type { Page } from './handles.ts';
8
- export type { ClaimedJob, EnqueueOptions, Job, JobEntry, JobState, Jobs, Queue, QueueOptions, QueueTx, Repeat, WorkOptions, } from './jobs.ts';
9
- export type { Batch, Bucket, BucketOptions, BucketTx, CounterOptions, Counters, Entry, Kind, Scanned, Tx, WriteOptions, } from './kv.ts';
10
- export type { Allowance, Limiter, LimiterOptions, Rate } from './limiter.ts';
11
+ export type { AddOptions, Answer, Backoff, Concurrency, Handler, Job, JobOptions, JobPage, JobState, ListOptions, Queue, QueueOptions, Run, Schedule, ScheduleOptions, ScheduleWhen, StoreTxQueue, TxQueue, Worker, WorkOptions, } from './jobs.ts';
12
+ export type { Bucket, BucketOptions, Counters, CountersOptions, Entry, Page as KvPage, ValueType, WriteOptions, } from './kv.ts';
13
+ export type { Allowance, Quota, Rate, RateLimit, RateLimitOptions, WindowUse } from './limits.ts';
14
+ export type { HoldOptions, Lease, Lock, LockOptions, Permit, Semaphore, SemaphoreOptions, Tried, } from './locks.ts';
11
15
  export { type ConsoleOut, type Logger, type LoggerOptions, logger } from './logger.ts';
12
- export { type Aggregate, type AggregateOp, type AggregateRange, type Bucket as MetricsBucket, Condition, type Counter, type Gauge, type Labels, type Metrics, noneOf, oneOf, type Plan, prefix, type Range, type Series, type SeriesInput, type SeriesKind, type Timer, } from './metrics.ts';
16
+ export { type Aggregate, type AggregateQuery, type Bucket as MetricsBucket, type Buckets, type Condition as MetricsCondition, type Counter, type Damage as MetricsDamage, type Description as MetricsDescription, exponentialBuckets, type Gauge, type GaugeFuncOptions, type Histogram, type HistogramOptions, type InstrumentLabels, type InstrumentOptions, type LabelPage, type Labels, type LabelValue, type Metrics, type NameInfo, type NamePage, type Newest, type Op as MetricsOp, type PageOptions, type Percentile, type PercentileBucket, type Plan, type Query as MetricsQuery, type Series, type SeriesInput, type SeriesKind, type Timer, type TimerOptions, type Timing, type ValueBucket, type ValuePage, } from './metrics.ts';
13
17
  export type { Once, OnceOptions } from './once.ts';
14
- export type { Quota, QuotaUsage, WindowUsage } from './quota.ts';
15
- export { type Cursor, type Damage, type Fields, fields, type Level, type LinesWriter, type LogRecord, type RecordInput, type Records, type RecordsQuery, } from './records.ts';
18
+ export type { ColumnType, Query, RowPage, Table, TableOptions, UpsertOptions } from './query.ts';
19
+ export type { Aggregate as EventsAggregate, AllEvents, AppendOptions, Counted, Damage, Event, EventLevel, Events, EventsOptions, Fields, Level, Lines, NewEvent, Page as EventsPage, PollBatch, Query as EventsQuery, Row as EventsRow, Stats, StoreLoggerOptions, StreamInfo, TailBatch, TailQuery, Top, } from './records.ts';
16
20
  export type { StandardSchemaV1 } from './schema.ts';
17
- export type { Database, Done, Migrations, Row, SqlArg, SqlBatch, SqlOptions, SqlValue, Statement, } from './sql.ts';
18
- export { type ConnectOptions, connect, type OpenOptions, open, type Status, Store, } from './store.ts';
21
+ export { type Found as SearchFound, type Hit as SearchHit, type IndexDocument, type IndexInfo, type IndexOptions, type IndexStatus, type Query as SearchQuery, SearchIndex, search, TableIndex, type TableIndexOptions, type Vector, type Where, type WhereValue, } from './search.ts';
22
+ export { type Columns, type Database, type DatabaseOptions, type Done, type Migrations, type Row, Sql, type SqlArg, type SqlTag, type SqlTx, type SqlValue, type Statement, sql, } from './sql.ts';
23
+ export { type ConnectOptions, connect, type NodeOptions, type OpenOptions, open, type Status, Store, } from './store.ts';
19
24
  export type { Duration, DurationText, Time } from './time.ts';
20
25
  export { type Trace, withTrace } from './trace.ts';
26
+ export type { Tx, TxBucket, TxCounters } from './tx.ts';
21
27
  export type { Key } from './wire/codec.ts';
package/dist/index.js CHANGED
@@ -1,8 +1,10 @@
1
1
  export { withSignal } from './cancel.js';
2
- export { fromEnv, required, secret, validate, } from './config.js';
2
+ export { duration, env, file, int, list, live, oneOf, required, Secret, secret, } from './config.js';
3
+ export { secrets } from './console.js';
3
4
  export * from './errors.js';
4
5
  export { logger } from './logger.js';
5
- export { Condition, noneOf, oneOf, prefix, } from './metrics.js';
6
- export { fields, } from './records.js';
6
+ export { exponentialBuckets, } from './metrics.js';
7
+ export { SearchIndex, search, TableIndex, } from './search.js';
8
+ export { Sql, sql, } from './sql.js';
7
9
  export { connect, open, Store, } from './store.js';
8
10
  export { withTrace } from './trace.js';