versimo 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.
package/dist/health.js ADDED
@@ -0,0 +1,68 @@
1
+ import { rollback } from './transitions.js';
2
+ import { VersimoError } from './types.js';
3
+ /** Recorded as `by` in history when the caller gives no name. */
4
+ export const HEALTH_ACTOR = 'versimo-health';
5
+ const isNumber = (v) => typeof v === 'number' && Number.isFinite(v);
6
+ const isCount = (v) => Number.isInteger(v) && v >= 0;
7
+ function invalid(message) {
8
+ throw new VersimoError('INVALID_INPUT', message);
9
+ }
10
+ function checkInputs(checks, obs) {
11
+ const { maxErrorRate, maxLatencyMs, url, minRequests } = checks;
12
+ if (maxErrorRate !== undefined && (!isNumber(maxErrorRate) || maxErrorRate < 0 || maxErrorRate > 1)) {
13
+ invalid('maxErrorRate must be a number from 0 to 1');
14
+ }
15
+ if (maxLatencyMs !== undefined && (!isNumber(maxLatencyMs) || maxLatencyMs < 0)) {
16
+ invalid('maxLatencyMs must be a number of 0 or more');
17
+ }
18
+ if (url !== undefined && (typeof url !== 'string' || url === ''))
19
+ invalid('url must be a non-empty string');
20
+ if (minRequests !== undefined && !isCount(minRequests))
21
+ invalid('minRequests must be an integer of 0 or more');
22
+ if (obs.requests !== undefined && !isCount(obs.requests))
23
+ invalid('requests must be an integer of 0 or more');
24
+ if (obs.errors !== undefined && !isCount(obs.errors))
25
+ invalid('errors must be an integer of 0 or more');
26
+ if (obs.errors !== undefined && obs.requests !== undefined && obs.errors > obs.requests) {
27
+ invalid('errors cannot be more than requests');
28
+ }
29
+ if (obs.latencyMs !== undefined && (!isNumber(obs.latencyMs) || obs.latencyMs < 0)) {
30
+ invalid('latencyMs must be a number of 0 or more');
31
+ }
32
+ if (obs.urlStatus !== undefined && !isCount(obs.urlStatus))
33
+ invalid('urlStatus must be an integer of 0 or more');
34
+ }
35
+ /** Judges one observation against the checks. Pure, and the same in every language. */
36
+ export function evaluateHealth(checks, obs) {
37
+ checkInputs(checks, obs);
38
+ const failures = [];
39
+ const { requests, errors, latencyMs, urlStatus } = obs;
40
+ if (checks.maxErrorRate !== undefined && requests !== undefined && errors !== undefined) {
41
+ if (requests >= Math.max(1, checks.minRequests ?? 1)) {
42
+ const rate = errors / requests;
43
+ if (rate > checks.maxErrorRate)
44
+ failures.push({ check: 'errorRate', value: rate, limit: checks.maxErrorRate });
45
+ }
46
+ }
47
+ if (checks.maxLatencyMs !== undefined && latencyMs !== undefined && latencyMs > checks.maxLatencyMs) {
48
+ failures.push({ check: 'latency', value: latencyMs, limit: checks.maxLatencyMs });
49
+ }
50
+ if (checks.url !== undefined && urlStatus !== undefined && (urlStatus < 200 || urlStatus > 299)) {
51
+ failures.push({ check: 'url', value: urlStatus, limit: null });
52
+ }
53
+ return { healthy: failures.length === 0, failures };
54
+ }
55
+ /**
56
+ * Judges current and, when it fails, steps back to last on its own.
57
+ * The rollback is recorded in history with the failed checks as the reason,
58
+ * for example `health: errorRate, latency`. With no last there is nothing
59
+ * to go back to, so the record is left as it is and only the verdict says so.
60
+ */
61
+ export function checkHealth(record, checks, obs, opts = {}) {
62
+ const verdict = evaluateHealth(checks, obs);
63
+ if (verdict.healthy || record.last === null)
64
+ return { record, verdict, rolledBack: false };
65
+ const reason = `health: ${verdict.failures.map((f) => f.check).join(', ')}`;
66
+ const next = rollback(record, { ...opts, by: opts.by ?? HEALTH_ACTOR, reason });
67
+ return { record: next, verdict, rolledBack: true };
68
+ }
package/dist/index.d.ts CHANGED
@@ -2,7 +2,11 @@ export { bucketFor } from './bucket.js';
2
2
  export { resolve, resolveVersion } from './resolve.js';
