@tinyshed/tinystore 0.5.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/config.d.ts CHANGED
@@ -28,6 +28,12 @@ interface Described extends Rules {
28
28
  required?: boolean;
29
29
  live?: boolean;
30
30
  secret?: boolean;
31
+ /** of a map of entries, each entry's group; its kind is 'object', as an older release reads it */
32
+ entries?: Group;
33
+ /** of a chosen group, the key of the setting beside it whose value names its group */
34
+ chosenBy?: string;
35
+ /** of a chosen group, each group by the name its chooser gives it; its kind is 'object' too */
36
+ groups?: Record<string, Group>;
31
37
  }
32
38
  /**
33
39
  * A setting its declaration says more of than a default would: its rules, a
@@ -43,6 +49,23 @@ export interface Setting<V, Live extends boolean = false, Given extends boolean
43
49
  readonly '~given'?: Given;
44
50
  readonly '~secret'?: IsSecret;
45
51
  }
52
+ /**
53
+ * A map of named entries, as `entries` declares one: each entry the group
54
+ * `G`, read as its settings are.
55
+ */
56
+ export interface Entries<G> extends Setting<Readonly<Record<string, Value<G>>>> {
57
+ /** what an object in code gives each entry; nothing at run time */
58
+ readonly '~entries': G;
59
+ }
60
+ /**
61
+ * A group whose settings are those of one of `G`, the one a text setting
62
+ * beside it names, as `chosenBy` declares one: each of `G`'s groups read as
63
+ * its settings are.
64
+ */
65
+ export interface Chosen<G> extends Setting<Value<G[keyof G]>> {
66
+ /** what an object in code gives the group; nothing at run time */
67
+ readonly '~chosen': G;
68
+ }
46
69
  /** A setting's text that prints as *** wherever it goes; `reveal` gives it. */
