versimo 0.0.0-stage → 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 (52) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/LICENSE +21 -0
  3. package/README.md +110 -2
  4. package/dist/bucket.d.ts +13 -0
  5. package/dist/bucket.js +60 -0
  6. package/dist/cli.d.ts +2 -0
  7. package/dist/cli.js +59 -0
  8. package/dist/client.d.ts +31 -0
  9. package/dist/client.js +102 -0
  10. package/dist/deploy.d.ts +29 -0
  11. package/dist/deploy.js +29 -0
  12. package/dist/github/app-auth.d.ts +14 -0
  13. package/dist/github/app-auth.js +63 -0
  14. package/dist/github/client.d.ts +64 -0
  15. package/dist/github/client.js +127 -0
  16. package/dist/github/index.d.ts +4 -0
  17. package/dist/github/index.js +4 -0
  18. package/dist/github/tags.d.ts +20 -0
  19. package/dist/github/tags.js +56 -0
  20. package/dist/github/webhook.d.ts +5 -0
  21. package/dist/github/webhook.js +23 -0
  22. package/dist/health.d.ts +50 -0
  23. package/dist/health.js +68 -0
  24. package/dist/index.d.ts +12 -0
  25. package/dist/index.js +12 -0
  26. package/dist/monitor.d.ts +67 -0
  27. package/dist/monitor.js +148 -0
  28. package/dist/posthog.d.ts +42 -0
  29. package/dist/posthog.js +96 -0
  30. package/dist/provider.d.ts +28 -0
  31. package/dist/provider.js +51 -0
  32. package/dist/resolve.d.ts +5 -0
  33. package/dist/resolve.js +22 -0
  34. package/dist/semver.d.ts +11 -0
  35. package/dist/semver.js +56 -0
  36. package/dist/transitions.d.ts +14 -0
  37. package/dist/transitions.js +51 -0
  38. package/dist/types.d.ts +51 -0
  39. package/dist/types.js +8 -0
  40. package/dist/validate.d.ts +6 -0
  41. package/dist/validate.js +79 -0
  42. package/docs/api.md +214 -0
  43. package/docs/concepts.md +65 -0
  44. package/docs/github-app.md +90 -0
  45. package/docs/health.md +76 -0
  46. package/docs/porting.md +130 -0
  47. package/docs/record-format.md +62 -0
  48. package/docs/usage.md +236 -0
  49. package/github-app/manifest.json +19 -0
  50. package/package.json +63 -4
  51. package/schema/examples/billing.json +15 -0
  52. package/schema/module-record.schema.json +50 -0
