@drupflare/spool 0.2.0 → 0.3.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.
Files changed (62) hide show
  1. package/README.md +256 -22
  2. package/dist/cdn/client.js +1 -1
  3. package/dist/cdn/manifest.json +7 -7
  4. package/dist/cdn/spool-sw.js +1 -1
  5. package/dist/client/activity.d.ts +37 -0
  6. package/dist/client/activity.js +114 -0
  7. package/dist/client/entry.js +2 -1
  8. package/dist/client/index.d.ts +1 -0
  9. package/dist/client/index.js +1 -0
  10. package/dist/media/embeds.d.ts +3 -2
  11. package/dist/media/embeds.js +16 -1
  12. package/dist/protocol/envelope.d.ts +2 -0
  13. package/dist/protocol/envelope.js +12 -2
  14. package/dist/protocol/errors.d.ts +1 -1
  15. package/dist/protocol/hash.d.ts +2 -0
  16. package/dist/protocol/hash.js +8 -0
  17. package/dist/protocol/index.d.ts +4 -0
  18. package/dist/protocol/index.js +4 -0
  19. package/dist/protocol/inline.d.ts +14 -0
  20. package/dist/protocol/inline.js +43 -0
  21. package/dist/protocol/navigation.d.ts +81 -0
  22. package/dist/protocol/navigation.js +249 -0
  23. package/dist/protocol/normalise.d.ts +4 -3
  24. package/dist/protocol/normalise.js +6 -4
  25. package/dist/protocol/provision.d.ts +6 -1
  26. package/dist/protocol/provision.js +15 -5
  27. package/dist/protocol/query.d.ts +80 -0
  28. package/dist/protocol/query.js +153 -0
  29. package/dist/protocol/route.d.ts +80 -4
  30. package/dist/protocol/route.js +63 -0
  31. package/dist/proxy/bases.d.ts +53 -0
  32. package/dist/proxy/bases.js +76 -0
  33. package/dist/proxy/index.d.ts +1 -0
  34. package/dist/proxy/index.js +1 -0
  35. package/dist/proxy/proxy.js +8 -2
  36. package/dist/report/capacity.d.ts +59 -0
  37. package/dist/report/capacity.js +76 -0
  38. package/dist/report/channels.d.ts +60 -0
  39. package/dist/report/channels.js +65 -0
  40. package/dist/report/index.d.ts +3 -0
  41. package/dist/report/index.js +3 -0
  42. package/dist/report/institution.d.ts +97 -0
  43. package/dist/report/institution.js +79 -0
  44. package/dist/report/ledger.d.ts +28 -0
  45. package/dist/report/ledger.js +30 -0
  46. package/dist/report/measurement.d.ts +1 -1
  47. package/dist/report/measurement.js +4 -1
  48. package/dist/report/traffic.d.ts +11 -2
  49. package/dist/report/traffic.js +13 -3
  50. package/dist/server/embedded.d.ts +3 -3
  51. package/dist/server/embedded.js +3 -3
  52. package/dist/server/index.d.ts +1 -0
  53. package/dist/server/index.js +1 -0
  54. package/dist/server/spool.d.ts +20 -0
  55. package/dist/server/spool.js +62 -9
  56. package/dist/sw/render.d.ts +3 -1
  57. package/dist/sw/render.js +14 -1
  58. package/dist/sw/replica.d.ts +2 -0
  59. package/dist/sw/replica.js +6 -0
  60. package/dist/sw/router.js +2 -2
  61. package/dist/sw/runtime.js +104 -9
  62. package/package.json +4 -2
