@mark1russell7/capacity 0.0.0-stage → 0.1.1

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 (45) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1110 -2
  3. package/build/index.d.ts +858 -0
  4. package/build/index.d.ts.map +1 -0
  5. package/build/index.js +1713 -0
  6. package/build/index.js.map +1 -0
  7. package/build/instance-check-Bt-SI8va.js +1732 -0
  8. package/build/instance-check-Bt-SI8va.js.map +1 -0
  9. package/build/instance-sZmVOOvz.d.ts +801 -0
  10. package/build/instance-sZmVOOvz.d.ts.map +1 -0
  11. package/build/schema.d.ts +69 -0
  12. package/build/schema.d.ts.map +1 -0
  13. package/build/schema.js +325 -0
  14. package/build/schema.js.map +1 -0
  15. package/limits/alerts-routes.line.json +78 -0
  16. package/limits/alerts-scale.limits.json +10 -0
  17. package/limits/alerts-start-gate.limits.json +1149 -0
  18. package/limits/alerts-start-routes-limit-home.bracket.json +543 -0
  19. package/limits/alerts-start-routes-limit-mid.bracket.json +464 -0
  20. package/limits/alerts-start-routes-limit.bracket.json +579 -0
  21. package/limits/alerts-tail-gate.limits.json +610 -0
  22. package/package.json +85 -3
  23. package/src/app-check.ts +477 -0
  24. package/src/app-metrics.ts +105 -0
  25. package/src/app.ts +239 -0
  26. package/src/check.ts +253 -0
  27. package/src/composition.ts +680 -0
  28. package/src/demand.ts +312 -0
  29. package/src/fit.ts +153 -0
  30. package/src/forms.ts +358 -0
  31. package/src/gate.ts +237 -0
  32. package/src/index.ts +143 -0
  33. package/src/instance-check.ts +122 -0
  34. package/src/instance.ts +84 -0
  35. package/src/knee.ts +606 -0
  36. package/src/law.ts +236 -0
  37. package/src/limit.ts +112 -0
  38. package/src/names.ts +19 -0
  39. package/src/observe.ts +74 -0
  40. package/src/program.ts +74 -0
  41. package/src/scale.ts +617 -0
  42. package/src/schema.ts +263 -0
  43. package/src/value.ts +206 -0
  44. package/src/workload-check.ts +130 -0
  45. package/src/workload.ts +88 -0