@@ -0,0 +1,127 @@
1
+ import { VersimoError } from '../types.js';
2
+ import { modulesFromTags } from './tags.js';
3
+ const API = 'https://api.github.com';
4
+ const PROTECTED = ['main', 'master'];
5
+ // A conservative subset of what git allows in a branch name.
6
+ const BRANCH = /^(?!\/)(?!.*\/\/)(?!.*\.\.)(?!.*\/$)(?!.*\.lock$)[A-Za-z0-9._\/-]+$/;
7
+ function request(opts) {
8
+ const base = (opts.apiUrl ?? API).replace(/\/+$/, '');
9
+ return async (method, path, body) => {
10
+ const f = opts.fetch ?? globalThis.fetch;
11
+ if (!f)
12
+ throw new VersimoError('SOURCE_ERROR', 'No fetch available. Pass the `fetch` option.');
13
+ let res;
14
+ try {
15
+ res = await f(`${base}${path}`, {
16
+ method,
17
+ headers: {
18
+ Accept: 'application/vnd.github+json',
19
+ Authorization: `Bearer ${opts.token}`,
20
+ 'User-Agent': 'versimo',
21
+ 'X-GitHub-Api-Version': '2022-11-28',
22
+ ...(body === undefined ? {} : { 'Content-Type': 'application/json' }),
23
+ },
24
+ body: body === undefined ? undefined : JSON.stringify(body),
25
+ });
26
+ }
27
+ catch (err) {
28
+ throw new VersimoError('SOURCE_ERROR', `GitHub ${method} ${path} failed: ${err.message}`);
29
+ }
30
+ const text = await res.text();
31
+ let data = {};
32
+ try {
33
+ data = text ? JSON.parse(text) : {};
34
+ }
35
+ catch {
36
+ if (res.ok)
37
+ throw new VersimoError('SOURCE_ERROR', `GitHub ${method} ${path}: the answer was not JSON`);
38
+ }
39
+ if (res.status === 404)
40
+ throw new VersimoError('NOT_FOUND', `GitHub ${method} ${path}: not found`);
41
+ if (!res.ok) {
42
+ const message = typeof data?.message === 'string' ? data.message : res.statusText;
43
+ throw new VersimoError('SOURCE_ERROR', `GitHub ${method} ${path}: ${res.status} ${message}`);
44
+ }
45
+ return data;
46
+ };
47
+ }
48
+ const enc = encodeURIComponent;
49
+ export function createGitHub(opts) {
50
+ if (!opts || typeof opts.token !== 'string' || !opts.token) {
51
+ throw new VersimoError('INVALID_INPUT', 'token is required');
52
+ }
53
+ const call = request(opts);
54
+ const repoPath = (owner, repo) => `/repos/${enc(owner)}/${enc(repo)}`;
55
+ async function listTags(owner, repo) {
56
+ const names = [];
57
+ for (let page = 1;; page++) {
58
+ const batch = (await call('GET', `${repoPath(owner, repo)}/tags?per_page=100&page=${page}`));
59
+ for (const t of batch)
60
+ names.push(t.name);
61
+ if (batch.length < 100)
62
+ return names;
63
+ }
64
+ }
65
+ async function openPullRequest(input) {
66
+ const { owner, repo, head, title, files } = input;
67
+ if (!title)
68
+ throw new VersimoError('INVALID_INPUT', 'title is required');
69
+ if (!Array.isArray(files) || files.length === 0)
70
+ throw new VersimoError('INVALID_INPUT', 'files must not be empty');
71
+ if (typeof head !== 'string' || !BRANCH.test(head)) {
72
+ throw new VersimoError('INVALID_INPUT', `head ${JSON.stringify(head)} is not a valid branch name`);
73
+ }
74
+ const path = repoPath(owner, repo);
75
+ const info = (await call('GET', path));
76
+ const base = input.base ?? info.default_branch;
77
+ if (head === base || head === info.default_branch || PROTECTED.includes(head)) {
78
+ throw new VersimoError('INVALID_INPUT', `Versimo never writes to ${head}. Use a new branch for the PR.`);
79
+ }
80
+ const ref = (await call('GET', `${path}/git/ref/heads/${base.split('/').map(enc).join('/')}`));
81
+ const parent = ref.object.sha;
82
+ const commit = (await call('GET', `${path}/git/commits/${parent}`));
83
+ const tree = (await call('POST', `${path}/git/trees`, {
84
+ base_tree: commit.tree.sha,
85
+ tree: files.map((f) => ({ path: f.path, mode: '100644', type: 'blob', content: f.content })),
86
+ }));
87
+ const created = (await call('POST', `${path}/git/commits`, {
88
+ message: input.message ?? title,
89
+ tree: tree.sha,
90
+ parents: [parent],
91
+ }));
92
+ // Create, never update: this fails if the branch already exists.
93
+ await call('POST', `${path}/git/refs`, { ref: `refs/heads/${head}`, sha: created.sha });
94
+ const pr = (await call('POST', `${path}/pulls`, { title, head, base, body: input.body ?? '' }));
95
+ const result = { number: pr.number, url: pr.html_url, head, base, autoMerge: false };
96
+ const method = input.autoMerge ?? 'SQUASH';
97
+ if (method === false)
98
+ return result;
99
+ try {
100
+ const gql = (await call('POST', '/graphql', {
101
+ query: 'mutation($id: ID!, $method: PullRequestMergeMethod!) { enablePullRequestAutoMerge(input: { pullRequestId: $id, mergeMethod: $method }) { clientMutationId } }',
102
+ variables: { id: pr.node_id, method },
103
+ }));
104
+ if (Array.isArray(gql.errors) && gql.errors.length > 0) {
105
+ result.autoMergeError = String(gql.errors[0]?.message ?? 'auto merge failed');
106
+ }
107
+ else {
108
+ result.autoMerge = true;
109
+ }
110
+ }
111
+ catch (err) {
112
+ result.autoMergeError = err.message;
113
+ }
114
+ return result;
115
+ }
116
+ return {
117
+ listTags,
118
+ moduleVersions: async (owner, repo) => modulesFromTags(await listTags(owner, repo)),
119
+ openPullRequest,
120
+ };
121
+ }
122
+ /** Swaps an app JWT for an installation token. Tokens last one hour. */
123
+ export async function getInstallationToken(opts) {
124
+ const call = request({ token: opts.jwt, fetch: opts.fetch, apiUrl: opts.apiUrl });
125
+ const data = (await call('POST', `/app/installations/${enc(String(opts.installationId))}/access_tokens`, {}));
126
+ return { token: data.token, expiresAt: data.expires_at };
127
+ }
@@ -0,0 +1,4 @@
1
+ export { parseModuleTag, modulesFromTags, recordFromTags, type ModuleTag } from './tags.js';
2
+ export { verifyWebhookSignature } from './webhook.js';
3
+ export { createAppJwt, type AppJwtOptions } from './app-auth.js';
4
+ export { createGitHub, getInstallationToken, type FileChange, type GitHubClient, type GitHubOptions, type InstallationTokenOptions, type MergeMethod, type PullRequestInput, type PullRequestResult, } from './client.js';
@@ -0,0 +1,4 @@
1
+ export { parseModuleTag, modulesFromTags, recordFromTags } from './tags.js';
2
+ export { verifyWebhookSignature } from './webhook.js';
3
+ export { createAppJwt } from './app-auth.js';
4
+ export { createGitHub, getInstallationToken, } from './client.js';
@@ -0,0 +1,20 @@
1
+ import type { ModuleRecord } from '../types.js';
2
+ export interface ModuleTag {
3
+ module: string;
4
+ version: string;
5
+ }
6
+ /**
7
+ * Reads a tag of the form `module/vX.Y.Z`, for example `billing/v2.4.0`.
8
+ * The module must be a lower-case slug. Anything else gives null, so tags
9
+ * such as `v1.0.0` or `packages/go/v0.2.0` are ignored.
10
+ */
11
+ export declare function parseModuleTag(tag: string): ModuleTag | null;
12
+ /** Groups tags by module. Each list is sorted from newest to oldest, without duplicates. */
13
+ export declare function modulesFromTags(tags: Iterable<string>): Record<string, string[]>;
14
+ /**
15
+ * A first record for a module that has no record yet.
16
+ * Current is the newest stable version and last the one before it.
17
+ * Next stays empty: drafting next is a choice, not something a tag decides.
18
+ * Returns null when the module has no stable version.
19
+ */
20
+ export declare function recordFromTags(module: string, versions: readonly string[], now?: Date | string | number): ModuleRecord | null;
@@ -0,0 +1,56 @@
1
+ import { compareSemver, isSemver } from '../semver.js';
2
+ const SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
3
+ /**
4
+ * Reads a tag of the form `module/vX.Y.Z`, for example `billing/v2.4.0`.
5
+ * The module must be a lower-case slug. Anything else gives null, so tags
6
+ * such as `v1.0.0` or `packages/go/v0.2.0` are ignored.
7
+ */
8
+ export function parseModuleTag(tag) {
9
+ const name = tag.startsWith('refs/tags/') ? tag.slice('refs/tags/'.length) : tag;
10
+ const slash = name.indexOf('/');
11
+ if (slash < 1)
12
+ return null;
13
+ const module = name.slice(0, slash);
14
+ const rest = name.slice(slash + 1);
15
+ if (!SLUG.test(module) || !rest.startsWith('v'))
16
+ return null;
17
+ const version = rest.slice(1);
18
+ return isSemver(version) ? { module, version } : null;
19
+ }
20
+ /** Groups tags by module. Each list is sorted from newest to oldest, without duplicates. */
21
+ export function modulesFromTags(tags) {
22
+ const found = {};
23
+ for (const tag of tags) {
24
+ const parsed = parseModuleTag(tag);
25
+ if (!parsed)
26
+ continue;
27
+ (found[parsed.module] ??= new Set()).add(parsed.version);
28
+ }
29
+ const out = {};
30
+ for (const module of Object.keys(found).sort()) {
31
+ out[module] = [...found[module]].sort((a, b) => compareSemver(b, a));
32
+ }
33
+ return out;
34
+ }
35
+ const isStable = (v) => !/^[^+]*-/.test(v);
36
+ /**
37
+ * A first record for a module that has no record yet.
38
+ * Current is the newest stable version and last the one before it.
39
+ * Next stays empty: drafting next is a choice, not something a tag decides.
40
+ * Returns null when the module has no stable version.
41
+ */
42
+ export function recordFromTags(module, versions, now = new Date()) {
43
+ const stable = versions.filter((v) => isSemver(v) && isStable(v)).sort((a, b) => compareSemver(b, a));
44
+ const unique = stable.filter((v, i) => i === 0 || compareSemver(v, stable[i - 1]) !== 0);
45
+ if (unique.length === 0)
46
+ return null;
47
+ return {
48
+ module,
49
+ last: unique[1] ?? null,
50
+ current: unique[0],
51
+ next: null,
52
+ rollout: 0,
53
+ healthy: true,
54
+ updatedAt: new Date(now).toISOString(),
55
+ };
56
+ }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Checks the `X-Hub-Signature-256` header of a GitHub webhook.
3
+ * Pass the raw body exactly as it arrived. Never throws.
4
+ */
5
+ export declare function verifyWebhookSignature(secret: string, body: string | Uint8Array, signature: string | null | undefined): Promise<boolean>;
@@ -0,0 +1,23 @@
1
+ const encoder = new TextEncoder();
2
+ function toHex(bytes) {
3
+ return Array.from(new Uint8Array(bytes), (b) => b.toString(16).padStart(2, '0')).join('');
4
+ }
5
+ /**
6
+ * Checks the `X-Hub-Signature-256` header of a GitHub webhook.
7
+ * Pass the raw body exactly as it arrived. Never throws.
8
+ */
9
+ export async function verifyWebhookSignature(secret, body, signature) {
10
+ if (!secret || typeof signature !== 'string' || !signature.startsWith('sha256='))
11
+ return false;
12
+ const key = await crypto.subtle.importKey('raw', encoder.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, [
13
+ 'sign',
14
+ ]);
15
+ const data = typeof body === 'string' ? encoder.encode(body) : new Uint8Array(body);
16
+ const expected = `sha256=${toHex(await crypto.subtle.sign('HMAC', key, data))}`;
17
+ if (expected.length !== signature.length)
18
+ return false;
19
+ let diff = 0;
20
+ for (let i = 0; i < expected.length; i++)
21
+ diff |= expected.charCodeAt(i) ^ signature.charCodeAt(i);
22
+ return diff === 0;
23
+ }
@@ -0,0 +1,50 @@
1
+ import { type ModuleRecord, type TransitionOptions } from './types.js';
2
+ export type HealthCheckName = 'errorRate' | 'latency' | 'url';
3
+ /** Limits for one module. Leave a check out to turn it off. */
4
+ export interface HealthChecks {
5
+ /** Highest share of failed requests, from 0 to 1. Fails when errors / requests is above it. */
6
+ maxErrorRate?: number;
7
+ /** Highest latency in milliseconds, usually p95. Fails when the latency is above it. */
8
+ maxLatencyMs?: number;
9
+ /** A URL that must answer with a 2xx status. */
10
+ url?: string;
11
+ /** The error rate is only judged once there are at least this many requests. Default 1. */
12
+ minRequests?: number;
13
+ }
14
+ /** What was measured for the current version. A missing value means that check is skipped. */
15
+ export interface HealthObservation {
16
+ requests?: number;
17
+ errors?: number;
18
+ latencyMs?: number;
19
+ /** HTTP status of the check URL. 0 means it could not be reached. */
20
+ urlStatus?: number;
21
+ }
22
+ export interface HealthFailure {
23
+ check: HealthCheckName;
24
+ /** The measured value: the error rate, the latency or the status. */
25
+ value: number;
26
+ /** The limit it broke, or null for the URL check. */
27
+ limit: number | null;
28
+ }
29
+ export interface HealthVerdict {
30
+ healthy: boolean;
31
+ /** Failed checks, always in the order errorRate, latency, url. */
32
+ failures: HealthFailure[];
33
+ }
34
+ export interface HealthResult {
35
+ /** The record after the check. The same record when nothing changed. */
36
+ record: ModuleRecord;
37
+ verdict: HealthVerdict;
38
+ rolledBack: boolean;
39
+ }
40
+ /** Recorded as `by` in history when the caller gives no name. */
41
+ export declare const HEALTH_ACTOR = "versimo-health";
42
+ /** Judges one observation against the checks. Pure, and the same in every language. */
43
+ export declare function evaluateHealth(checks: HealthChecks, obs: HealthObservation): HealthVerdict;
44
+ /**
45
+ * Judges current and, when it fails, steps back to last on its own.
46
+ * The rollback is recorded in history with the failed checks as the reason,
47
+ * for example `health: errorRate, latency`. With no last there is nothing
48
+ * to go back to, so the record is left as it is and only the verdict says so.
49
+ */
50
+ export declare function checkHealth(record: ModuleRecord, checks: HealthChecks, obs: HealthObservation, opts?: TransitionOptions): HealthResult;
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
+ }
@@ -0,0 +1,12 @@
1
+ export { bucketFor } from './bucket.js';
2
+ export { resolve, resolveVersion } from './resolve.js';
3
+ export { draftNext, promote, rollback, setRollout } from './transitions.js';
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';
7
+ export { compareSemver, isSemver, parseSemver, SEMVER_PATTERN, type ParsedSemver } from './semver.js';
8
+ export { createDeployClient, type DeployClient, type DeployClientOptions, type DeployModule } from './deploy.js';
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';
11
+ export { VersimoProvider, type EvaluationContext, type ResolutionDetails } from './provider.js';
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 ADDED
@@ -0,0 +1,12 @@
1
+ export { bucketFor } from './bucket.js';
2
+ export { resolve, resolveVersion } from './resolve.js';
3
+ export { draftNext, promote, rollback, setRollout } from './transitions.js';
4
+ export { validateRecord } from './validate.js';
5
+ export { checkHealth, evaluateHealth, HEALTH_ACTOR, } from './health.js';
6
+ export { createHealthMonitor, } from './monitor.js';
7
+ export { compareSemver, isSemver, parseSemver, SEMVER_PATTERN } from './semver.js';
8
+ export { createDeployClient } from './deploy.js';
9
+ export { createClient } from './client.js';
10
+ export { postHogFlagKey, postHogRollout, rolloutFromFlag, POSTHOG_DISTINCT_ID, } from './posthog.js';
11
+ export { VersimoProvider } from './provider.js';
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;