@@ -0,0 +1,59 @@
1
+ import type { WorkSample } from './traffic.js';
2
+ /**
3
+ * What one node can do within the latency SLO, per resource. A resource is any name the trace uses,
4
+ * such as `busyMs` or `memoryMb`. `perNode.busyMs` is handler milliseconds a node can do per second
5
+ * within the SLO, for example 1000 times cores times a target utilisation, so callers pass busy time
6
+ * as a per-second rate.
7
+ */
8
+ export type NodeLimits = {
9
+ /** what one node serves per second within the SLO, per resource; must be positive */
10
+ perNode: Record<string, number>;
11
+ /** fewest nodes the fleet runs; default 1 */
12
+ floor?: number;
13
+ /** nodes kept above the peak need; default 0 */
14
+ spares?: number;
15
+ /** regions the fleet spans; default 1 */
16
+ regions?: number;
17
+ /** nodes each region must run; default 1 */
18
+ minPerRegion?: number;
19
+ };
20
+ /** demand in one interval: what the origin did, and what spool removed of it, per resource */
21
+ export type IntervalDemand = {
22
+ /** when the interval starts, on the clock of the samples it came from */
23
+ start: number;
24
+ /** length of the interval in seconds */
25
+ seconds: number;
26
+ /** the origin's need per resource, per second */
27
+ demand: Record<string, number>;
28
+ /** the part of demand spool removed, per resource and per second; missing means none */
29
+ avoided?: Record<string, number>;
30
+ };
31
+ /** `bindingBefore` and `bindingAfter` name the resource that set the worst interval's need */
32
+ export type CapacityPlan = {
33
+ /** nodes the worst interval needs without spool */
34
+ before: number;
35
+ /** nodes the worst interval needs once avoided work is removed */
36
+ after: number;
37
+ /** nodes spool makes unneeded: before minus after */
38
+ retirable: number;
39
+ /** resource that sets the need before spool; null when no interval needs a node */
40
+ bindingBefore: string | null;
41
+ /** resource that sets the need after spool; null when no interval needs a node */
42
+ bindingAfter: string | null;
43
+ /** number of intervals in the plan */
44
+ intervals: number;
45
+ };
46
+ /** nodes one interval's demand needs, and the resource with the largest need */
47
+ export declare function nodesNeeded(demand: Record<string, number>, limits: NodeLimits): {
48
+ /** nodes needed: peak need plus spares, not below the floor or the regional minimum */
49
+ nodes: number;
50
+ /** resource with the largest need, first by name on a tie; null when none needs a node */
51
+ binding: string | null;
52
+ };
53
+ /** the fleet the intervals need before and after spool removes its avoided work */
54
+ export declare function capacityPlan(intervals: readonly IntervalDemand[], limits: NodeLimits): CapacityPlan;
55
+ /**
56
+ * Per-second demand for each sample, with `busyMs` summed over its routes. `avoidedBusyMs` holds the
57
+ * handler milliseconds spool removed in each interval, in the order of `samples` sorted by start.
58
+ */
59
+ export declare function intervalsFromWork(samples: readonly WorkSample[], avoidedBusyMs: readonly number[]): IntervalDemand[];
@@ -0,0 +1,76 @@
1
+ /** nodes one interval's demand needs, and the resource with the largest need */
2
+ export function nodesNeeded(demand, limits) {
3
+ for (const [name, per] of Object.entries(limits.perNode)) {
4
+ if (!Number.isFinite(per) || per <= 0) {
5
+ throw new RangeError(`perNode.${name} must be a positive finite number`);
6
+ }
7
+ }
8
+ for (const [name, need] of Object.entries(demand)) {
9
+ if (!Number.isFinite(need) || need < 0) {
10
+ throw new RangeError(`demand.${name} must be a finite, non-negative number`);
11
+ }
12
+ }
13
+ let peak = 0;
14
+ let binding = null;
15
+ // sorted so a tie goes to the name that sorts first
16
+ const names = Object.entries(limits.perNode).sort(([a], [b]) => (a < b ? -1 : 1));
17
+ for (const [name, per] of names) {
18
+ const need = Math.ceil((demand[name] ?? 0) / per);
19
+ if (need > peak) {
20
+ peak = need;
21
+ binding = name;
22
+ }
23
+ }
24
+ const nodes = Math.max(peak + (limits.spares ?? 0), limits.floor ?? 1, (limits.regions ?? 1) * (limits.minPerRegion ?? 1));
25
+ return { nodes, binding };
26
+ }
27
+ /** the interval that needs the most nodes, first on a tie; an empty list needs the base fleet */
28
+ function worstOf(demands, limits) {
29
+ let worst = null;
30
+ for (const demand of demands) {
31
+ const got = nodesNeeded(demand, limits);
32
+ if (worst === null || got.nodes > worst.nodes)
33
+ worst = got;
34
+ }
35
+ return worst ?? nodesNeeded({}, limits);
36
+ }
37
+ /** demand after avoided work, clamped at zero; a resource with no avoided keeps its need */
38
+ function afterAvoided({ demand, avoided = {} }) {
39
+ const out = {};
40
+ for (const [name, need] of Object.entries(demand)) {
41
+ out[name] = Math.max(0, need - (avoided[name] ?? 0));
42
+ }
43
+ return out;
44
+ }
45
+ /** the fleet the intervals need before and after spool removes its avoided work */
46
+ export function capacityPlan(intervals, limits) {
47
+ const before = worstOf(intervals.map((interval) => interval.demand), limits);
48
+ const after = worstOf(intervals.map(afterAvoided), limits);
49
+ return {
50
+ before: before.nodes,
51
+ after: after.nodes,
52
+ retirable: before.nodes - after.nodes,
53
+ bindingBefore: before.binding,
54
+ bindingAfter: after.binding,
55
+ intervals: intervals.length
56
+ };
57
+ }
58
+ /**
59
+ * Per-second demand for each sample, with `busyMs` summed over its routes. `avoidedBusyMs` holds the
60
+ * handler milliseconds spool removed in each interval, in the order of `samples` sorted by start.
61
+ */
62
+ export function intervalsFromWork(samples, avoidedBusyMs) {
63
+ if (avoidedBusyMs.length !== samples.length) {
64
+ throw new RangeError('avoidedBusyMs needs one entry per sample');
65
+ }
66
+ const ordered = [...samples].sort((a, b) => a.start - b.start);
67
+ return ordered.map((sample, i) => {
68
+ const busy = Object.values(sample.busyMs).reduce((total, ms) => total + ms, 0);
69
+ return {
70
+ start: sample.start,
71
+ seconds: sample.seconds,
72
+ demand: { busyMs: busy / sample.seconds },
73
+ avoided: { busyMs: avoidedBusyMs[i] / sample.seconds }
74
+ };
75
+ });
76
+ }
@@ -0,0 +1,60 @@
1
+ import type { Layer } from './inputs.js';
2
+ import type { InstitutionReport } from './institution.js';
3
+ /** a figure with the layer it is at and the source it came from */
4
+ export type Labelled<T> = {
5
+ /** the figure, in the shape T gives it */
6
+ value: T;
7
+ /** L0 published, L1 measured here, L2 derived, L3 scenario */
8
+ layer: Layer;
9
+ /** where the figure came from, so a reader can check it */
10
+ source: string;
11
+ };
12
+ /** what spool kept off the origin and the network, per measure; null where nothing was measured */
13
+ export type AvoidedDemand = {
14
+ /** bytes not sent over the network */
15
+ transferredBytes: number | null;
16
+ /** requests not made */
17
+ requests: number | null;
18
+ /** origin CPU milliseconds not spent */
19
+ serverCpuMs: number | null;
20
+ /** browser CPU milliseconds not spent */
21
+ browserCpuMs: number | null;
22
+ /** data centre work milliseconds not done */
23
+ dataCentreWorkMs: number | null;
24
+ /** nodes the peak no longer needs */
25
+ peakNodes: number | null;
26
+ };
27
+ /**
28
+ * The four channels. They are reported side by side and never summed, so there is no total across
29
+ * them.
30
+ */
31
+ export type Channels = {
32
+ /** energy a meter read, in joules; null when nothing was read */
33
+ metered: Labelled<{
34
+ /** joules the meter read */
35
+ joules: number;
36
+ }> | null;
37
+ /** energy attributed to the workload; null when none is attributed */
38
+ attributional: Labelled<{
39
+ /** joules attributed to the workload */
40
+ joules: number;
41
+ }> | null;
42
+ /** the institution report's capacity figures; null without a report */
43
+ capacity: Labelled<InstitutionReport> | null;
44
+ /** what spool kept off the origin and the network; null when not measured */
45
+ avoided: Labelled<AvoidedDemand> | null;
46
+ };
47
+ export type ChannelRow = {
48
+ /** the channel the number belongs to */
49
+ channel: keyof Channels;
50
+ /** what the number measures, as a short label */
51
+ measure: string;
52
+ /** the number, in unit */
53
+ value: number;
54
+ /** unit of value, such as J, nodes or MWh */
55
+ unit: string;
56
+ /** the layer the number is at */
57
+ layer: Layer;
58
+ };
59
+ /** one row per present number, in channel order; rows from different channels are never combined */
60
+ export declare function channelRows(channels: Channels): ChannelRow[];
@@ -0,0 +1,65 @@
1
+ /** one row per present number, in channel order; rows from different channels are never combined */
2
+ export function channelRows(channels) {
3
+ const rows = [];
4
+ for (const channel of ['metered', 'attributional']) {
5
+ const labelled = channels[channel];
6
+ if (labelled) {
7
+ rows.push({
8
+ channel,
9
+ measure: 'energy',
10
+ value: labelled.value.joules,
11
+ unit: 'J',
12
+ layer: labelled.layer
13
+ });
14
+ }
15
+ }
16
+ const capacity = channels.capacity;
17
+ if (capacity) {
18
+ const { potential, financial, physical } = capacity.value;
19
+ if (potential) {
20
+ rows.push({
21
+ channel: 'capacity',
22
+ measure: 'potential retirable nodes',
23
+ value: potential.plan.retirable,
24
+ unit: 'nodes',
25
+ layer: potential.layer
26
+ });
27
+ }
28
+ if (financial) {
29
+ rows.push({
30
+ channel: 'capacity',
31
+ measure: 'financial saving',
32
+ value: financial.saving,
33
+ unit: financial.currency,
34
+ layer: financial.layer
35
+ });
36
+ }
37
+ if (physical) {
38
+ rows.push({
39
+ channel: 'capacity',
40
+ measure: 'physical energy',
41
+ value: physical.mwh,
42
+ unit: 'MWh',
43
+ layer: physical.layer
44
+ });
45
+ }
46
+ }
47
+ const avoided = channels.avoided;
48
+ if (avoided) {
49
+ const fields = [
50
+ ['transferredBytes', 'B'],
51
+ ['requests', 'requests'],
52
+ ['serverCpuMs', 'ms'],
53
+ ['browserCpuMs', 'ms'],
54
+ ['dataCentreWorkMs', 'ms'],
55
+ ['peakNodes', 'nodes']
56
+ ];
57
+ for (const [measure, unit] of fields) {
58
+ const value = avoided.value[measure];
59
+ if (value !== null) {
60
+ rows.push({ channel: 'avoided', measure, value, unit, layer: avoided.layer });
61
+ }
62
+ }
63
+ }
64
+ return rows;
65
+ }
@@ -1,6 +1,9 @@
1
+ export * from './capacity.js';
2
+ export * from './channels.js';
1
3
  export * from './derive.js';