47
70
  export declare class Secret {
48
71
  #private;
@@ -65,7 +88,7 @@ export type Changes<D> = {
65
88
  };
66
89
  /** An object in code over the declaration: any of its settings, at any depth, a secret as text. */
67
90
  export type Overlay<D> = {
68
- readonly [K in keyof D]?: D[K] extends Setting<infer V, boolean, boolean, boolean> ? V extends Secret ? string : V : D[K] extends readonly unknown[] ? Value<D[K]> : D[K] extends object ? Overlay<D[K]> : Value<D[K]>;
91
+ readonly [K in keyof D]?: D[K] extends Entries<infer G> ? Readonly<Record<string, Overlay<G>>> : D[K] extends Chosen<infer G> ? Overlay<G[keyof G]> : D[K] extends Setting<infer V, boolean, boolean, boolean> ? V extends Secret ? string : V : D[K] extends readonly unknown[] ? Value<D[K]> : D[K] extends object ? Overlay<D[K]> : Value<D[K]>;
69
92
  };
70
93
  /** A file a config reads: TOML, YAML or JSON by its extension. */
71
94
  export interface FileLayer {
@@ -182,6 +205,10 @@ export interface DurationBounds {
182
205
  min?: DurationText | undefined;
183
206
  max?: DurationText | undefined;
184
207
  }
208
+ /** The entries a map of entries' declaration gives, each as an object in code gives one. */
209
+ export interface EntriesOptions<G> {
210
+ default?: Readonly<Record<string, Overlay<G>>> | undefined;
211
+ }
185
212
  /** A list's default and how many items it holds at least and at most. */
186
213
  export interface ListOptions<V> extends Bounds {
187
214
  default?: readonly V[] | undefined;
@@ -221,6 +248,24 @@ export declare function duration(fallback: DurationText, rules?: DurationBounds)
221
248
  export declare function list<T extends Token>(item: T, options?: ListOptions<Of<T>>): Setting<readonly Of<T>[]>;
222
249
  export declare function list<V>(item: Setting<V, false, boolean>, options?: ListOptions<V>): Setting<readonly V[]>;
223
250
  export declare function list<G extends object>(item: G, options?: ListOptions<Value<G>>): Setting<readonly Value<G>[]>;
251
+ /**
252
+ * A map of named entries, each the group `item` declares, whose fields are
253
+ * settings of their own, with their own marks: a file gives an entry field
254
+ * by field, and `APP_INSTANCE_AIMEE_PASSWORD`, or its `_FILE`, one field of
255
+ * the entry `aimee` that a layer before it made. A map written as a value,
256
+ * `{}`, is one setting, given whole.
257
+ */
258
+ export declare function entries<G extends object>(item: G, options?: EntriesOptions<G>): Entries<G>;
259
+ /**
260
+ * A group whose settings are those of one of `groups`, the one the text
261
+ * setting beside it, `by`, names: `settings: chosenBy('plugin', { postgres,
262
+ * stripe })` reads an instance's settings as postgres's when its `plugin` is
263
+ * 'postgres'. Its fields are settings of their own, with their own marks; a
264
+ * field of a group not chosen is refused, and so is a `plugin` that names no
265
+ * group. A layer after the one that chose a group may choose another: then
266
+ * what the layers gave the first is dropped, and explain says so.
267
+ */
268
+ export declare function chosenBy<const G extends Readonly<Record<string, object>>>(by: string, groups: G): Chosen<G>;
224
269
  /** A file a config reads: TOML, YAML or JSON by its extension, a relative path the program's. */
225
270
  export declare function file(path: string, options?: FileOptions): FileLayer;
226
271
  /**
package/dist/config.js CHANGED
@@ -83,6 +83,7 @@ export function required(given) {
83
83
  if (inner === undefined) {
84
84
  throw new InvalidError('required takes String, Number, Boolean, or a rule without its default');
85
85
  }
86
+ refuseEntries(inner);
86
87
  if (inner.secret === true) {
87
88
  throw new InvalidError('a secret is required already: secret(String)');
88
89
  }
@@ -97,6 +98,7 @@ export function live(given) {
97
98
  throw new InvalidError('a mark goes on a setting, not on a group: mark each of its settings');
98
99
  }
99
100
  const inner = describedOf(given) ?? declaredValue(given, 'live');
101
+ refuseEntries(inner);
100
102
  if (inner.secret === true) {
101
103
  throw new InvalidError('a secret is never live');
102
104
  }
@@ -141,6 +143,7 @@ function itemOf(item) {
141
143
  }
142
144
  const inner = describedOf(item);
143
145
  if (inner !== undefined) {
146
+ refuseEntries(inner);
144
147
  if (inner.live === true || inner.secret === true) {
145
148
  throw new InvalidError("a list's items are neither live nor secret: the list is one setting");
146
149
  }
@@ -152,6 +155,57 @@ function itemOf(item) {
152
155
  }
153
156
  throw new InvalidError(`a list of ${String(item)}: of String, Number, Boolean, a rule or a group`);
154
157
  }
158
+ /**
159
+ * A map of named entries, each the group `item` declares, whose fields are
160
+ * settings of their own, with their own marks: a file gives an entry field
161
+ * by field, and `APP_INSTANCE_AIMEE_PASSWORD`, or its `_FILE`, one field of
162
+ * the entry `aimee` that a layer before it made. A map written as a value,
163
+ * `{}`, is one setting, given whole.
164
+ */
165
+ export function entries(item, options = {}) {
166
+ if (!isPlainObject(item) || describedOf(item) !== undefined || Object.keys(item).length === 0) {
167
+ throw new InvalidError('an entry is a group of settings: entries({ host: String, password: secret(String) })');
168
+ }
169
+ const described = {
170
+ kind: 'object',
171
+ default: options.default ?? {},
172
+ entries: declaredGroup(item, '*'),
173
+ };
174
+ return setting(described);
175
+ }
176
+ /**
177
+ * A group whose settings are those of one of `groups`, the one the text
178
+ * setting beside it, `by`, names: `settings: chosenBy('plugin', { postgres,
179
+ * stripe })` reads an instance's settings as postgres's when its `plugin` is
180
+ * 'postgres'. Its fields are settings of their own, with their own marks; a
181
+ * field of a group not chosen is refused, and so is a `plugin` that names no
182
+ * group. A layer after the one that chose a group may choose another: then
183
+ * what the layers gave the first is dropped, and explain says so.
184
+ */
185
+ export function chosenBy(by, groups) {
186
+ const named = Object.entries(groups);
187
+ if (typeof by !== 'string' || by === '' || !isPlainObject(groups) || named.length === 0) {
188
+ throw new InvalidError("a chosen group: chosenBy('plugin', { postgres: { host: String }, stripe: { key: secret(String) } })");
189
+ }
190
+ const declared = {};
191
+ for (const [name, group] of named) {
192
+ if (!isPlainObject(group) || describedOf(group) !== undefined) {
193
+ throw new InvalidError(`chosenBy: ${name} is a group of settings, not a setting`);
194
+ }
195
+ declared[name] = declaredGroup(group, name);
196
+ }
197
+ const described = { kind: 'object', default: {}, chosenBy: by, groups: declared };
198
+ return setting(described);
199
+ }
200
+ /** A mark around a map of entries or a chosen group, which marks none of their settings. */
201
+ function refuseEntries(inner) {
202
+ if (inner.entries !== undefined) {
203
+ throw new InvalidError('entries take no mark: each of their fields carries its own');
204
+ }
205
+ if (inner.groups !== undefined) {
206
+ throw new InvalidError('a chosen group takes no mark: each of its settings carries its own');
207
+ }
208
+ }
155
209
  /** A file a config reads: TOML, YAML or JSON by its extension, a relative path the program's. */
156
210
  export function file(path, options = {}) {
157
211
  return Object.freeze({ [layerMark]: 'file', path, optional: options.optional === true });
@@ -243,11 +297,22 @@ function plainItem(first) {
243
297
  return { kind: 'any' };
244
298
  }
245
299
  }
246
- /** Every setting's path, as the core names its variable. */
300
+ /** Every setting's path, as the core names its variable, every map of entries' and every chosen group's. */
247
301
  function paths(group, path) {
248
302
  return Object.entries(group).flatMap(([key, node]) => {
249
303
  const at = path === '' ? key : `${path}.${key}`;
250
- return 'group' in node ? paths(node.group, at) : [at];
304
+ if ('group' in node) {
305
+ return paths(node.group, at);
306
+ }
307
+ const chosen = Object.values(node.groups ?? {}).flatMap(inner => paths(inner, at));
308
+ return node.groups === undefined ? [at] : [...new Set(chosen)];
309
+ });
310
+ }
311
+ /** Every map of entries' path, whose entries' variables begin with its own. */
312
+ function entryMaps(group, path) {
313
+ return Object.entries(group).flatMap(([key, node]) => {
314
+ const at = path === '' ? key : `${path}.${key}`;
315
+ return 'group' in node ? entryMaps(node.group, at) : node.entries === undefined ? [] : [at];
251
316
  });
252
317
  }
253
318
  /**
@@ -320,11 +385,15 @@ async function envData(layer, declared) {
320
385
  const key = (name) => (windows ? name.toUpperCase() : name);
321
386
  const named = paths(declared, '').map(path => layer.vars[path] ?? envName(layer.prefix, path));
322
387
  const wanted = new Set(named.flatMap(name => [key(name), key(`${name}_FILE`)]));
323
- const start = key(`${layer.prefix}_`);
388
+ // an entry's field is named by its key, so its map's variable is what it begins with
389
+ const starts = entryMaps(declared, '').map(path => key(`${envName(layer.prefix, path)}_`));
390
+ if (layer.prefix !== '') {
391
+ starts.push(key(`${layer.prefix}_`));
392
+ }
324
393
  const variables = {};
325
394
  for (const [name, value] of Object.entries(layer.from ?? process.env)) {
326
395
  const k = key(name);
327
- if (value !== undefined && (wanted.has(k) || (layer.prefix !== '' && k.startsWith(start)))) {
396
+ if (value !== undefined && (wanted.has(k) || starts.some(start => k.startsWith(start)))) {
328
397
  variables[k] = value;
329
398
  }
330
399
  }
@@ -358,16 +427,34 @@ function fileVariables(text) {
358
427
  }
359
428
  return found;
360
429
  }
361
- /** A value as the program reads it: a duration spelled, a secret wrapped, all of it frozen. */
430
+ /**
431
+ * A value as the program reads it: a duration spelled, a secret wrapped, a
432
+ * chosen group as the group its chooser names, all of it frozen.
433
+ */
362
434
  function viewed(group, value) {
363
435
  const source = (isPlainObject(value) ? value : {});
364
436
  const out = {};
365
437
  for (const [key, node] of Object.entries(group)) {
366
- out[key] = 'group' in node ? viewed(node.group, source[key]) : viewedSetting(node, source[key]);
438
+ if ('group' in node) {
439
+ out[key] = viewed(node.group, source[key]);
440
+ }
441
+ else if (node.groups !== undefined) {
442
+ const name = source[node.chosenBy ?? ''];
443
+ const chosen = typeof name === 'string' ? node.groups[name] : undefined;
444
+ out[key] = viewed(chosen ?? {}, source[key]);
445
+ }
446
+ else {
447
+ out[key] = viewedSetting(node, source[key]);
448
+ }
367
449
  }
368
450
  return Object.freeze(out);
369
451
  }
370
452
  function viewedSetting(described, value) {
453
+ const item = described.entries;
454
+ if (item !== undefined) {
455
+ const each = Object.entries(isPlainObject(value) ? value : {});
456
+ return Object.freeze(Object.fromEntries(each.map(([key, entry]) => [key, viewed(item, entry)])));
457
+ }
371
458
  if (described.secret === true) {
372
459
  return new Secret(typeof value === 'string' ? value : '');
373
460
  }
@@ -462,7 +549,7 @@ function originOf(sent) {
462
549
  return { kind: sent.kind };
463
550
  }
464
551
  }
465
- /** The text the core's `from` says: crates/tinystore/src/kv/config/explain.rs, Origin's Display. */
552
+ /** The text the core's `from` says: crates/tinystore/src/config/explain.rs, Origin's Display. */
466
553
  function originText(origin) {
467
554
  switch (origin.kind) {
468
555
  case 'declaration':
package/dist/index.d.ts CHANGED
@@ -3,7 +3,7 @@ export type { Body, FileBytes, FileInfo, FileListOptions, FileOptions, FilePage,
3
3
  export { withSignal } from './cancel.ts';
4
4
  export type { Channel, EachOptions, Message as ChannelMessage, Missed, SubscribeOptions, Subscription, TxChannel, } from './channels.ts';
5
5
  export type { Clock } from './clock.ts';
6
- export { type Bounds, type Changes, type Config, type ConfigOptions, type DurationBounds, duration, type EnvLayer, type EnvOptions, type Explained, type ExplainGiven, type ExplainLine, type ExplainOrigin, 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';
6
+ export { type Bounds, type Changes, type Chosen, type Config, type ConfigOptions, chosenBy, type DurationBounds, duration, type Entries, type EntriesOptions, type EnvLayer, type EnvOptions, type Explained, type ExplainGiven, type ExplainLine, type ExplainOrigin, entries, 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
7
  export type { Durability, SelfMetrics } from './connection.ts';
8
8
  export { type ConsoleFormat, type ConsoleTime, secrets } from './console.ts';
9
9
  export * from './errors.ts';
@@ -12,11 +12,11 @@ export type { Adding, AddOptions, Answer, Backoff, Concurrency, Handler, Job, Jo
12
12
  export type { Bucket, BucketOptions, Counters, CountersOptions, Entry, Page as KvPage, ValueType, WriteOptions, } from './kv.ts';
13
13
  export type { Allowance, Quota, Rate, RateLimit, RateLimitOptions, WindowUse } from './limits.ts';
14
14
  export type { HoldOptions, Lease, Lock, LockOptions, Permit, Semaphore, SemaphoreOptions, Tried, } from './locks.ts';
15
- export { type ConsoleOut, type Logger, type LoggerOptions, logger } from './logger.ts';
15
+ export { type ConsoleOut, colors, type Logger, type LoggerOptions, logger } from './logger.ts';
16
16
  export { type Aggregate, type AggregatePage, 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 PrometheusOptions, type Query as MetricsQuery, type Series, type SeriesInput, type SeriesKind, type SeriesPage, type Timer, type TimerOptions, type Timing, type ValueBucket, type ValuePage, } from './metrics.ts';
17
17
  export type { Once, OnceOptions } from './once.ts';
18
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, Levels, Lines, NewEvent, Page as EventsPage, PollBatch, Query as EventsQuery, Row as EventsRow, Stats, StoreLoggerOptions, StreamInfo, TailBatch, TailQuery, Top, } from './records.ts';
19
+ export type { Aggregate as EventsAggregate, AllEvents, Appending, AppendOptions, Counted, Damage, Event, EventLevel, Events, EventsOptions, FieldInfo, Fields, Level, Levels, Lines, NameCount, NewEvent, Page as EventsPage, PollBatch, Query as EventsQuery, Row as EventsRow, Stats, StoreLoggerOptions, StreamFields, StreamInfo, TailBatch, TailQuery, Top, TxEvents, ValueKind, } from './records.ts';
20
20
  export type { StandardSchemaV1 } from './schema.ts';
21
21
  export { type Found as SearchFound, type Hit as SearchHit, type IndexDocument, type IndexInfo, type IndexOptions, type IndexStatus, type KeyboardLayout, type Match as SearchMatch, type Query as SearchQuery, SearchIndex, search, TableIndex, type TableIndexOptions, type Vector, type Where, type WhereValue, } from './search.ts';
22
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';
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
1
  export { withSignal } from './cancel.js';
2
- export { duration, env, file, int, list, live, oneOf, required, Secret, secret, } from './config.js';
2
+ export { chosenBy, duration, entries, env, file, int, list, live, oneOf, required, Secret, secret, } from './config.js';
3
3
  export { secrets } from './console.js';
4
4
  export * from './errors.js';
5
- export { logger } from './logger.js';
5
+ export { colors, logger } from './logger.js';
6
6
  export { exponentialBuckets, } from './metrics.js';
7
7
  export { SearchIndex, search, TableIndex, } from './search.js';
8
8
  export { Sql, sql, } from './sql.js';
package/dist/logger.d.ts CHANGED
@@ -103,6 +103,16 @@ type Told = Omit<LoggerOptions, 'level'> & {
103
103
  export declare function newStoreLogger(append: (lines: ConsoleLine[]) => Promise<void>, stream: string, options?: Told): [Logger, LogConfig];
104
104
  /** TinyStore's own lines, on the console of a logger of stream tinystore made when first needed. */
105
105
  export declare const sayOwn: Say;
106
+ /**
107
+ * Whether a stream shows colours, by the rule every logger keeps, in Bun,
108
+ * Python, Go and Rust, and the command line too, so that a program's own
109
+ * words and the log lines printed beside them are coloured alike: off under
110
+ * NO_COLOR or a TERM of dumb, on where FORCE_COLOR is other than 0, a pipe or
111
+ * a file too, and otherwise on a terminal alone.
112
+ *
113
+ * `const painted = colors(process.stdout)`
114
+ */
115
+ export declare function colors(stream: Pick<ConsoleOut, 'isTTY'>): boolean;
106
116
  /**
107
117
  * A logger of one stream. `info`, `warn` and the rest return at once; a line
108
118
  * goes to the console as it is logged, and becomes a record named `log`, its
package/dist/logger.js CHANGED
@@ -226,6 +226,21 @@ function forceColor() {
226
226
  const force = process.env.FORCE_COLOR;
227
227
  return force !== undefined && force !== '' && force !== '0';
228
228
  }
229
+ /**
230
+ * Whether a stream shows colours, by the rule every logger keeps, in Bun,
231
+ * Python, Go and Rust, and the command line too, so that a program's own
232
+ * words and the log lines printed beside them are coloured alike: off under
233
+ * NO_COLOR or a TERM of dumb, on where FORCE_COLOR is other than 0, a pipe or
234
+ * a file too, and otherwise on a terminal alone.
235
+ *
236
+ * `const painted = colors(process.stdout)`
237
+ */
238
+ export function colors(stream) {
239
+ if (process.env.NO_COLOR || process.env.TERM === 'dumb') {
240
+ return false;
241
+ }
242
+ return forceColor() || stream.isTTY === true;
243
+ }
229
244
  /** Whether a console told no format prints pretty lines: on a terminal, or where FORCE_COLOR asks. */
230
245
  function prettyUntold(options, out) {
231
246
  const stream = out ?? options.to ?? process.stderr;
@@ -238,17 +253,12 @@ function printer(options, out) {
238
253
  return undefined;
239
254
  }
240
255
  const stream = out ?? options.to ?? process.stderr;
241
- const forced = out === undefined && forceColor();
242
- const terminal = stream.isTTY === true;
243
256
  const pretty = options.console === 'pretty' || (options.console === undefined && prettyUntold(options, out));
244
257
  if (!pretty) {
245
258
  return line => void stream.write(jsonLine(line));
246
259
  }
247
- const color = (forced || (terminal && out === undefined)) &&
248
- !process.env.NO_COLOR &&
249
- process.env.TERM !== 'dumb';
250
260
  const look = {
251
- color,
261
+ color: out === undefined && colors(stream),
252
262
  utc: out?.utc === true,
253
263
  time: options.time,
254
264
  hideStream: options.hideStream,
package/dist/metrics.d.ts CHANGED
@@ -218,6 +218,23 @@ export declare class Metrics {
218
218
  constructor(link: Link, instruments: Instruments);
219
219
  /** Writes series and their samples, every one or none: a refused series names itself. */
220
220
  ingest(series: SeriesInput | readonly SeriesInput[]): Promise<void>;
221
+ /**
222
+ * Replaces a gauge's samples from `from` to `to`, `to` excluded, with the series' own,
223
+ * whether the store had packed them or not: a time given takes its value, a time not there
224
+ * before is added, and a time the series does not give goes. One write: a read sees the
225
+ * range as it was or as it is now, never half, and the same samples sent again write
226
+ * nothing. A counter's or a histogram's is an InvalidError.
227
+ *
228
+ * // the last three days read again from the shop's database, a refund taken off yesterday
229
+ * await store.metrics.replace(
230
+ * { name: 'revenue', kind: 'gauge', labels: { shop: 'msk' }, samples: [[day(3), 1000], [day(2), 1000], [day(1), 900]] },
231
+ * { from: day(3), to: day(0) },
232
+ * )
233
+ */
234
+ replace(series: SeriesInput, range: {
235
+ from: Time;
236
+ to: Time;
237
+ }): Promise<void>;
221
238
  /**
222
239
  * Reads the text an exporter serves, in Prometheus' format or OpenMetrics', and writes its
223
240
  * series, every one or none: a counter as a counter, a histogram's _bucket series as
package/dist/metrics.js CHANGED
@@ -9,7 +9,7 @@ import { InvalidError, OutcomeUnknownError } from './errors.js';
9
9
  import { Counter, Gauge, Histogram, labelsOf, Timer, } from './instruments.js';
10
10
  import { ConnectionLostError } from './session.js';
11
11
  import { ms, unixMs } from './time.js';
12
- import { Empty, MetricsAggregateAsked, MetricsAggregates, MetricsDamages, MetricsDeleted, MetricsDescription, MetricsExposition, MetricsIngest, MetricsLatest, MetricsNameAsked, MetricsNamePage, MetricsPageAsked, MetricsPiece, MetricsPlan, MetricsQuery, MetricsRead, MetricsSeriesNamed, MetricsTextPage, MetricsUpload, methods, } from './wire/protocol.js';
12
+ import { Empty, MetricsAggregateAsked, MetricsAggregates, MetricsDamages, MetricsDeleted, MetricsDescription, MetricsExposition, MetricsIngest, MetricsLatest, MetricsNameAsked, MetricsNamePage, MetricsPageAsked, MetricsPiece, MetricsPlan, MetricsQuery, MetricsRead, MetricsReplace, MetricsSeriesNamed, MetricsTextPage, MetricsUpload, methods, } from './wire/protocol.js';
13
13
  export { Counter, exponentialBuckets, Gauge, Histogram, Timer, Timing, } from './instruments.js';
14
14
  /**
15
15
  * A store's metrics: series by name and labels, their reads and aggregates,
@@ -31,6 +31,27 @@ export class Metrics {
31
31
  const body = MetricsIngest.encode({ series: given.map(newSeries) });
32
32
  await this.#link.run('write', connection => connection.session.call(methods['metrics.ingest'], body));
33
33
  }
34
+ /**
35
+ * Replaces a gauge's samples from `from` to `to`, `to` excluded, with the series' own,
36
+ * whether the store had packed them or not: a time given takes its value, a time not there
37
+ * before is added, and a time the series does not give goes. One write: a read sees the
38
+ * range as it was or as it is now, never half, and the same samples sent again write
39
+ * nothing. A counter's or a histogram's is an InvalidError.
40
+ *
41
+ * // the last three days read again from the shop's database, a refund taken off yesterday
42
+ * await store.metrics.replace(
43
+ * { name: 'revenue', kind: 'gauge', labels: { shop: 'msk' }, samples: [[day(3), 1000], [day(2), 1000], [day(1), 900]] },
44
+ * { from: day(3), to: day(0) },
45
+ * )
46
+ */
47
+ async replace(series, range) {
48
+ const body = MetricsReplace.encode({
49
+ series: newSeries(series),
50
+ from: unixMs(range.from),
51
+ to: unixMs(range.to),
52
+ });
53
+ await this.#link.run('write', connection => connection.session.call(methods['metrics.replace'], body));
54
+ }
34
55
  /**
35
56
  * Reads the text an exporter serves, in Prometheus' format or OpenMetrics', and writes its
36
57
  * series, every one or none: a counter as a counter, a histogram's _bucket series as
package/dist/records.d.ts CHANGED
@@ -1,9 +1,10 @@
1
- import { type Link } from './connection.ts';
1
+ import { type Connection, type Link } from './connection.ts';
2
2
  import { type ConsoleLine } from './console.ts';
3
+ import { type Home, type Open, type Via } from './handles.ts';
3
4
  import { type LogConfig, type Logger, type LoggerOptions } from './logger.ts';
4
5
  import type { Stream } from './session.ts';
5
6
  import { type Calendar, type Duration, type DurationText } from './time.ts';
6
- import { methods } from './wire/protocol.ts';
7
+ import { methods, type RecordsNewEvent } from './wire/protocol.ts';
7
8
  /** A level a logger logs at: one of its four names, or slog's number between them. */
8
9
  export type Level = 'debug' | 'info' | 'warn' | 'error' | number;
9
10
  /** An event's level: what loggers and the programs whose lines are kept write. */
@@ -126,6 +127,27 @@ export interface StreamInfo {
126
127
  retainedFrom: Date;
127
128
  newest: Date;
128
129
  }
130
+ /** What a stream's events carry, each by name. */
131
+ export interface StreamFields {
132
+ eventNames: NameCount[];
133
+ fields: FieldInfo[];
134
+ context: FieldInfo[];
135
+ }
136
+ /** A name a stream's events have, and how many have it. */
137
+ export interface NameCount {
138
+ name: string;
139
+ count: number;
140
+ }
141
+ /** A key of a stream's events' fields or contexts. */
142
+ export interface FieldInfo {
143
+ name: string;
144
+ /** the kinds of value it holds, in the order `ValueKind` lists them */
145
+ kinds: ValueKind[];
146
+ /** the events that carry it: one that writes it twice, once */
147
+ count: number;
148
+ }
149
+ /** What a value is, as its JSON is spelled: `float` has a fraction or an exponent, `integer` is whole. */
150
+ export type ValueKind = 'float' | 'integer' | 'text' | 'bool' | 'object' | 'list' | 'null';
129
151
  export interface PollBatch {
130
152
  events: Event[];
131
153
  /** where the next poll begins, kept once these events are safe */
@@ -160,7 +182,10 @@ declare abstract class Reads {
160
182
  protected abstract opened(method: Method, body: (handle: number | undefined) => Uint8Array): Promise<Stream>;
161
183
  /** Keeps a stream that follows the store for its close to cancel; it returns what lets it go. */
162
184
  protected abstract follow(stream: Stream): () => void;
163
- /** One page, from one moment of the file: `{ events, next }`. */
185
+ /**
186
+ * One page: `{ events, next }`, its `limit` of events that match, fewer
187
+ * only on the last, which has no `next`.
188
+ */
164
189
  list(query?: Query): Promise<Page>;
165
190
  /** Every event the query finds, a page after another. */
166
191
  all(query?: Query): AsyncGenerator<Event>;
@@ -190,12 +215,28 @@ declare abstract class Reads {
190
215
  }
191
216
  /** Opens a stream of events: lazily, at its first call on a connection. */
192
217
  export declare function openEvents(link: Link, stream: string, options?: EventsOptions): Events;
218
+ /** A stream's open, through the database of `database`, a handle on the connection, when given. */
219
+ export declare function eventsOpen(stream: string, options?: EventsOptions, database?: number): Uint8Array;
220
+ /** What a stream's appends in a database's transaction and batch need of it. */
221
+ interface EventsParts {
222
+ stream: string;
223
+ open: Open;
224
+ home: Home | undefined;
225
+ }
193
226
  /** A stream of events: written with `append`, which waits for the file, and read back. */
194
227
  export declare class Events extends Reads {
195
228
  #private;
196
229
  readonly stream: string;
197
- /** Events come from `store.events(stream)`. */
198
- constructor(link: Link, stream: string, open: Uint8Array);
230
+ /** Events come from `store.events(stream)`, or `db.events(stream)` through a database. */
231
+ constructor(link: Link, stream: string, open: Open, home?: Home);
232
+ /**
233
+ * An event's append for a batch of the database the stream was opened
234
+ * from, `db.events`: it is kept with the batch's rows and reaches the
235
+ * stream once they commit, before the batch returns, or never.
236
+ *
237
+ * await db.batch([sql`update roles set role = ${role} where user_id = ${id}`, audit.appending('role.changed', { userId: id, role })])
238
+ */
239
+ appending(name: string, fields?: Fields, options?: AppendOptions): Appending;
199
240
  /**
200
241
  * Writes an event, or a list of them whole or not at all: it returns once
201
242
  * they are written, and a read finds them at once. An event whose id the
@@ -221,6 +262,44 @@ export declare class Events extends Reads {
221
262
  protected opened(method: Method, body: (handle: number | undefined) => Uint8Array): Promise<Stream>;
222
263
  protected follow(stream: Stream): () => void;
223
264
  }
265
+ /** The parts of a stream, when `handle` is one. */
266
+ export declare function eventsParts(handle: unknown): EventsParts | undefined;
267
+ /**
268
+ * A stream's appends inside a transaction of the database it was opened
269
+ * from, `tx.with(audit)`: each is kept with the transaction's rows and
270
+ * reaches the stream once it commits, before `db.tx` returns. A read goes
271
+ * through the stream itself, and finds what committed.
272
+ */
273
+ export declare class TxEvents {
274
+ #private;
275
+ readonly stream: string;
276
+ /** TxEvents come from `tx.with(events)`. */
277
+ constructor(parts: EventsParts, via: Via);
278
+ /**
279
+ * Appends an event once the transaction commits, and says whether it
280
+ * will be written: false when its stream, or this transaction, holds its id.
281
+ */
282
+ append(name: string, fields?: Fields, options?: AppendOptions): Promise<boolean>;
283
+ }
284
+ interface AppendingParts extends EventsParts {
285
+ event: Parameters<typeof RecordsNewEvent.encode>[0];
286
+ }
287
+ /** An event's append for a database's batch, from `events.appending`. */
288
+ export declare class Appending {
289
+ #private;
290
+ /** Comes from `events.appending`. */
291
+ constructor(parts: AppendingParts);
292
+ }
293
+ /**
294
+ * What a batch of `home` sends of an append, on the connection it goes on:
295
+ * the append's call, its stream's handle opened there first. A stream opened
296
+ * from the store or another database is refused, since its event would not
297
+ * commit with the rows.
298
+ */
299
+ export declare function appendingIn(appending: Appending, home: Home): (connection: Connection) => Promise<{
300
+ method: number;
301
+ body: Uint8Array;
302
+ }>;
224
303
  /** Every stream's events, to read: `store.events()`. */
225
304
  export declare class AllEvents extends Reads {
226
305
  #private;
@@ -228,6 +307,12 @@ export declare class AllEvents extends Reads {
228
307
  constructor(link: Link);
229
308
  /** Every stream with events, by name, with what it keeps, where that begins and its newest event's time. */
230
309
  streams(): Promise<StreamInfo[]>;
310
+ /**
311
+ * What the events of `stream` carry, none of it read from a packed event: each name with how
312
+ * many events have it, and each key of their fields and contexts with the kinds of value it
313
+ * holds and how many events carry it. A stream with no events carries nothing.
314
+ */
315
+ fields(stream: string): Promise<StreamFields>;
231
316
  /**
232
317
  * Every event once, a batch a call, from a cursor the program keeps, the
233
318
  * oldest event kept without one: `{ events, cursor, expired }`. With no