package/src/scale.ts ADDED
@@ -0,0 +1,617 @@
1
+ import { err, ok, type Result } from "@mark1russell7/optional";
2
+ import { convertible, factorOf, whyNotConvertible } from "@mark1russell7/quantity";
3
+ import {
4
+ flatPartsOf,
5
+ partsOutside,
6
+ preparedOf,
7
+ rowValueOf,
8
+ rowValuesOf,
9
+ type Catalog,
10
+ type Composition,
11
+ type CompositionProblemCode,
12
+ type FlatPart,
13
+ type Prepared,
14
+ } from "./composition.ts";
15
+ import { portionOf } from "./demand.ts";
16
+ import type { Instance, Limit, LimitProblemCode } from "./instance.ts";
17
+ import { MAX_STEPS, amountTest, openValueOf, rowOf, searchGrid, type Curve, type OpenValue } from "./knee.ts";
18
+ import { DEFAULT_LEVEL, type Problem } from "./law.ts";
19
+ import { limitAmount } from "./limit.ts";
20
+ import { repeated } from "./names.ts";
21
+ import type { LevelOptions, Range } from "./value.ts";
22
+ import { demandProblems } from "./workload-check.ts";
23
+ import type { Amounts, Demand } from "./workload.ts";
24
+
25
+ /** This number is the largest count of instances of a scale search when the options give none: 2 to the power 20. */
26
+ export const SCALE_MOST: number = 2 ** 20;
27
+
28
+ /** This number is the count of steps of the grid of a scale search when the options give none. */
29
+ export const SCALE_STEPS: number = 128;
30
+
31
+ /**
32
+ * A scale model holds what the scale queries of a service read: the resources of one instance, the
33
+ * limits of the service and the compositions. Each limit reads the composition of its measure. The
34
+ * catalog gives each law and each nested composition that the compositions name.
35
+ */
36
+ export interface ScaleModel {
37
+ readonly instance: Instance;
38
+ readonly limits: readonly Limit[];
39
+ /** Each composition gives one measure, by the id of its measure. The list can hold compositions that no limit reads. */
40
+ readonly compositions: readonly Composition[];
41
+ readonly catalog: Catalog;
42
+ }
43
+
44
+ /**
45
+ * These options set a scale query. The field `given` gives the state of each instance, for example
46
+ * its heap. A level in `whole` does not divide between the instances, as in `shareOf`.
47
+ *
48
+ * The count search goes up to `most` instances. The load search goes from `1 / most` to `most`
49
+ * times the demand. Each search has a grid of `steps` steps on a log scale. The level of the
50
+ * intervals is 0.95 when the options give none.
51
+ */
52
+ export interface ScaleOptions extends LevelOptions {
53
+ readonly given?: Amounts;
54
+ readonly whole?: readonly string[];
55
+ readonly most?: number;
56
+ readonly steps?: number;
57
+ }
58
+
59
+ /** A scale problem code names the part of a scale model, or of a scale query, that is not correct. */
60
+ export type ScaleProblemCode = CompositionProblemCode | LimitProblemCode;
61
+
62
+ /** A scale problem tells what is not correct, and where: `path` is the path of the field in the model or in the query. */
63
+ export type ScaleProblem = Problem<ScaleProblemCode>;
64
+
65
+ /**
66
+ * A limit count is the lowest count of instances that holds one limit at a load. Each larger count
67
+ * also holds the limit. A null count is more than the largest count of the search.
68
+ */
69
+ export interface LimitCount {
70
+ readonly limit: string;
71
+ readonly measure: string;
72
+ readonly count: OpenValue;
73
+ /** This number is the share of the replicates where this limit needs more instances than each other limit. */
74
+ readonly binds: number;
75
+ /** This flag tells that the composition has no value past the share of the estimate. Then the edge of the composition sets the count. */
76
+ readonly edge: boolean;
77
+ /** This flag tells that a law of the composition reads a variable outside its range at the count of the estimate. */
78
+ readonly extrapolated: boolean;
79
+ }
80
+
81
+ /**
82
+ * A limit reach is the first load where one limit breaks at a count of instances, as a factor of
83
+ * the demand. Below this factor, the limit holds. A null factor is past the end of the search.
84
+ */
85
+ export interface LimitReach {
86
+ readonly limit: string;
87
+ readonly measure: string;
88
+ readonly factor: OpenValue;
89
+ /** This number is the share of the replicates where this limit breaks before each other limit. */
90
+ readonly binds: number;
91
+ /** This flag tells that the composition has no value past the factor of the estimate. Then the edge of the composition sets the factor. */
92
+ readonly edge: boolean;
93
+ /** This flag tells that a law of the composition reads a variable outside its range at the factor of the estimate. */
94
+ readonly extrapolated: boolean;
95
+ }
96
+
97
+ /**
98
+ * A count reach is the highest load that a count of instances holds, as a factor of the demand. The
99
+ * demand at the factor `f` is `scaleDemand(demand, f)`. The `factor` is the first factor where a
100
+ * limit breaks, and the `binding` limit breaks there in the estimate.
101
+ *
102
+ * The limits go from the first limit that breaks to the last. The flag `extrapolated` tells that a
103
+ * law reads a variable outside its range at the factor of the estimate.
104
+ */
105
+ export interface CountReach {
106
+ readonly count: number;
107
+ readonly level: number;
108
+ readonly search: Range;
109
+ readonly factor: OpenValue;
110
+ readonly binding: string | null;
111
+ readonly extrapolated: boolean;
112
+ readonly limits: readonly LimitReach[];
113
+ }
114
+
115
+ /**
116
+ * A scale rule is the lowest count of instances that holds each limit at a load, with its interval.
117
+ * Each larger count also holds each limit. A null count is more than `most` instances.
118
+ *
119
+ * The `binding` limit needs the most instances in the estimate. It is null when one instance holds
120
+ * each limit at each share of the search. The limits go from the largest count to the smallest. The
121
+ * reach `next` is the highest load of the count of the estimate: there the service needs one more instance.
122
+ */
123
+ export interface ScaleRule {
124
+ readonly level: number;
125
+ readonly most: number;
126
+ readonly count: OpenValue;
127
+ readonly binding: string | null;
128
+ readonly extrapolated: boolean;
129
+ readonly limits: readonly LimitCount[];
130
+ readonly next: CountReach | null;
131
+ }
132
+
133
+ /** The setup of one limit: its composition, and the number that changes a value of the composition to a use of the limit. */
134
+ interface LimitSetup {
135
+ readonly limit: Limit;
136
+ readonly path: string;
137
+ /** This index is the index of the composition in the model. */
138
+ readonly at: number;
139
+ readonly prepared: Prepared;
140
+ /** This number times a value of the composition is the use of the limit. A use above 1 breaks the limit. */
141
+ readonly per: number;
142
+ }
143
+
144
+ /** The setup of a scale query: each limit, the count of rows that the limits share, and the options. */
145
+ interface Setup {
146
+ readonly limits: readonly LimitSetup[];
147
+ readonly rows: number;
148
+ readonly level: number;
149
+ readonly given: Amounts;
150
+ readonly whole: readonly string[];
151
+ readonly most: number;
152
+ readonly steps: number;
153
+ readonly demand: Demand;
154
+ }
155
+
156
+ /** A path of demands gives the demand on one instance at each load of a search. */
157
+ type DemandAt = (load: number) => Demand | undefined;
158
+
159
+ /** The search of one limit: the first load where each row breaks the limit, and if the edge sets the load of the estimate. Row 0 is the estimate. */
160
+ interface LimitBreaks {
161
+ readonly rows: readonly number[];
162
+ readonly edge: boolean;
163
+ }
164
+
165
+ /**
166
+ * The summary holds the rows of all limits: the first load where each row breaks a limit. It also holds the limit that
167
+ * breaks first in the estimate, and the share of the rows where each limit is first.
168
+ */
169
+ interface Summary {
170
+ readonly rows: readonly number[];
171
+ readonly binding: number | null;
172
+ readonly binds: readonly number[];
173
+ /** These indexes put the limits in the order of the load of the estimate, from the first limit that breaks. */
174
+ readonly order: readonly number[];
175
+ }
176
+
177
+ const problem = (code: ScaleProblemCode, path: string, message: string): ScaleProblem => ({ code, path, message });
178
+
179
+ /** This function gives a problem with `owner` in front of its path. */
180
+ const under = (found: Problem<string>, owner: string): ScaleProblem => ({
181
+ code: found.code as ScaleProblemCode,
182
+ path: `${owner}.${found.path}`,
183
+ message: found.message,
184
+ });
185
+
186
+ /**
187
+ * This function gives a problem of a composition of the model, with the path in the model. A path of
188
+ * the catalog starts with `laws` or `compositions`, and each other path is in the composition.
189
+ */
190
+ const inComposition = (found: Problem<string>, at: number): ScaleProblem =>
191
+ under(found, /^(laws|compositions)\./.test(found.path) ? "catalog" : `compositions[${at}]`);
192
+
193
+ /** This function gives the setup of a scale query, or the first problem of the model, the demand or the options. */
194
+ const setupOf = (model: ScaleModel, demand: Demand, options: ScaleOptions): Result<Setup, ScaleProblem> => {
195
+ const level = options.level ?? DEFAULT_LEVEL;
196
+ const most = options.most ?? SCALE_MOST;
197
+ if (!Number.isSafeInteger(most) || most < 2) {
198
+ return err(problem("factor", "most", `The largest count of the search, ${most}, is not a whole number of 2 or more.`));
199
+ }
200
+ const badDemand = demandProblems(demand)[0];
201
+ if (badDemand !== undefined) return err(under(badDemand, "demand"));
202
+ const whole = options.whole ?? [];
203
+ const unknown = whole.find((name) => !Object.hasOwn(demand.levels, name));
204
+ if (unknown !== undefined) return err(problem("variable", "whole", `The demand has no level "${unknown}".`));
205
+ if (model.limits.length === 0) return err(problem("measure", "limits", "The model has no limit."));
206
+ const twice = repeated(model.limits.map((limit) => limit.id));
207
+ if (twice !== undefined) return err(problem("id", "limits", `Two limits have the id "${twice}".`));
208
+
209
+ const byMeasure = new Map<string, number>();
210
+ for (const [index, composition] of model.compositions.entries()) {
211
+ const measure = composition.measure.id;
212
+ if (byMeasure.has(measure)) return err(problem("measure", `compositions[${index}].measure.id`, `Two compositions give the measure "${measure}".`));
213
+ byMeasure.set(measure, index);
214
+ }
215
+ const prepared = new Map<number, Prepared>();
216
+ const limits: LimitSetup[] = [];
217
+ for (const [index, limit] of model.limits.entries()) {
218
+ const path = `limits[${index}]`;
219
+ const amount = limitAmount(limit, model.instance);
220
+ if (amount.tag === "err") return err(under(amount.error, amount.error.path.startsWith("resources.") ? "instance" : path));
221
+ const at = byMeasure.get(limit.measure);
222
+ if (at === undefined) {
223
+ return err(problem("measure", `${path}.measure`, `The model has no composition of the measure "${limit.measure}" of the limit "${limit.id}".`));
224
+ }
225
+ const composition = model.compositions[at] as Composition;
226
+ let ready = prepared.get(at);
227
+ if (ready === undefined) {
228
+ const found = preparedOf(composition, model.catalog, level);
229
+ if (found.tag === "err") return err(inComposition(found.error, at));
230
+ ready = found.value;
231
+ prepared.set(at, ready);
232
+ }
233
+ const unit = composition.measure.unit;
234
+ const ceiling = amount.value;
235
+ if (!convertible(unit, ceiling.unit)) {
236
+ const why = whyNotConvertible(unit, ceiling.unit) ?? "the units are different";
237
+ const message = `The composition of the limit "${limit.id}" gives "${unit}", and the ceiling of the limit is in "${ceiling.unit}": ${why}.`;
238
+ return err(problem("unit", `compositions[${at}].measure.unit`, message));
239
+ }
240
+ limits.push({ limit, path, at, prepared: ready, per: factorOf(unit, ceiling.unit) / ceiling.value });
241
+ }
242
+ const rows = Math.min(...limits.map((each) => each.prepared.rows));
243
+ return ok({ limits, rows, level, given: options.given ?? {}, whole, most, steps: options.steps ?? SCALE_STEPS, demand });
244
+ };
245
+
246
+ /** This function gives the flat parts of the composition of a limit at one load of a path, or undefined when the load has none. */
247
+ const partsAt = (setup: Setup, each: LimitSetup, demandAt: DemandAt, load: number): readonly FlatPart[] | undefined => {
248
+ const demand = demandAt(load);
249
+ if (demand === undefined) return undefined;
250
+ const parts = flatPartsOf(each.prepared, demand, setup.given);
251
+ return parts.tag === "ok" ? parts.value : undefined;
252
+ };
253
+
254
+ /**
255
+ * This function searches each limit along a path of demands. For each row of each limit, it gives the first load
256
+ * where the use of the limit is above 1. A load where the composition has no value also breaks the row.
257
+ * Infinity tells that the row holds the limit on all of the grid.
258
+ *
259
+ * A problem of the composition at the start of the search is a problem of the model, and not an edge.
260
+ */
261
+ const breaksOf = (setup: Setup, grid: readonly number[], demandAt: DemandAt): Result<readonly LimitBreaks[], ScaleProblem> => {
262
+ const found: LimitBreaks[] = [];
263
+ const start = grid[0] as number;
264
+ for (const each of setup.limits) {
265
+ const demand = demandAt(start);
266
+ if (demand !== undefined) {
267
+ const first = flatPartsOf(each.prepared, demand, setup.given);
268
+ if (first.tag === "err") return err(inComposition(first.error, each.at));
269
+ }
270
+ // The loads of the grid repeat in each row. Thus the parts of a load are kept for the next row.
271
+ const known = new Map<number, readonly FlatPart[] | undefined>();
272
+ const cached = (load: number): readonly FlatPart[] | undefined => {
273
+ if (!known.has(load)) known.set(load, partsAt(setup, each, demandAt, load));
274
+ return known.get(load);
275
+ };
276
+ // Each row reads each load of the grid. Thus the values of all the rows at a load of the grid come from one call.
277
+ // The loads of a bisection differ for each row, so they give the value of one row.
278
+ const onGrid = new Set(grid);
279
+ const gridRows = new Map<number, readonly (number | undefined)[] | undefined>();
280
+ const valueAt = (load: number, row: number): number | undefined => {
281
+ if (onGrid.has(load)) {
282
+ if (!gridRows.has(load)) {
283
+ const parts = cached(load);
284
+ gridRows.set(load, parts === undefined ? undefined : rowValuesOf(parts, 0, setup.rows));
285
+ }
286
+ return gridRows.get(load)?.[row];
287
+ }
288
+ const parts = cached(load);
289
+ return parts === undefined ? undefined : rowValueOf(parts, row);
290
+ };
291
+ const rows: number[] = [];
292
+ let edge = false;
293
+ for (let row = 0; row <= setup.rows; row += 1) {
294
+ const curve: Curve = (loads) =>
295
+ loads.map((load) => {
296
+ const value = valueAt(load, row);
297
+ return value === undefined ? undefined : each.per * value;
298
+ });
299
+ const result = rowOf(curve, `${each.path}.rows[${row}]`, amountTest(1), grid, 0, "composition");
300
+ if (result.tag === "err") return result;
301
+ const crossing = result.value.crossing ?? Infinity;
302
+ if (row === 0) edge = result.value.edge <= crossing && Number.isFinite(result.value.edge);
303
+ rows.push(Math.min(crossing, result.value.edge));
304
+ }
305
+ found.push({ rows, edge });
306
+ }
307
+ return ok(found);
308
+ };
309
+
310
+ /** This function gives the index of the least finite value, the first on a tie, or null when no value is finite. */
311
+ const leastOf = (values: readonly number[]): number | null => {
312
+ let best: number | null = null;
313
+ for (const [index, value] of values.entries()) {
314
+ if (Number.isFinite(value) && (best === null || value < (values[best] as number))) best = index;
315
+ }
316
+ return best;
317
+ };
318
+
319
+ /** This function joins the rows of the limits. Each row breaks at the first load where one of its limits breaks. */
320
+ const summaryOf = (breaks: readonly LimitBreaks[], rows: number): Summary => {
321
+ const joined: number[] = [];
322
+ const counts = new Array<number>(breaks.length).fill(0);
323
+ for (let row = 0; row <= rows; row += 1) {
324
+ const loads = breaks.map((each) => each.rows[row] as number);
325
+ const first = leastOf(loads);
326
+ joined.push(first === null ? Infinity : (loads[first] as number));
327
+ if (row > 0 && first !== null) counts[first] = (counts[first] as number) + 1;
328
+ }
329
+ const estimate = breaks.map((each) => each.rows[0] as number);
330
+ const order = estimate.map((_, index) => index).sort((a, b) => (estimate[a] as number) - (estimate[b] as number) || a - b);
331
+ return { rows: joined, binding: leastOf(estimate), binds: counts.map((count) => count / rows), order };
332
+ };
333
+
334
+ /** This function tells if a law of the composition of a limit reads a variable outside its range at one load of a path. */
335
+ const outsideAt = (setup: Setup, each: LimitSetup, demandAt: DemandAt, load: number): boolean => {
336
+ const parts = partsAt(setup, each, demandAt, load);
337
+ return parts !== undefined && partsOutside(parts);
338
+ };
339
+
340
+ /** This function tells if a law of the composition of a limit reads a variable outside its range at one load. */
341
+ type OutsideAt = (each: LimitSetup, load: number) => boolean;
342
+
343
+ /** This function gives the reach of a count of instances from the breaks of each limit along the factor of the demand. */
344
+ const reachFrom = (setup: Setup, count: number, breaks: readonly LimitBreaks[], outside: OutsideAt): CountReach => {
345
+ const { most, level } = setup;
346
+ const summary = summaryOf(breaks, setup.rows);
347
+ const at = (value: number | null): number => value ?? most;
348
+ const limits = summary.order.map((index): LimitReach => {
349
+ const each = setup.limits[index] as LimitSetup;
350
+ const found = breaks[index] as LimitBreaks;
351
+ const factor = openValueOf(found.rows, level, most);
352
+ return {
353
+ limit: each.limit.id,
354
+ measure: each.limit.measure,
355
+ factor,
356
+ binds: summary.binds[index] as number,
357
+ edge: found.edge,
358
+ extrapolated: outside(each, at(factor.value)),
359
+ };
360
+ });
361
+ const factor = openValueOf(summary.rows, level, most);
362
+ return {
363
+ count,
364
+ level,
365
+ search: { low: 1 / most, high: most },
366
+ factor,
367
+ binding: summary.binding === null ? null : (setup.limits[summary.binding] as LimitSetup).limit.id,
368
+ extrapolated: setup.limits.some((each) => outside(each, at(factor.value))),
369
+ limits,
370
+ };
371
+ };
372
+
373
+ /** This function gives the reach of a count of instances, from a correct setup. */
374
+ const reachOf = (setup: Setup, count: number): Result<CountReach, ScaleProblem> => {
375
+ const { most, whole } = setup;
376
+ const grid = searchGrid(1 / most, most, setup.steps, true, "The factor of the demand");
377
+ if (grid.tag === "err") return grid;
378
+ const demandAt: DemandAt = (factor) => {
379
+ const portion = portionOf(setup.demand, factor / count, factor, whole);
380
+ return portion.tag === "ok" ? portion.value : undefined;
381
+ };
382
+ const breaks = breaksOf(setup, grid.value, demandAt);
383
+ if (breaks.tag === "err") return breaks;
384
+ return ok(reachFrom(setup, count, breaks.value, (each, factor) => outsideAt(setup, each, demandAt, factor)));
385
+ };
386
+
387
+ /**
388
+ * This function gives the highest load that a count of instances holds, as a factor of the demand,
389
+ * with an interval. Thus it is the inverse query of the scale rule. The demand divides between the
390
+ * instances, as in `shareOf`, and the levels in `options.whole` do not divide.
391
+ *
392
+ * Each row of the doubt of the laws has its own search. Row `i` of each limit reads row `i` of each
393
+ * law, thus the rows of the limits pair. The factor of a row is the first factor where one limit
394
+ * of the row breaks, or where a composition has no value. The interval is the share `level` of the
395
+ * factors of the replicates, made wider to hold the factor of the estimate.
396
+ *
397
+ * The search tests a grid of factors, then a bisection finds each crossing. A crossing between two
398
+ * loads of the grid is found. Two crossings in one step of the grid can hide the first.
399
+ *
400
+ * The function gives a problem for a model, a demand or options that are not correct. It gives a
401
+ * problem for a count that is not a whole number of 1 or more. It also gives a problem when a
402
+ * composition has no value at the start of the search.
403
+ */
404
+ export const countReach = (model: ScaleModel, count: number, demand: Demand, options: ScaleOptions = {}): Result<CountReach, ScaleProblem> => {
405
+ const setup = setupOf(model, demand, options);
406
+ if (setup.tag === "err") return setup;
407
+ if (!Number.isSafeInteger(count) || count < 1) {
408
+ return err(problem("factor", "count", `The count of instances ${count} is not a whole number of 1 or more.`));
409
+ }
410
+ return reachOf(setup.value, count);
411
+ };
412
+
413
+ /** This function gives the lowest count of instances for a share of one instance where a limit breaks. A null count is more than `most`. */
414
+ const countAt = (share: number | null, most: number): number | null => {
415
+ if (share === null) return 1;
416
+ const count = Math.floor(1 / share) + 1;
417
+ return count > most ? null : count;
418
+ };
419
+
420
+ /** This function changes an open value of the share of one instance to an open value of the count. The ends change places. */
421
+ const countsOf = (share: OpenValue, most: number): OpenValue => ({
422
+ value: countAt(share.value, most),
423
+ interval: { low: countAt(share.interval.high, most), high: countAt(share.interval.low, most) },
424
+ });
425
+
426
+ /**
427
+ * This function gives the scale rule of a service at a load: the lowest count of instances that
428
+ * holds each limit, with an interval. It also gives the limit that binds first, and the load of the
429
+ * next step: the highest load of that count, from `countReach`.
430
+ *
431
+ * The search goes along the share of the demand on one instance: the share of `n` instances is
432
+ * `1 / n`. It starts at the share of `most` instances and goes up to the share of one instance. The
433
+ * count of a row comes from the first share where one limit of the row breaks. Thus the count holds
434
+ * each limit, and each larger count also holds each limit. A level in `options.whole` does not divide.
435
+ *
436
+ * Each row of the doubt of the laws has its own search, and the rows of the limits pair, as in
437
+ * `countReach`. The interval of the count is the share `level` of the counts of the replicates, made
438
+ * wider to hold the count of the estimate. The field `binds` of each limit is the share of the
439
+ * replicates where that limit sets the count.
440
+ *
441
+ * The function gives each problem of `countReach` that is not about a count.
442
+ */
443
+ export const scaleRule = (model: ScaleModel, demand: Demand, options: ScaleOptions = {}): Result<ScaleRule, ScaleProblem> => {
444
+ const setup = setupOf(model, demand, options);
445
+ if (setup.tag === "err") return setup;
446
+ const { most, whole } = setup.value;
447
+ const grid = searchGrid(1 / most, 1, setup.value.steps, true, "The share of one instance");
448
+ if (grid.tag === "err") return grid;
449
+ const demandAt: DemandAt = (share) => {
450
+ const portion = portionOf(setup.value.demand, share, 1, whole);
451
+ return portion.tag === "ok" ? portion.value : undefined;
452
+ };
453
+ const breaks = breaksOf(setup.value, grid.value, demandAt);
454
+ if (breaks.tag === "err") return breaks;
455
+ return ruleFrom(
456
+ setup.value,
457
+ breaks.value,
458
+ (each, share) => outsideAt(setup.value, each, demandAt, share),
459
+ (count) => reachOf(setup.value, count),
460
+ );
461
+ };
462
+
463
+ /** This function gives the scale rule from the breaks of each limit along the share of one instance, and the reach of a count. */
464
+ const ruleFrom = (
465
+ setup: Setup,
466
+ breaks: readonly LimitBreaks[],
467
+ outside: OutsideAt,
468
+ reachAt: (count: number) => Result<CountReach, ScaleProblem>,
469
+ ): Result<ScaleRule, ScaleProblem> => {
470
+ const { most, level } = setup;
471
+ const summary = summaryOf(breaks, setup.rows);
472
+ const shareOfCount = (count: number | null): number => 1 / (count ?? most);
473
+ const limits = summary.order.map((index): LimitCount => {
474
+ const each = setup.limits[index] as LimitSetup;
475
+ const found = breaks[index] as LimitBreaks;
476
+ const count = countsOf(openValueOf(found.rows, level, 1), most);
477
+ return {
478
+ limit: each.limit.id,
479
+ measure: each.limit.measure,
480
+ count,
481
+ binds: summary.binds[index] as number,
482
+ edge: found.edge,
483
+ extrapolated: outside(each, shareOfCount(count.value)),
484
+ };
485
+ });
486
+ const count = countsOf(openValueOf(summary.rows, level, 1), most);
487
+ let next: CountReach | null = null;
488
+ if (count.value !== null) {
489
+ const reach = reachAt(count.value);
490
+ if (reach.tag === "err") return reach;
491
+ next = reach.value;
492
+ }
493
+ return ok({
494
+ level,
495
+ most,
496
+ count,
497
+ binding: summary.binding === null ? null : (setup.limits[summary.binding] as LimitSetup).limit.id,
498
+ extrapolated: setup.limits.some((each) => outside(each, shareOfCount(count.value))),
499
+ limits,
500
+ next,
501
+ });
502
+ };
503
+
504
+ /** A limit ladder holds, for each row of one limit, the first load on one instance where the row breaks the limit. */
505
+ export interface LimitLadder {
506
+ readonly limit: string;
507
+ readonly measure: string;
508
+ /**
509
+ * Each value is the first load on one instance, as a factor of the demand, where one row breaks the limit. Row 0 is the
510
+ * estimate. A load where the composition has no value also breaks the row. Infinity tells that the row holds on all of the search.
511
+ */
512
+ readonly rows: readonly number[];
513
+ /** This flag tells that the edge of the composition sets the load of row 0. */
514
+ readonly edge: boolean;
515
+ }
516
+
517
+ /**
518
+ * A scale ladder is the scale rule of a service at each load of a range, from one search. With no level in `whole`, the
519
+ * demand on one of `n` instances at `f` times the load is the demand at `f / n` times the load. Thus each row of each
520
+ * limit breaks at one load on one instance, and a count needs only arithmetic.
521
+ *
522
+ * The function `ruleAt(f)` gives the value of `scaleRule` at the demand `scaleDemand(demand, f)`. The function
523
+ * `reachAt(n, f)` gives the value of `countReach` for `n` instances at the same demand. Each of them reads the
524
+ * compositions only for the flags `extrapolated`, one value for each limit.
525
+ */
526
+ export interface ScaleLadder {
527
+ readonly level: number;
528
+ readonly most: number;
529
+ /** This range holds the factors of the demand that the ladder answers. */
530
+ readonly range: Range;
531
+ /** This range holds the loads on one instance of the search, as factors of the demand. */
532
+ readonly search: Range;
533
+ /** The limits are in the order of the model. */
534
+ readonly limits: readonly LimitLadder[];
535
+ readonly ruleAt: (factor: number) => Result<ScaleRule, ScaleProblem>;
536
+ readonly reachAt: (count: number, factor: number) => Result<CountReach, ScaleProblem>;
537
+ }
538
+
539
+ /**
540
+ * This function changes the loads on one instance of a ladder to the loads of a search from `low` to `high`. A load
541
+ * past `high` holds on all of that search, and a load before `low` breaks at its start, as in `rowOf`.
542
+ */
543
+ const loadsIn = (rows: readonly number[], times: number, low: number, high: number): number[] =>
544
+ rows.map((load) => {
545
+ const found = load * times;
546
+ return found > high ? Infinity : Math.max(found, low);
547
+ });
548
+
549
+ /**
550
+ * This function gives the scale ladder of a service over the factors of the demand from `range.low` to `range.high`.
551
+ * The search covers the loads on one instance that `scaleRule` and `countReach` read at each factor of the range: from
552
+ * `range.low / most` to `range.high * most`. Its grid has the density of the grid of `scaleRule`, up to the largest
553
+ * count of steps.
554
+ *
555
+ * The values of the ladder agree with `scaleRule` and `countReach` to the precision of their bisections. They can differ
556
+ * when two crossings are in one step of a grid, because the grids are different.
557
+ *
558
+ * The function gives each problem of `scaleRule`. It also gives a problem for a level in `options.whole`. With such a level,
559
+ * the demand on one instance does not depend only on the load over the count. It gives a problem for a range that does not
560
+ * go from a number above 0 to a larger finite number.
561
+ */
562
+ export const scaleLadder = (model: ScaleModel, demand: Demand, range: Range, options: ScaleOptions = {}): Result<ScaleLadder, ScaleProblem> => {
563
+ const found = setupOf(model, demand, options);
564
+ if (found.tag === "err") return found;
565
+ const setup = found.value;
566
+ if (setup.whole.length > 0) {
567
+ return err(problem("variable", "whole", "A ladder needs a demand that divides between the instances. Use scaleRule for a level in whole."));
568
+ }
569
+ if (!(range.low > 0 && Number.isFinite(range.high) && range.low < range.high)) {
570
+ return err(problem("factor", "range", `The range goes from ${range.low} to ${range.high}. It must go from a number above 0 to a larger finite number.`));
571
+ }
572
+ const { most, level } = setup;
573
+ const search: Range = { low: range.low / most, high: range.high * most };
574
+ // The grid of scaleRule has `steps` steps over the factor `most`. This grid keeps that count of steps for each factor.
575
+ const steps = Math.min(MAX_STEPS, Math.max(setup.steps, Math.ceil((setup.steps * Math.log(search.high / search.low)) / Math.log(most))));
576
+ const grid = searchGrid(search.low, search.high, steps, true, "The load on one instance");
577
+ if (grid.tag === "err") return grid;
578
+ const demandAt: DemandAt = (load) => {
579
+ const portion = portionOf(setup.demand, load, load, []);
580
+ return portion.tag === "ok" ? portion.value : undefined;
581
+ };
582
+ const breaks = breaksOf(setup, grid.value, demandAt);
583
+ if (breaks.tag === "err") return breaks;
584
+ const ladder = breaks.value;
585
+ const outsideOn = (each: LimitSetup, load: number): boolean => outsideAt(setup, each, demandAt, load);
586
+ const inRange = (factor: number): Result<number, ScaleProblem> =>
587
+ factor >= range.low && factor <= range.high
588
+ ? ok(factor)
589
+ : err(problem("factor", "factor", `The factor ${factor} is outside the range of the ladder, from ${range.low} to ${range.high}.`));
590
+ /** This function gives the breaks of each limit along the factor of a search from `low` to `high`. The load on one instance is `times` the factor. */
591
+ const breaksIn = (times: number, low: number, high: number): LimitBreaks[] =>
592
+ ladder.map((each) => {
593
+ const rows = loadsIn(each.rows, 1 / times, low, high);
594
+ return { rows, edge: each.edge && Number.isFinite(rows[0] as number) };
595
+ });
596
+ const reachIn = (count: number, factor: number): CountReach =>
597
+ reachFrom(setup, count, breaksIn(factor / count, 1 / most, most), (each, at) => outsideOn(each, (factor * at) / count));
598
+ const reachAt = (count: number, factor: number): Result<CountReach, ScaleProblem> => {
599
+ if (!Number.isSafeInteger(count) || count < 1) {
600
+ return err(problem("factor", "count", `The count of instances ${count} is not a whole number of 1 or more.`));
601
+ }
602
+ const at = inRange(factor);
603
+ return at.tag === "err" ? at : ok(reachIn(count, factor));
604
+ };
605
+ const ruleAt = (factor: number): Result<ScaleRule, ScaleProblem> => {
606
+ const at = inRange(factor);
607
+ if (at.tag === "err") return at;
608
+ return ruleFrom(
609
+ setup,
610
+ breaksIn(factor, 1 / most, 1),
611
+ (each, share) => outsideOn(each, factor * share),
612
+ (count) => ok(reachIn(count, factor)),
613
+ );
614
+ };
615
+ const limits = setup.limits.map((each, index): LimitLadder => ({ limit: each.limit.id, measure: each.limit.measure, ...(ladder[index] as LimitBreaks) }));
616
+ return ok({ level, most, range, search, limits, ruleAt, reachAt });
617
+ };