2
4
  export * from './economics.js';
3
5
  export * from './inputs.js';
6
+ export * from './institution.js';
4
7
  export * from './ledger.js';
5
8
  export * from './measurement.js';
6
9
  export * from './model.js';
@@ -1,6 +1,9 @@
1
+ export * from './capacity.js';
2
+ export * from './channels.js';
1
3
  export * from './derive.js';
2
4
  export * from './economics.js';
3
5
  export * from './inputs.js';
6
+ export * from './institution.js';
4
7
  export * from './ledger.js';
5
8
  export * from './measurement.js';
6
9
  export * from './model.js';
@@ -0,0 +1,97 @@
1
+ import type { CapacityPlan } from './capacity.js';
2
+ /**
3
+ * A server or instance the institution retired because spool made it unneeded. `watts` is the
4
+ * draw of one unit; without it an instance has no energy figure and is listed as unpriced.
5
+ */
6
+ export type RetirementEntry = {
7
+ /** the server or instance's identifier in the institution's records */
8
+ id: string;
9
+ /** whether a physical server or a cloud instance */
10
+ kind: 'server' | 'instance';
11
+ /** the date the unit was removed */
12
+ removedOn: string;
13
+ /** server-years the removal saves; must be a positive finite number */
14
+ years: number;
15
+ /** draw of one unit in watts; without it an instance is listed as unpriced */
16
+ watts?: number;
17
+ /** the source for the removal; required, must not be blank */
18
+ evidence: string;
19
+ };
20
+ /** a period's invoice totals before and after spool, in the invoice currency */
21
+ export type Invoices = {
22
+ /** the currency the totals are in, such as USD */
23
+ currency: string;
24
+ /** whether the totals cover a month or a year */
25
+ period: 'month' | 'year';
26
+ /** invoice total for the period before spool */
27
+ before: number;
28
+ /** invoice total for the same period with spool */
29
+ after: number;
30
+ };
31
+ /** a production measurement of the same workload before and after spool, over one stated period */
32
+ export type Observed = {
33
+ /** name of the measured quantity */
34
+ metric: string;
35
+ /** unit the before and after values are in */
36
+ unit: string;
37
+ /** the period both readings cover */
38
+ period: string;
39
+ /** metric value before spool, in unit; non-negative */
40
+ before: number;
41
+ /** metric value with spool, in unit; non-negative */
42
+ after: number;
43
+ };
44
+ export type InstitutionInputs = {
45
+ /** the capacity plan behind the potential channel */
46
+ plan?: CapacityPlan;
47
+ /** a production measurement of the same workload before and after spool */
48
+ observed?: Observed;
49
+ /** the layer the plan is reported at; a plan from a real trace and SLO is L2 */
50
+ planLayer?: 'L2' | 'L3';
51
+ /** invoice totals before and after spool */
52
+ invoices?: Invoices;
53
+ /** servers and instances the institution retired */
54
+ ledger?: readonly RetirementEntry[];
55
+ };
56
+ /** an observed change, then the three results of the capacity plan; none is added to another and any can be null or read zero */
57
+ export type InstitutionReport = {
58
+ /** what telemetry saw change, which is neither what the model says could change nor what was removed */
59
+ observed: (Observed & {
60
+ /** fractional drop from before to after; null when before is zero */
61
+ reduction: number | null;
62
+ /** L1, measured here */
63
+ layer: 'L1';
64
+ }) | null;
65
+ /** the capacity plan's node counts; null without a plan */
66
+ potential: {
67
+ /** the capacity plan the figures come from */
68
+ plan: CapacityPlan;
69
+ /** L2 when the plan comes from a real trace and SLO, else L3 */
70
+ layer: 'L2' | 'L3';
71
+ } | null;
72
+ /** the invoice saving; null without invoices */
73
+ financial: {
74
+ /** currency of the saving */
75
+ currency: string;
76
+ /** month or year, as the invoices stated */
77
+ period: 'month' | 'year';
78
+ /** invoice before minus after, in currency */
79
+ saving: number;
80
+ /** L1, measured here */
81
+ layer: 'L1';
82
+ } | null;
83
+ /** priced capacity saving from the ledger; null when no entry is priced */
84
+ physical: {
85
+ /** energy the retired servers drew, in MWh */
86
+ mwh: number;
87
+ /** server-years retired */
88
+ servers: number;
89
+ /** ids of retired entries with no energy figure */
90
+ unpriced: string[];
91
+ /** L2, derived from the ledger */
92
+ layer: 'L2';
93
+ } | null;
94
+ /** sentence stating the physical saving, or that none was shown */
95
+ statement: string;
96
+ };
97
+ export declare function institutionReport(inputs: InstitutionInputs): InstitutionReport;
@@ -0,0 +1,79 @@
1
+ import { serverYearMWh } from './model.js';
2
+ /** the priced part of the ledger, or only the unpriced ids when no entry has an energy figure */
3
+ function physicalFrom(ledger) {
4
+ if (ledger.length === 0)
5
+ return null;
6
+ let mwh = 0;
7
+ let servers = 0;
8
+ const unpriced = [];
9
+ for (const entry of ledger) {
10
+ if (!Number.isFinite(entry.years) || entry.years <= 0) {
11
+ throw new RangeError(`${entry.id}: years must be a positive finite number`);
12
+ }
13
+ if (entry.evidence.trim() === '') {
14
+ throw new RangeError(`${entry.id}: evidence is required`);
15
+ }
16
+ if (entry.kind === 'instance' && entry.watts === undefined) {
17
+ unpriced.push(entry.id);
18
+ continue;
19
+ }
20
+ mwh += entry.years * serverYearMWh(entry.watts);
21
+ servers += entry.years;
22
+ }
23
+ if (servers === 0)
24
+ return { unpriced };
25
+ return { mwh, servers, unpriced, layer: 'L2' };
26
+ }
27
+ function observedFrom(observed) {
28
+ if (!observed)
29
+ return null;
30
+ for (const n of [observed.before, observed.after]) {
31
+ if (!Number.isFinite(n) || n < 0) {
32
+ throw new RangeError(`${observed.metric}: before and after must be non-negative finite numbers`);
33
+ }
34
+ }
35
+ return {
36
+ ...observed,
37
+ reduction: observed.before > 0 ? (observed.before - observed.after) / observed.before : null,
38
+ layer: 'L1'
39
+ };
40
+ }
41
+ function financialFrom(invoices) {
42
+ if (!invoices)
43
+ return null;
44
+ return {
45
+ currency: invoices.currency,
46
+ period: invoices.period,
47
+ saving: invoices.before - invoices.after,
48
+ layer: 'L1'
49
+ };
50
+ }
51
+ export function institutionReport(inputs) {
52
+ const ledger = inputs.ledger ?? [];
53
+ const potential = inputs.plan
54
+ ? { plan: inputs.plan, layer: inputs.planLayer ?? 'L3' }
55
+ : null;
56
+ const found = physicalFrom(ledger);
57
+ if (!found || !('mwh' in found)) {
58
+ const unpriced = found?.unpriced ?? [];
59
+ return {
60
+ observed: observedFrom(inputs.observed),
61
+ potential,
62
+ financial: financialFrom(inputs.invoices),
63
+ physical: null,
64
+ statement: 'No physical capacity saving demonstrated.' +
65
+ (unpriced.length > 0 ? ` Unpriced entries: ${unpriced.join(', ')}.` : '')
66
+ };
67
+ }
68
+ const servers = Number(found.servers.toPrecision(3)).toString();
69
+ const priced = ledger.length - found.unpriced.length;
70
+ const years = servers === '1' ? 'server-year' : 'server-years';
71
+ const entries = priced === 1 ? 'entry' : 'entries';
72
+ return {
73
+ observed: observedFrom(inputs.observed),
74
+ potential,
75
+ financial: financialFrom(inputs.invoices),
76
+ physical: found,
77
+ statement: `Physical saving from ${servers} retired ${years} across ${priced} ledger ${entries}.`
78
+ };
79
+ }
@@ -163,6 +163,34 @@ export declare function activityFigures(rows: readonly Row[], limit?: number): {
163
163
  counts: Record<string, WindowCount>;
164
164
  arms: Record<string, ActivityArm | null>;
165
165
  };