3
3
  export { draftNext, promote, rollback, setRollout } from './transitions.js';
4
4
  export { validateRecord, type ValidationResult } from './validate.js';
5
+ export { checkHealth, evaluateHealth, HEALTH_ACTOR, type HealthCheckName, type HealthChecks, type HealthFailure, type HealthObservation, type HealthResult, type HealthVerdict, } from './health.js';
6
+ export { createHealthMonitor, type HealthAlert, type HealthMonitor, type HealthReport, type MonitorOptions, type PostHogOptions, type RecordStore, } from './monitor.js';
5
7
  export { compareSemver, isSemver, parseSemver, SEMVER_PATTERN, type ParsedSemver } from './semver.js';
8
+ export { createDeployClient, type DeployClient, type DeployClientOptions, type DeployModule } from './deploy.js';
6
9
  export { createClient, type ClientOptions, type SourceFn, type VersimoClient } from './client.js';
10
+ export { postHogFlagKey, postHogRollout, rolloutFromFlag, POSTHOG_DISTINCT_ID, type PostHogRolloutOptions, type RolloutFn, } from './posthog.js';
7
11
  export { VersimoProvider, type EvaluationContext, type ResolutionDetails } from './provider.js';
8
12
  export { VersimoError, type Action, type Channel, type Context, type ErrorCode, type HistoryEntry, type ModuleRecord, type Resolution, type ResolutionReason, type TransitionOptions, } from './types.js';
package/dist/index.js CHANGED
@@ -2,7 +2,11 @@ export { bucketFor } from './bucket.js';
2
2
  export { resolve, resolveVersion } from './resolve.js';
3
3
  export { draftNext, promote, rollback, setRollout } from './transitions.js';
4
4
  export { validateRecord } from './validate.js';
5
+ export { checkHealth, evaluateHealth, HEALTH_ACTOR, } from './health.js';
6
+ export { createHealthMonitor, } from './monitor.js';
5
7
  export { compareSemver, isSemver, parseSemver, SEMVER_PATTERN } from './semver.js';
8
+ export { createDeployClient } from './deploy.js';
6
9
  export { createClient } from './client.js';
10
+ export { postHogFlagKey, postHogRollout, rolloutFromFlag, POSTHOG_DISTINCT_ID, } from './posthog.js';
7
11
  export { VersimoProvider } from './provider.js';
8
12
  export { VersimoError, } from './types.js';
