@mark1russell7/guidebook-library 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.
@@ -0,0 +1,174 @@
1
+ // The plan of the copies of one level as a query of `@mark1russell7/stack-placement`.
2
+ // Each slot is one copy. Each candidate is one medium offer at one place. Each place and each kind of medium is a shared
3
+ // fragment, so two copies at one place share the loss of that place. The chance comes from `worksChance` of `stack-risk`.
4
+
5
+ import type { Candidate, ChanceReading, PlacementLayer, PlacementPlan, Shared } from "@mark1russell7/stack-placement";
6
+ import { PLACEMENT_SCHEMA, planPlacement } from "@mark1russell7/stack-placement";
7
+ import { RISK_SCHEMA, worksChance } from "@mark1russell7/stack-risk";
8
+ import type { RiskLayer } from "@mark1russell7/stack-risk";
9
+ import { riskAddOn } from "@mark1russell7/stack-risk/add-on";
10
+ import type { Part, Stack } from "@mark1russell7/system-stack";
11
+ import { readLayer } from "@mark1russell7/system-stack";
12
+ import type { CopyRule, MediumKind } from "./records.ts";
13
+
14
+ /** A medium that a copy can go on, with its price and its rate of loss. The offers are input data of the caller. */
15
+ export interface MediumOffer {
16
+ readonly id: string;
17
+ readonly kind: MediumKind;
18
+ /** The capacity of one medium in bytes. */
19
+ readonly bytes: number;
20
+ /** The price of one medium, in the currency of the plan. */
21
+ readonly price: number;
22
+ /** The years of use of one medium. The cost of a month is `price / (lifeYears × 12)`. */
23
+ readonly lifeYears: number;
24
+ /** The chance from 0 to 1 that a copy on the medium cannot be read after one year, for example an annual failure rate. */
25
+ readonly yearlyLoss: number;
26
+ /** The source of `yearlyLoss`. */
27
+ readonly source: string;
28
+ }
29
+
30
+ /** A place that holds copies, with its rate of loss. The places are input data of the caller. */
31
+ export interface CopyPlace {
32
+ readonly id: string;
33
+ /** The chance from 0 to 1 that the place loses all its copies in one year, for example by fire, flood or theft. */
34
+ readonly yearlyLoss: number;
35
+ /** The source of `yearlyLoss`. */
36
+ readonly source: string;
37
+ /** The cost of a month of the place, for example the rent of a box. The default is 0. */
38
+ readonly monthly?: number;
39
+ }
40
+
41
+ /** A shared cause of loss of all the copies on one kind of medium, for example a format that no reader can read. */
42
+ export interface KindLoss {
43
+ readonly kind: MediumKind;
44
+ readonly yearlyLoss: number;
45
+ readonly source: string;
46
+ }
47
+
48
+ /** The input of `copiesLayer`. */
49
+ export interface CopiesInput {
50
+ /** The copy rule of the level. The slots, the counts of kinds and places, and the period of the chance come from it. */
51
+ readonly rule: CopyRule;
52
+ /** The bytes of the bundles of the level, for example from `bytesOf`. An offer with less capacity is not a candidate. */
53
+ readonly bytes: number;
54
+ readonly offers: readonly MediumOffer[];
55
+ readonly places: readonly CopyPlace[];
56
+ /** The shared losses of the kinds. A kind with no record has no shared loss. */
57
+ readonly kindLosses?: readonly KindLoss[];
58
+ /** The count of optional slots after the `rule.copies` slots. The default is 1. */
59
+ readonly extra?: number;
60
+ /** The currency of the prices. */
61
+ readonly currency: string;
62
+ /** The largest cost of a month, and the smallest chance. */
63
+ readonly limits?: { readonly cost?: number; readonly chance?: number };
64
+ }
65
+
66
+ /** The layer and the base stack of a plan of copies. */
67
+ export interface CopiesQuery {
68
+ readonly layer: PlacementLayer;
69
+ readonly base: Stack;
70
+ }
71
+
72
+ /** The part of a placed stack that works when one copy of the level or more can be read. */
73
+ export const libraryPartOf = (level: string): string => `library:${level}`;
74
+
75
+ const placePartOf = (place: string): string => `place:${place}`;
76
+ const kindPartOf = (kind: MediumKind): string => `medium:${kind}`;
77
+
78
+ /** This function gives the chance that a thing with a yearly loss still works after `days` days. */
79
+ export function keepChance(yearlyLoss: number, days: number): number {
80
+ if (!(yearlyLoss >= 0 && yearlyLoss <= 1) || !(days >= 0)) throw new RangeError(`keepChance: the loss ${yearlyLoss} or the days ${days} is out of range.`);
81
+ return (1 - yearlyLoss) ** (days / 365);
82
+ }
83
+
84
+ const fragment = (part: Part, works: number, source: string): Stack => ({
85
+ schema: "stack/1",
86
+ parts: [part],
87
+ layers: { [RISK_SCHEMA]: { schema: RISK_SCHEMA, goals: [], chances: [{ part: part.id, works, source }] } satisfies RiskLayer },
88
+ });
89
+
90
+ /**
91
+ * This function gives the placement layer and the base stack of the copies of one level.
92
+ * The chance of a choice is the chance that one copy or more can be read after one period `rule.everyDays`. A check then repairs each loss.
93
+ * It throws a `RangeError` when no offer can hold the bytes, or when the input has no place.
94
+ */
95
+ export function copiesLayer(input: CopiesInput): CopiesQuery {
96
+ const { rule } = input;
97
+ const days = rule.everyDays;
98
+ const offers = input.offers.filter((offer) => offer.bytes >= input.bytes);
99
+ if (offers.length === 0) throw new RangeError(`copiesLayer: no offer holds the ${input.bytes} bytes of the level "${rule.level}".`);
100
+ if (input.places.length === 0) throw new RangeError(`copiesLayer: the level "${rule.level}" has no place.`);
101
+ const count = Math.max(1, rule.copies) + (input.extra ?? 1);
102
+ const slotIds = Array.from({ length: count }, (_, i) => `copy-${i + 1}`);
103
+ const kinds = [...new Set(offers.map((offer) => offer.kind))];
104
+ const losses = new Map((input.kindLosses ?? []).map((loss) => [loss.kind, loss]));
105
+ const shared: Shared[] = [
106
+ ...input.places.map((place) => ({
107
+ id: placePartOf(place.id),
108
+ stack: fragment({ id: placePartOf(place.id), kind: "place", name: place.id }, keepChance(place.yearlyLoss, days), place.source),
109
+ cost: place.monthly ?? 0,
110
+ })),
111
+ ...kinds.map((kind) => {
112
+ const loss = losses.get(kind);
113
+ const works = loss === undefined ? 1 : keepChance(loss.yearlyLoss, days);
114
+ return { id: kindPartOf(kind), stack: fragment({ id: kindPartOf(kind), kind: "medium", name: kind }, works, loss?.source ?? "No shared loss of the kind is known.") };
115
+ }),
116
+ ];
117
+ const candidatesOf = (slot: string): Candidate[] =>
118
+ offers.flatMap((offer) =>
119
+ input.places.map((place) => ({
120
+ key: `${offer.id}@${place.id}`,
121
+ cost: offer.price / (offer.lifeYears * 12),
122
+ uses: [placePartOf(place.id), kindPartOf(offer.kind)],
123
+ source: offer.id,
124
+ stack: fragment({ id: slot, kind: "copy", needs: [placePartOf(place.id), kindPartOf(offer.kind)] }, keepChance(offer.yearlyLoss, days), offer.source),
125
+ })),
126
+ );
127
+ const part = libraryPartOf(rule.level);
128
+ const layer: PlacementLayer = {
129
+ schema: PLACEMENT_SCHEMA,
130
+ part,
131
+ currency: input.currency,
132
+ slots: slotIds.map((id, i) => ({ id, candidates: candidatesOf(id), optional: i >= rule.copies })),
133
+ shared,
134
+ ...(input.limits === undefined ? {} : { limits: input.limits }),
135
+ };
136
+ const base: Stack = {
137
+ schema: "stack/1",
138
+ parts: [{ id: part, kind: "function", needs: [{ any: slotIds }] }],
139
+ layers: { [RISK_SCHEMA]: { schema: RISK_SCHEMA, goals: [], chances: [{ part, works: 1, source: "The level works when one copy or more can be read." }] } satisfies RiskLayer },
140
+ };
141
+ return { layer, base };
142
+ }
143
+
144
+ /** The options of `planCopies`. */
145
+ export interface PlanCopiesOptions {
146
+ /** The date of the plan, for the risk add-on. */
147
+ readonly today: string;
148
+ /** The count of evaluations of a seeded search of a large space. */
149
+ readonly evaluations?: number;
150
+ readonly seed?: number | string;
151
+ }
152
+
153
+ /**
154
+ * This function gives the front of the plans of copies. No other plan is better on the cost of a month and on the chance.
155
+ * A plan with fewer places or fewer kinds than the rule gets the break `measure`, so it is not on the front.
156
+ */
157
+ export function planCopies(query: CopiesQuery, rule: CopyRule, options: PlanCopiesOptions): PlacementPlan {
158
+ const risk = riskAddOn({ today: options.today });
159
+ const chance = (stack: Stack, part: string): ChanceReading => {
160
+ const places = stack.parts.filter((p) => p.kind === "place").length;
161
+ const kinds = stack.parts.filter((p) => p.kind === "medium").length;
162
+ if (places < rule.places || kinds < rule.kinds) throw new RangeError(`The plan has ${places} places and ${kinds} kinds. The rule needs ${rule.places} and ${rule.kinds}.`);
163
+ const read = readLayer(stack, risk);
164
+ if (read !== undefined && !read.ok) throw new RangeError(read.errors.join(" "));
165
+ const works = worksChance(read?.layer ?? { schema: RISK_SCHEMA, goals: [] }, stack, part);
166
+ return works.kind === "exact" ? { value: works.value, importance: works.importance, assumed: works.assumed } : { value: Number.NaN };
167
+ };
168
+ return planPlacement(query.layer, query.base, {
169
+ joiners: [risk],
170
+ chance,
171
+ ...(options.evaluations === undefined ? {} : { evaluations: options.evaluations }),
172
+ ...(options.seed === undefined ? {} : { seed: options.seed }),
173
+ });
174
+ }
package/src/records.ts ADDED
@@ -0,0 +1,61 @@
1
+ // The records of the library add-on: an offline bundle, a copy of a bundle on one medium, and the copy rule of a level.
2
+
3
+ import type { IsoDate, License, SourceId } from "@mark1russell7/guidebook";
4
+
5
+ /** The kinds of media that hold a copy. */
6
+ export const MEDIUM_KINDS = ["flash", "ssd", "hdd", "optical", "paper"] as const;
7
+
8
+ /** A kind of medium. */
9
+ export type MediumKind = (typeof MEDIUM_KINDS)[number];
10
+
11
+ /**
12
+ * An offline bundle: one file that holds a full source, for example a Kiwix ZIM file.
13
+ * The `level` names a rule of the caller, so the add-on names no topic.
14
+ */
15
+ export interface Bundle {
16
+ readonly id: string;
17
+ readonly title: string;
18
+ /** The size of the file in bytes. */
19
+ readonly bytes: number;
20
+ readonly license: License;
21
+ /** The level of the most important content of the bundle. A copy rule of the caller gives the copies of each level. */
22
+ readonly level: string;
23
+ /** The `id` of the source of the bundle in the sources of the core. */
24
+ readonly source: SourceId;
25
+ /** The release of the file, for example `2026-10`. */
26
+ readonly version?: string;
27
+ /** The SHA-256 of the file, as 64 lower-case hexadecimal digits. */
28
+ readonly sha256?: string;
29
+ /** The address of the file, with `https:` or `http:`. */
30
+ readonly url?: string;
31
+ }
32
+
33
+ /** A copy of a bundle on one medium. Where each copy goes is a query of the caller, for example of `stack-placement`. */
34
+ export interface Copy {
35
+ /** The `id` of the bundle. */
36
+ readonly bundle: string;
37
+ /** The `id` of the medium, for example the label on a drive. */
38
+ readonly medium: string;
39
+ readonly kind: MediumKind;
40
+ /** The `id` of the place of the medium. The places are input data of the caller. */
41
+ readonly place: string;
42
+ /** The date of the last read of the full copy against its hash. */
43
+ readonly checked: IsoDate;
44
+ /** The release of the bundle on the medium. */
45
+ readonly version?: string;
46
+ /** The SHA-256 that the last check read from the copy. */
47
+ readonly sha256?: string;
48
+ }
49
+
50
+ /** The copies that a level needs. */
51
+ export interface CopyRule {
52
+ readonly level: string;
53
+ /** The smallest count of good copies. */
54
+ readonly copies: number;
55
+ /** The smallest count of different kinds of media among the good copies. */
56
+ readonly kinds: number;
57
+ /** The smallest count of different places among the good copies. */
58
+ readonly places: number;
59
+ /** A copy is good for this number of days after its last check. */
60
+ readonly everyDays: number;
61
+ }