166
+ /** a page with a pause hook, the same page without it, and the quiet page of the same setup */
167
+ export type ActivityPair = {
168
+ plain: string;
169
+ hook: string;
170
+ quiet: string;
171
+ };
172
+ /** the two pairs the rig measures: a loop off screen in a visible page, and a poll in a hidden tab */
173
+ export declare const ACTIVITY_PAIRS: readonly ActivityPair[];
174
+ /** what a pause hook did for one pair, in watts */
175
+ export type ActivityGain = {
176
+ pair: ActivityPair;
177
+ /** the same page without the hook less with it, over the arm medians; the range sets each page's extreme against the other's opposite */
178
+ saved: {
179
+ median: number;
180
+ min: number;
181
+ max: number;
182
+ };
183
+ /** what the page with the hook still draws above the quiet page */
184
+ residual: number;
185
+ };
186
+ /**
187
+ * Per pair, the watts a hook removes from the page it is on (the gain), and the watts that page
188
+ * still draws above a quiet one (the residual). A pair with an arm that has no kept window is left
189
+ * out. The quiet arm is not the baseline of the gain: a quiet page is where a perfect hook would end.
190
+ */
191
+ export declare function activityGains(arms: Readonly<Record<string, {
192
+ extraWatts: Spread;
193
+ } | null | undefined>>, pairs?: readonly ActivityPair[]): ActivityGain[];
166
194
  /** attributional joules for `bytes` (the same SWD v4 rate as the headline, no origin term: these are the same requests with fewer bytes) */