@@ -0,0 +1,67 @@
1
+ import { type HealthChecks, type HealthFailure, type HealthObservation, type HealthResult } from './health.js';
2
+ import { type ModuleRecord } from './types.js';
3
+ /** Where the monitor reads and writes module records. */
4
+ export interface RecordStore {
5
+ read(module: string): ModuleRecord | null | undefined | Promise<ModuleRecord | null | undefined>;
6
+ write(record: ModuleRecord): void | Promise<void>;
7
+ }
8
+ /**
9
+ * PostHog error tracking. Tag your events with the module and the version the
10
+ * user got. The error rate is `$exception` events over all events for that
11
+ * module and version in the window.
12
+ */
13
+ export interface PostHogOptions {
14
+ /** Default `https://us.posthog.com`. Use `https://eu.posthog.com` for the EU cloud. */
15
+ host?: string;
16
+ projectId: string | number;
17
+ /** A personal API key with query read access. Keep it in your secret store. */
18
+ apiKey: string;
19
+ /** How far back to look, in minutes. Default 5. */
20
+ windowMinutes?: number;
21
+ /** Event property with the module slug. Default `versimo_module`. */
22
+ moduleProperty?: string;
23
+ /** Event property with the version. Default `versimo_version`. */
24
+ versionProperty?: string;
25
+ }
26
+ export interface HealthAlert {
27
+ module: string;
28
+ /** ISO 8601 date-time of the check. */
29
+ at: string;
30
+ /** The version that failed. */
31
+ version: string;
32
+ rolledBack: boolean;
33
+ /** The version users are on now. */
34
+ current: string;
35
+ failures: HealthFailure[];
36
+ /** One line for people, also used as the Slack `text`. */
37
+ text: string;
38
+ }
39
+ export interface MonitorOptions {
40
+ store: RecordStore;
41
+ /** Checks by module slug, or a function that returns them. */
42
+ checks: Record<string, HealthChecks> | ((module: string) => HealthChecks | undefined);
43
+ /** Your own measurements. Values here win over PostHog and the URL check. */
44
+ observe?: (module: string, record: ModuleRecord) => HealthObservation | Promise<HealthObservation>;
45
+ posthog?: PostHogOptions;
46
+ /** A webhook URL that gets the alert as JSON (Slack works), or a function. */
47
+ alert?: string | ((alert: HealthAlert) => void | Promise<void>);
48
+ /** Recorded as `by` in history. Default `versimo-health`. */
49
+ by?: string;
50
+ /** Time out for the check URL, in milliseconds. Default 5000. */
51
+ urlTimeoutMs?: number;
52
+ /** Called when a scheduled check throws. Default `console.warn`. */
53
+ onError?: (module: string, error: unknown) => void;
54
+ fetch?: typeof fetch;
55
+ now?: () => Date | number;
56
+ }
57
+ export interface HealthReport extends HealthResult {
58
+ module: string;
59
+ observation: HealthObservation;
60
+ }
61
+ export interface HealthMonitor {
62
+ /** Runs the checks for one module once. Rolls back, writes and alerts when current fails. */
63
+ check(module: string): Promise<HealthReport>;
64
+ /** Checks every module on a timer. Returns a function that stops it. */
65
+ start(modules: string[], everyMs?: number): () => void;
66
+ }
67
+ export declare function createHealthMonitor(options: MonitorOptions): HealthMonitor;
@@ -0,0 +1,148 @@
1
+ import { checkHealth } from './health.js';
2
+ import { validateRecord } from './validate.js';
3
+ import { VersimoError } from './types.js';
4
+ const IDENT = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
5
+ async function urlStatus(f, url, timeoutMs) {
6
+ const ctrl = new AbortController();
7
+ const timer = setTimeout(() => ctrl.abort(), timeoutMs);
8
+ try {
9
+ const res = await f(url, { signal: ctrl.signal, redirect: 'follow' });
10
+ return res.status;
11
+ }
12
+ catch {
13
+ return 0;
14
+ }
15
+ finally {
16
+ clearTimeout(timer);
17
+ }
18
+ }
19
+ async function posthogCounts(f, o, module, version) {
20
+ const moduleProp = o.moduleProperty ?? 'versimo_module';
21
+ const versionProp = o.versionProperty ?? 'versimo_version';
22
+ if (!IDENT.test(moduleProp) || !IDENT.test(versionProp)) {
23
+ throw new VersimoError('INVALID_INPUT', 'PostHog property names must be plain identifiers');
24
+ }
25
+ const minutes = o.windowMinutes ?? 5;
26
+ if (!Number.isInteger(minutes) || minutes < 1) {
27
+ throw new VersimoError('INVALID_INPUT', 'windowMinutes must be a whole number of 1 or more');
28
+ }
29
+ const host = (o.host ?? 'https://us.posthog.com').replace(/\/+$/, '');
30
+ const query = `SELECT countIf(event = '$exception'), count() FROM events ` +
31
+ `WHERE properties.${moduleProp} = {module} AND properties.${versionProp} = {version} ` +
32
+ `AND timestamp > now() - toIntervalMinute(${minutes})`;
33
+ let res;
34
+ try {
35
+ res = await f(`${host}/api/projects/${encodeURIComponent(String(o.projectId))}/query/`, {
36
+ method: 'POST',
37
+ headers: { Authorization: `Bearer ${o.apiKey}`, 'Content-Type': 'application/json' },
38
+ body: JSON.stringify({ query: { kind: 'HogQLQuery', query, values: { module, version } } }),
39
+ });
40
+ }
41
+ catch (err) {
42
+ throw new VersimoError('SOURCE_ERROR', `PostHog query failed: ${err.message}`);
43
+ }
44
+ if (!res.ok)
45
+ throw new VersimoError('SOURCE_ERROR', `PostHog query returned ${res.status}`);
46
+ const body = (await res.json());
47
+ const row = body.results?.[0];
48
+ const errors = Number(row?.[0] ?? 0);
49
+ const requests = Number(row?.[1] ?? 0);
50
+ if (!Number.isInteger(errors) || !Number.isInteger(requests)) {
51
+ throw new VersimoError('SOURCE_ERROR', 'PostHog query returned an unexpected shape');
52
+ }
53
+ return { requests, errors };
54
+ }
55
+ function alertText(a) {
56
+ const checks = a.failures.map((f) => f.check).join(', ');
57
+ const tail = a.rolledBack ? `Rolled back to ${a.current}.` : 'There is no last version to roll back to.';
58
+ return `Versimo: ${a.module} ${a.version} failed its health checks (${checks}). ${tail}`;
59
+ }
60
+ export function createHealthMonitor(options) {
61
+ const now = () => new Date(options.now?.() ?? Date.now());
62
+ const f = () => {
63
+ const impl = options.fetch ?? globalThis.fetch;
64
+ if (!impl)
65
+ throw new VersimoError('SOURCE_ERROR', 'No fetch available. Pass the `fetch` option.');
66
+ return impl;
67
+ };
68
+ const checksFor = (module) => typeof options.checks === 'function' ? options.checks(module) : options.checks[module];
69
+ // The version we last alerted about, per module, so a failure that cannot be rolled back alerts once.
70
+ const alerted = new Map();
71
+ async function sendAlert(a) {
72
+ if (options.alert === undefined)
73
+ return;
74
+ if (typeof options.alert === 'function')
75
+ return options.alert(a);
76
+ const res = await f()(options.alert, {
77
+ method: 'POST',
78
+ headers: { 'Content-Type': 'application/json' },
79
+ body: JSON.stringify(a),
80
+ });
81
+ if (!res.ok)
82
+ throw new VersimoError('SOURCE_ERROR', `Alert webhook returned ${res.status}`);
83
+ }
84
+ async function check(module) {
85
+ const record = await options.store.read(module);
86
+ if (record === null || record === undefined)
87
+ throw new VersimoError('NOT_FOUND', `No record for module "${module}"`);
88
+ const valid = validateRecord(record);
89
+ if (!valid.ok)
90
+ throw new VersimoError('INVALID_RECORD', `Invalid record for "${module}": ${valid.errors.join('; ')}`);
91
+ const checks = checksFor(module) ?? {};
92
+ let observation = {};
93
+ if (options.posthog && checks.maxErrorRate !== undefined) {
94
+ observation = { ...observation, ...(await posthogCounts(f(), options.posthog, module, record.current)) };
95
+ }
96
+ if (checks.url !== undefined) {
97
+ observation.urlStatus = await urlStatus(f(), checks.url, options.urlTimeoutMs ?? 5000);
98
+ }
99
+ if (options.observe)
100
+ observation = { ...observation, ...(await options.observe(module, record)) };
101
+ const at = now();
102
+ const result = checkHealth(record, checks, observation, { now: at, by: options.by });
103
+ if (result.rolledBack)
104
+ await options.store.write(result.record);
105
+ if (result.verdict.healthy) {
106
+ alerted.delete(module);
107
+ }
108
+ else if (result.rolledBack || alerted.get(module) !== record.current) {
109
+ alerted.set(module, record.current);
110
+ const base = {
111
+ module,
112
+ at: at.toISOString(),
113
+ version: record.current,
114
+ rolledBack: result.rolledBack,
115
+ current: result.record.current,
116
+ failures: result.verdict.failures,
117
+ };
118
+ await sendAlert({ ...base, text: alertText(base) });
119
+ }
120
+ return { ...result, module, observation };
121
+ }
122
+ function start(modules, everyMs = 60_000) {
123
+ const onError = options.onError ?? ((m, e) => console.warn(`versimo health check for ${m} failed:`, e));
124
+ let running = false;
125
+ const tick = async () => {
126
+ if (running)
127
+ return;
128
+ running = true;
129
+ try {
130
+ for (const m of modules) {
131
+ try {
132
+ await check(m);
133
+ }
134
+ catch (err) {
135
+ onError(m, err);
136
+ }
137
+ }
138
+ }
139
+ finally {
140
+ running = false;
141
+ }
142
+ };
143
+ void tick();
144
+ const timer = setInterval(() => void tick(), everyMs);
145
+ return () => clearInterval(timer);
146
+ }
147
+ return { check, start };
148
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * A function returning the share of users on `next` for a module, from 0 to 100.
3
+ * Null or undefined means "no override": the record's own `rollout` is used.
4
+ */
5
+ export type RolloutFn = (module: string) => number | null | undefined | Promise<number | null | undefined>;
6
+ export interface PostHogRolloutOptions {
7
+ /** The PostHog project API key (starts with `phc_`). It is a public key. */
8
+ apiKey: string;
9
+ /** PostHog ingestion host. Default `https://eu.i.posthog.com`. Use `https://us.i.posthog.com` for US projects. */
10
+ host?: string;
11
+ /** How long one PostHog answer is cached, in milliseconds. Default 30000. */
12
+ ttlMs?: number;
13
+ /** Clock for the cache, in milliseconds. Mainly for tests. */
14
+ now?: () => number;
15
+ /** Fetch implementation. Defaults to the global `fetch`. */
16
+ fetch?: typeof fetch;
17
+ }
18
+ /** The PostHog flag that carries the share for a module. */
19
+ export declare function postHogFlagKey(module: string): string;
20
+ /** The fixed distinct id sent to PostHog. No user id ever leaves the app. */
21
+ export declare const POSTHOG_DISTINCT_ID = "versimo";
22
+ /**
23
+ * Reads the share on `next` from one flag in a PostHog `/flags?v=2` answer.
24
+ *
25
+ * - No flag: null, so the record's own rollout is used.
26
+ * - Flag off: 0. Turning the flag off takes everyone off `next`.
27
+ * - Flag on with a payload `{"rollout": n}`, n an integer from 0 to 100: n.
28
+ * - Anything else: null.
29
+ *
30
+ * The payload may be a JSON string, as PostHog sends it, or an object.
31
+ * Who lands on `next` is still decided by `bucketFor`, never by PostHog.
32
+ */
33
+ export declare function rolloutFromFlag(flag: unknown): number | null;
34
+ /**
35
+ * A rollout source backed by PostHog feature flags, for `createClient({ rollout })`.
36
+ *
37
+ * One request to `<host>/flags?v=2` is made per TTL for all modules. The request
38
+ * carries only the project key and the fixed distinct id `versimo`, so no user id
39
+ * or other user data is sent. When PostHog cannot be reached the last good answer
40
+ * is kept, and with none the record's own rollout is used.
41
+ */
42
+ export declare function postHogRollout(options: PostHogRolloutOptions): RolloutFn;
@@ -0,0 +1,96 @@
1
+ import { VersimoError } from './types.js';
2
+ /** The PostHog flag that carries the share for a module. */
3
+ export function postHogFlagKey(module) {
4
+ return `versimo-${module}`;
5
+ }
6
+ /** The fixed distinct id sent to PostHog. No user id ever leaves the app. */
7
+ export const POSTHOG_DISTINCT_ID = 'versimo';
8
+ const isObject = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
9
+ /**
10
+ * Reads the share on `next` from one flag in a PostHog `/flags?v=2` answer.
11
+ *
12
+ * - No flag: null, so the record's own rollout is used.
13
+ * - Flag off: 0. Turning the flag off takes everyone off `next`.
14
+ * - Flag on with a payload `{"rollout": n}`, n an integer from 0 to 100: n.
15
+ * - Anything else: null.
16
+ *
17
+ * The payload may be a JSON string, as PostHog sends it, or an object.
18
+ * Who lands on `next` is still decided by `bucketFor`, never by PostHog.
19
+ */
20
+ export function rolloutFromFlag(flag) {
21
+ if (!isObject(flag))
22
+ return null;
23
+ if (flag.enabled === false)
24
+ return 0;
25
+ if (flag.enabled !== true)
26
+ return null;
27
+ let payload = isObject(flag.metadata) ? flag.metadata.payload : undefined;
28
+ if (typeof payload === 'string') {
29
+ try {
30
+ payload = JSON.parse(payload);
31
+ }
32
+ catch {
33
+ return null;
34
+ }
35
+ }
36
+ if (!isObject(payload))
37
+ return null;
38
+ const n = payload.rollout;
39
+ return typeof n === 'number' && Number.isInteger(n) && n >= 0 && n <= 100 ? n : null;
40
+ }
41
+ /**
42
+ * A rollout source backed by PostHog feature flags, for `createClient({ rollout })`.
43
+ *
44
+ * One request to `<host>/flags?v=2` is made per TTL for all modules. The request
45
+ * carries only the project key and the fixed distinct id `versimo`, so no user id
46
+ * or other user data is sent. When PostHog cannot be reached the last good answer
47
+ * is kept, and with none the record's own rollout is used.
48
+ */
49
+ export function postHogRollout(options) {
50
+ if (!options.apiKey)
51
+ throw new VersimoError('INVALID_INPUT', 'postHogRollout needs an apiKey');
52
+ const ttlMs = options.ttlMs ?? 30_000;
53
+ const now = options.now ?? Date.now;
54
+ const url = `${(options.host ?? 'https://eu.i.posthog.com').replace(/\/+$/, '')}/flags?v=2`;
55
+ let cached;
56
+ let inflight;
57
+ async function load() {
58
+ const f = options.fetch ?? globalThis.fetch;
59
+ if (!f)
60
+ throw new VersimoError('SOURCE_ERROR', 'No fetch available. Pass the `fetch` option.');
61
+ const res = await f(url, {
62
+ method: 'POST',
63
+ headers: { 'content-type': 'application/json' },
64
+ body: JSON.stringify({ api_key: options.apiKey, distinct_id: POSTHOG_DISTINCT_ID }),
65
+ });
66
+ if (!res.ok)
67
+ throw new VersimoError('SOURCE_ERROR', `PostHog returned ${res.status}`);
68
+ const body = await res.json();
69
+ if (!isObject(body) || !isObject(body.flags))
70
+ throw new VersimoError('SOURCE_ERROR', 'PostHog answer has no flags');
71
+ return body.flags;
72
+ }
73
+ async function flags() {
74
+ if (cached && cached.expires > now())
75
+ return cached.flags;
76
+ inflight ??= load()
77
+ .then((fresh) => {
78
+ cached = { flags: fresh, expires: now() + ttlMs };
79
+ return fresh;
80
+ })
81
+ .catch(() => {
82
+ // Keep the last good answer for another TTL. With none, use the record.
83
+ if (cached)
84
+ cached = { flags: cached.flags, expires: now() + ttlMs };
85
+ return cached?.flags;
86
+ })
87
+ .finally(() => {
88
+ inflight = undefined;
89
+ });
90
+ return inflight;
91
+ }
92
+ return async (module) => {
93
+ const all = await flags();
94
+ return all ? rolloutFromFlag(all[postHogFlagKey(module)]) : null;
95
+ };
96
+ }
@@ -11,6 +11,8 @@ function apply(record, changes, action, from, to, opts) {
11
11
  const entry = { at, action, from, to };
12
12
  if (opts.by !== undefined)
13
13
  entry.by = opts.by;
14
+ if (opts.reason !== undefined)
15
+ entry.reason = opts.reason;
14
16
  return { ...record, ...changes, updatedAt: at, history: [...(record.history ?? []), entry] };
15
17
  }
16
18
  /** Sets a new next version at 0% rollout. It replaces any next already drafted. */
package/dist/types.d.ts CHANGED
@@ -6,6 +6,8 @@ export interface HistoryEntry {
6
6
  from: string | null;
7
7
  to: string | null;
8
8
  by?: string;
9
+ /** Why the change was made, for example `health: errorRate`. */
10
+ reason?: string;
9
11
  }
10
12
  export interface ModuleRecord {
11
13
  $schema?: string;
@@ -39,6 +41,8 @@ export interface TransitionOptions {
39
41
  by?: string;
40
42
  /** Time of the change. Defaults to now. */
41
43
  now?: Date | string | number;
44
+ /** Why the change was made. Recorded in history. */
45
+ reason?: string;
42
46
  }
43
47
  export type ErrorCode = 'INVALID_INPUT' | 'INVALID_RECORD' | 'NOT_FOUND' | 'SOURCE_ERROR';
44
48
  export declare class VersimoError extends Error {
package/dist/validate.js CHANGED
@@ -3,7 +3,7 @@ const SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
3
3
  const DATE_TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;
4
4
  const ACTIONS = ['draft', 'promote', 'rollback', 'rollout', 'patch'];
5
5
  const KEYS = ['$schema', 'module', 'last', 'current', 'next', 'rollout', 'healthy', 'updatedAt', 'history'];
6
- const ENTRY_KEYS = ['at', 'action', 'from', 'to', 'by'];
6
+ const ENTRY_KEYS = ['at', 'action', 'from', 'to', 'by', 'reason'];
7
7
  const isObject = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
8
8
  const isDateTime = (v) => typeof v === 'string' && DATE_TIME.test(v) && !Number.isNaN(Date.parse(v));
9
9
  function checkEntry(entry, path, errors) {
@@ -27,6 +27,8 @@ function checkEntry(entry, path, errors) {
27
27
  }
28
28
  if (entry.by !== undefined && typeof entry.by !== 'string')
29
29
  errors.push(`${path}.by must be a string`);
30
+ if (entry.reason !== undefined && typeof entry.reason !== 'string')
31
+ errors.push(`${path}.reason must be a string`);
30
32
  }
31
33
  /** Checks a record by hand. It never throws. Each error names the field. */
32
34
  export function validateRecord(record) {
package/docs/api.md CHANGED
@@ -79,10 +79,26 @@ Moves `next` to `current` and `current` to `last`. Empties `next`, sets `rollout
79
79
 
80
80
  Sets `current` to `last`. Sets `last` and `next` to null, `rollout` to 0 and `healthy` to true. Throws when `last` is null.
81
81
 
82
+ All four take `opts.by` and `opts.reason`, which are written to the history entry.
83
+
82
84
  ### `setRollout(record, n, opts?)`
83
85
 
84
86
  Sets `rollout` to `n`, an integer from 0 to 100. Throws when `n` is above 0 and `next` is null.
85
87
 
88
+ ## Health
89
+
90
+ ### `evaluateHealth(checks, observation)`
91
+
92
+ Judges one observation against the checks and returns `{ healthy, failures }`. Each failure is `{ check, value, limit }`, with `check` one of `errorRate`, `latency` or `url`, in that order. Throws `INVALID_INPUT` for a bad limit or a bad measurement.
93
+
94
+ ### `checkHealth(record, checks, observation, opts?)`
95
+
96
+ Runs `evaluateHealth`. When current fails and there is a last, it returns the rolled back record with `rolledBack: true`. The history entry has `by` (default `versimo-health`) and `reason`, for example `health: errorRate, latency`. With no last the record comes back unchanged. Returns `{ record, verdict, rolledBack }`.
97
+
98
+ ### `createHealthMonitor(options)`
99
+
100
+ Runs the checks on its own: reads the record from your store, measures, rolls back, writes the record and alerts. `check(module)` runs once. `start(modules, everyMs?)` runs on a timer and returns a stop function. See [Health checks](health.md) for the options.
101
+
86
102
  ## Validating
87
103
 
88
104
  ### `validateRecord(record)`
@@ -99,12 +115,15 @@ interface ClientOptions {
99
115
  ttlMs?: number; // default 30000
100
116
  now?: () => number; // clock for the cache, for tests
101
117
  fetch?: typeof fetch; // for URL sources
118
+ rollout?: (module: string) => number | null | undefined | Promise<number | null | undefined>;
102
119
  }
103
120
  ```
104
121
 
122
+ `rollout` overrides the record's share on next, for example with `postHogRollout`. Only the share changes. When it returns null, a value outside 0 to 100, or throws, the record's own rollout is used.
123
+
105
124
  Returns a `VersimoClient`:
106
125
 
107
- - `record(module)` returns the cached or freshly loaded, validated record.
126
+ - `record(module)` returns the cached or freshly loaded, validated record, with any `rollout` override applied.
108
127
  - `resolve(module, ctx?)` returns a `Resolution`.
109
128
  - `version(module, ctx?)` returns the version string.
110
129
  - `clear(module?)` drops one cached record, or all.
@@ -113,6 +132,30 @@ Concurrent loads of one module share a single request. If a refresh fails with a
113
132
 
114
133
  Module slugs must match `^[a-z0-9]+(-[a-z0-9]+)*$`.
115
134
 
135
+ ## PostHog
136
+
137
+ ### `postHogRollout(options)`
138
+
139
+ ```ts
140
+ interface PostHogRolloutOptions {
141
+ apiKey: string; // PostHog project key, phc_...
142
+ host?: string; // default https://eu.i.posthog.com
143
+ ttlMs?: number; // default 30000
144
+ now?: () => number;
145
+ fetch?: typeof fetch;
146
+ }
147
+ ```
148
+
149
+ Returns a rollout function for `createClient`. It reads the flag `versimo-<module>` from one `/flags?v=2` request per TTL, sent with the distinct id `versimo` and no user data. See [PostHog flags drive next](usage.md#posthog-flags-drive-next).
150
+
151
+ ### `rolloutFromFlag(flag)`
152
+
153
+ The share on next from one flag of a PostHog `/flags?v=2` answer, or null to keep the record's rollout. Flag off gives 0. Flag on with a payload whose `rollout` is a whole number from 0 to 100 gives that number. The payload may be a JSON string or an object.
154
+
155
+ ### `postHogFlagKey(module)`
156
+
157
+ `versimo-<module>`.
158
+
116
159
  ## OpenFeature provider
117
160
 
118
161
  ### `new VersimoProvider(client)`
@@ -145,3 +188,27 @@ An `Error` with a `code`.
145
188
  | `INVALID_RECORD` | A fetched record failed `validateRecord` |
146
189
  | `NOT_FOUND` | The source has no record for the module |
147
190
  | `SOURCE_ERROR` | The source threw, or the HTTP request failed |
191
+
192
+ ## GitHub
193
+
194
+ `versimo/github` holds what the Versimo GitHub app needs. It is a separate entry point, so the main package stays small. See [github-app.md](github-app.md) for the full picture.
195
+
196
+ ```ts
197
+ parseModuleTag(tag: string): { module: string; version: string } | null
198
+ modulesFromTags(tags: Iterable<string>): Record<string, string[]>
199
+ recordFromTags(module: string, versions: readonly string[], now?: Date | string | number): ModuleRecord | null
200
+
201
+ createAppJwt(opts: { appId: string | number; privateKey: string; now?: Date | string | number }): Promise<string>
202
+ getInstallationToken(opts: { jwt: string; installationId: string | number; fetch?; apiUrl? }): Promise<{ token: string; expiresAt: string }>
203
+ verifyWebhookSignature(secret: string, body: string | Uint8Array, signature: string | null | undefined): Promise<boolean>
204
+
205
+ createGitHub(opts: { token: string; fetch?: typeof fetch; apiUrl?: string }): GitHubClient
206
+
207
+ interface GitHubClient {
208
+ listTags(owner: string, repo: string): Promise<string[]>;
209
+ moduleVersions(owner: string, repo: string): Promise<Record<string, string[]>>;
210
+ openPullRequest(input: PullRequestInput): Promise<PullRequestResult>;
211
+ }
212
+ ```
213
+
214
+ `openPullRequest` creates a new branch, commits the files to it, opens the pull request and turns on auto merge (squash by default, `autoMerge: false` to skip). It refuses a head branch named `main`, `master`, the default branch or the base, and fails if the branch already exists. It never moves an existing branch. GitHub errors throw `VersimoError` with `NOT_FOUND` or `SOURCE_ERROR`, bad input throws `INVALID_INPUT`.
package/docs/concepts.md CHANGED
@@ -43,7 +43,9 @@ Promote when next has run on live for long enough and looks good.
43
43
 
44
44
  ## Health and rollback
45
45
 
46
- Your health checks decide whether current is healthy. Versimo does not run checks. Your tooling sets `healthy` to `false` on the record.
46
+ Each module can have health checks: an error rate, a latency and a custom URL. When current fails one, Versimo rolls back to last on its own, records the failed checks in the history, and sends an alert. See [Health checks](health.md).
47
+
48
+ You can also set `healthy` to `false` on the record from your own tooling.
47
49
 
48
50
  While `healthy` is `false`, every user gets last. This is the automatic step back and it needs no deploy. If there is no last, users stay on current, because there is nothing better to serve.
49
51