167
195
  export declare const ledgerJoules: (bytes: number) => number;
168
196
  /** megawatt-hours a year when `perView` joules are saved on a share of `views` views */
@@ -272,6 +272,36 @@ export function activityFigures(rows, limit = CONTAMINATION_MS_PER_S) {
272
272
  }
273
273
  return { idleWatts, noisyRounds: noisy.sort((a, b) => a - b), counts, arms };
274
274
  }
275
+ /** the two pairs the rig measures: a loop off screen in a visible page, and a poll in a hidden tab */
276
+ export const ACTIVITY_PAIRS = [
277
+ { plain: 'raf-off-plain', hook: 'raf-off-hook', quiet: 'quiet' },
278
+ { plain: 'poll-hidden-plain', hook: 'poll-hidden-hook', quiet: 'quiet-hidden' }
279
+ ];
280
+ /**
281
+ * Per pair, the watts a hook removes from the page it is on (the gain), and the watts that page
282
+ * still draws above a quiet one (the residual). A pair with an arm that has no kept window is left
283
+ * out. The quiet arm is not the baseline of the gain: a quiet page is where a perfect hook would end.
284
+ */
285
+ export function activityGains(arms, pairs = ACTIVITY_PAIRS) {
286
+ return pairs.flatMap((pair) => {
287
+ const plain = arms[pair.plain]?.extraWatts;
288
+ const hook = arms[pair.hook]?.extraWatts;
289
+ const quiet = arms[pair.quiet]?.extraWatts;
290
+ if (!plain || !hook || !quiet)
291
+ return [];
292
+ return [
293
+ {
294
+ pair,
295
+ saved: {
296
+ median: plain.median - hook.median,
297
+ min: plain.min - hook.max,
298
+ max: plain.max - hook.min
299
+ },
300
+ residual: hook.median - quiet.median
301
+ }
302
+ ];
303
+ });
304
+ }
275
305
  /** attributional joules for `bytes` (the same SWD v4 rate as the headline, no origin term: these are the same requests with fewer bytes) */
276
306
  export const ledgerJoules = (bytes) => attributionalJoules(bytes);
277
307
  /** megawatt-hours a year when `perView` joules are saved on a share of `views` views */
@@ -1,6 +1,6 @@
1
1
  import type { Layer } from './inputs.js';
2
2
  /** the rigs that write to `measurements/<rig>/`, one folder each */
3
- export declare const RIGS: readonly ["repeat-nav", "on-wire", "zero-network", "device-cpu", "rapl", "iphone", "payload", "trim", "link-assets", "image-crawl", "dictionary-size"];
3
+ export declare const RIGS: readonly ["repeat-nav", "on-wire", "zero-network", "device-cpu", "rapl", "iphone", "payload", "trim", "link-assets", "image-crawl", "dictionary-size", "nav-replay", "first-payload", "embed-markup"];
4
4
  /** one of {@link RIGS} */
5
5
  export type Rig = (typeof RIGS)[number];
6
6
  /** the format version {@link parseMeasurement} reads */
@@ -10,7 +10,10 @@ export const RIGS = [
10
10
  'trim',
11
11
  'link-assets',
12
12
  'image-crawl',
13
- 'dictionary-size'
13
+ 'dictionary-size',
14
+ 'nav-replay',
15
+ 'first-payload',
16
+ 'embed-markup'
14
17
  ];
15
18
  /** the format version {@link parseMeasurement} reads */
16
19
  export const MEASUREMENT_SCHEMA = 1;
@@ -136,5 +136,14 @@ export type Transitions = {
136
136
  };
137
137
  /** counts per `(from, route)` pair and per `from`; a view with no `from` counts in neither */
138
138
  export declare function transitions(views: readonly TimedView[]): Transitions;
139
- /** the share of views from `from` that went to each route, in route order; empty when none came from it */
140
- export declare function nextShare(views: readonly TimedView[], from: string): Record<string, number>;
139
+ /**
140
+ * The share of views from `from` that went to each route, in route order; empty when none came from
141
+ * it. With `first`, only a first view of the route counts toward its share, over every view from
142
+ * `from`. A catalogue entry saves only a first view, so that share is the one to rank entries by:
143
+ * the share over all views counts returning visits and, in a replay of 989,818 public visitors,
144
+ * ran 1.5 to 7 times the observed chance of a first view in the bins that decide an entry
145
+ * (`measurements/nav-replay`).
146
+ */
147
+ export declare function nextShare(views: readonly TimedView[], from: string, options?: {
148
+ first?: boolean;
149
+ }): Record<string, number>;
@@ -214,9 +214,19 @@ export function transitions(views) {
214
214
  const sorted = [...pairs.values()].sort((a, b) => a.from === b.from ? (a.route < b.route ? -1 : 1) : a.from < b.from ? -1 : 1);
215
215
  return { pairs: sorted, byFrom };
216
216
  }
217
- /** the share of views from `from` that went to each route, in route order; empty when none came from it */
218
- export function nextShare(views, from) {
219
- const { pairs, byFrom } = transitions(views);
217
+ /** a view of a page the device did not hold: a network view of a cold route, or a catalogue entry's first open */
218
+ const isFirstView = (view) => view.reason === 'cold' || view.reason === 'catalogue';
219
+ /**
220
+ * The share of views from `from` that went to each route, in route order; empty when none came from
221
+ * it. With `first`, only a first view of the route counts toward its share, over every view from
222
+ * `from`. A catalogue entry saves only a first view, so that share is the one to rank entries by:
223
+ * the share over all views counts returning visits and, in a replay of 989,818 public visitors,
224
+ * ran 1.5 to 7 times the observed chance of a first view in the bins that decide an entry
225
+ * (`measurements/nav-replay`).
226
+ */
227
+ export function nextShare(views, from, options = {}) {
228
+ const { byFrom } = transitions(views);
229
+ const { pairs } = options.first ? transitions(views.filter(isFirstView)) : transitions(views);
220
230
  const total = byFrom[from];
221
231
  const out = {};
222
232
  if (!total)