tockward 0.1.0 → 0.2.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/README.md CHANGED
@@ -17,12 +17,14 @@ Both give you the same `tockward` command. No dependencies.
17
17
 
18
18
  ```sh
19
19
  tockward ping <token> # report a successful run
20
- tockward fail <token> # report a failed run
20
+ tockward fail <token> "disk full" # report a failed run, optionally why
21
21
  tockward run <token> -- ./backup.sh # run a command, then report success or failure
22
22
  ```
23
23
 
24
24
  `tockward run` passes the command's output through, sends its duration along, and exits
25
- with the command's own exit code, so it drops straight into a crontab:
25
+ with the command's own exit code, so it drops straight into a crontab. When the command
26
+ fails, the last lines of its output go along too, so the alert says why
27
+ (`exited with code 3: error: disk full`):
26
28
 
27
29
  ```cron
28
30
  0 3 * * * tockward run abc123 -- /usr/local/bin/backup.sh
@@ -30,18 +32,42 @@ with the command's own exit code, so it drops straight into a crontab:
30
32
 
31
33
  `<token>` is the monitor's token, or its full ping URL copied from the dashboard.
32
34
 
35
+ ## Git repos
36
+
37
+ `tockward git` checks the git repos on a server and reports ok, or a failure saying what's
38
+ wrong. It only reads (no fetch, no pull), uses the server's own git access, and sends just
39
+ a short summary: repo, branch and commit names, never file names or code.
40
+
41
+ ```cron
42
+ # Git server: every repo under /srv/git has the same branches and tags as GitHub/GitLab
43
+ 0 * * * * tockward git <token> /srv/git --behind-after 12h
44
+
45
+ # Production: nothing changed by hand, on the latest commit of main
46
+ */15 * * * * tockward git <token> /var/www/app --deploy --branch main --behind-after 30m
47
+ ```
48
+
49
+ | Option | Meaning |
50
+ |---|---|
51
+ | `--deploy` | the folder is one checkout (production) instead of a folder of repos |
52
+ | `--branch <name>` | the branch it should be on (deploy; default: the current one) |
53
+ | `--remote <name>` | compare with this remote (default: the GitHub, GitLab or Bitbucket one, else `origin`) |
54
+ | `--behind-after <t>` | only alert when it has been behind for longer than `t` (`30m`, `2h`, `1d`), so a deploy or mirror sync in progress doesn't alert |
55
+ | `--depth <n>` | how deep to look for repos under the folder (default 3) |
56
+
57
+ Exit code 0 when all is well, 1 when something's wrong, 2 when the check itself couldn't run.
58
+
33
59
  ## In code
34
60
 
35
61
  ```js
36
62
  const tockward = require('tockward');
37
63
  await tockward.ping('abc123');
38
- await tockward.fail('abc123');
64
+ await tockward.fail('abc123', { message: 'disk full' });
39
65
  ```
40
66
 
41
67
  ```python
42
68
  import tockward
43
69
  tockward.ping("abc123")
44
- tockward.fail("abc123")
70
+ tockward.fail("abc123", message="disk full")
45
71
  ```
46
72
 
47
73
  Delivery is retried twice with a 10-second timeout per attempt; an unknown token fails at once.
@@ -53,6 +79,7 @@ It's just an HTTP request, so `curl` works too:
53
79
  ```sh
54
80
  curl -fsS https://ping.tockward.com/v1/beat/<token> # success
55
81
  curl -fsS https://ping.tockward.com/v1/beat/<token>/fail # failure
82
+ curl -fsS -d "disk full" https://ping.tockward.com/v1/beat/<token>/fail # failure, with why
56
83
  ```
57
84
 
58
85
  ## Settings
package/bin/tockward.js CHANGED
@@ -1,17 +1,33 @@
1
1
  #!/usr/bin/env node
2
2
  'use strict';
3
3
  const { spawn } = require('child_process');
4
- const { ping, fail } = require('..');
4
+ const os = require('os');
5
+ const { ping, fail, OutputTail, failureMessage } = require('..');
5
6
  const { version } = require('../package.json');
6
7
 
7
8
  const USAGE = `Tockward: know when your cron jobs, scripts and devices go silent.
8
9
 
9
10
  Usage:
10
11
  tockward ping <token> report a successful run
11
- tockward fail <token> report a failed run
12
+ tockward fail <token> [message] report a failed run, optionally why
12
13
  tockward run <token> -- <command> run a command, then report success or
13
- failure (with its duration); exits with
14
- the command's exit code
14
+ failure (with its duration, and on
15
+ failure its last output lines); exits
16
+ with the command's exit code
17
+ tockward git <token> [folder] [options]
18
+ check git repos and report: ok, or
19
+ fail with what's wrong (read-only)
20
+
21
+ git options:
22
+ (default) every repo under folder (a Git server) must have the
23
+ same branches and tags as its hosted remote
24
+ --deploy folder is a checkout (production): nothing changed by
25
+ hand, on the remote's latest commit
26
+ --branch <name> the branch it should be on (deploy)
27
+ --remote <name> compare with this remote (default: GitHub, GitLab or
28
+ Bitbucket, else origin)
29
+ --behind-after <t> only alert when behind for longer than t (30m, 2h)
30
+ --depth <n> how deep to look for repos (default 3)
15
31
 
16
32
  <token> is the monitor's token or its full ping URL.
17
33
  Set TOCKWARD_URL to use another server. https://tockward.com`;
@@ -25,20 +41,44 @@ async function main(argv) {
25
41
  if (!token) { warn('missing token'); console.error(USAGE); return 2; }
26
42
 
27
43
  if (cmd === 'ping' || cmd === 'fail') {
28
- try { await (cmd === 'ping' ? ping : fail)(token); return 0; }
44
+ const message = cmd === 'fail' ? rest.join(' ').trim() : '';
45
+ try { await (cmd === 'ping' ? ping : fail)(token, { message }); return 0; }
29
46
  catch (err) { warn(`could not report: ${err.message}`); return 1; }
30
47
  }
31
48
 
49
+ if (cmd === 'git') {
50
+ const result = require('../git').run(token, rest);
51
+ for (const line of result.lines) (result.code ? process.stderr : process.stdout).write(`${line}\n`);
52
+ try { await (result.code === 0 ? ping : fail)(token, { message: result.message }); }
53
+ catch (err) { warn(`could not report: ${err.message}`); return result.code || 1; }
54
+ return result.code;
55
+ }
56
+
32
57
  if (cmd === 'run') {
33
58
  const command = rest[0] === '--' ? rest.slice(1) : rest;
34
59
  if (!command.length) { warn('nothing to run; use: tockward run <token> -- <command>'); return 2; }
35
60
  const started = Date.now();
61
+ // Output still goes to the terminal or cron log as it comes; the last
62
+ // lines are kept for the failure message.
63
+ const tail = new OutputTail();
64
+ let headline = '';
36
65
  const code = await new Promise(resolve => {
37
- const child = spawn(command[0], command.slice(1), { stdio: 'inherit' });
38
- child.on('error', err => { warn(`could not start ${command[0]}: ${err.message}`); resolve(127); });
39
- child.on('exit', (c, signal) => resolve(signal ? 128 : c));
66
+ const child = spawn(command[0], command.slice(1), { stdio: ['inherit', 'pipe', 'pipe'] });
67
+ child.stdout.on('data', d => { process.stdout.write(d); tail.write(d); });
68
+ child.stderr.on('data', d => { process.stderr.write(d); tail.write(d); });
69
+ child.on('error', err => {
70
+ headline = `could not start ${command[0]}: ${err.message}`;
71
+ warn(headline);
72
+ resolve(127);
73
+ });
74
+ child.on('close', (c, signal) => {
75
+ if (headline) return;
76
+ headline = signal ? `killed by ${signal}` : `exited with code ${c}`;
77
+ resolve(signal ? 128 + (os.constants.signals[signal] || 0) : c);
78
+ });
40
79
  });
41
- try { await (code === 0 ? ping : fail)(token, { ms: Date.now() - started }); }
80
+ const ms = Date.now() - started;
81
+ try { await (code === 0 ? ping(token, { ms }) : fail(token, { ms, message: failureMessage(headline, tail.last) })); }
42
82
  catch (err) { warn(`could not report: ${err.message}`); }
43
83
  return code;
44
84
  }
package/git.js ADDED
@@ -0,0 +1,262 @@
1
+ 'use strict';
2
+ // `tockward git`: checks repos on this machine against their remote and
3
+ // returns what's wrong, for a heartbeat. Read-only: only git status,
4
+ // rev-parse, for-each-ref, cat-file, merge-base and ls-remote; never fetch
5
+ // or pull. Uses this machine's own git setup and access.
6
+ //
7
+ // mirror (default) every repo under the folder (a Git server's repos):
8
+ // are its branches and tags the same as the hosted
9
+ // remote (GitHub, GitLab, Bitbucket, else origin)?
10
+ // deploy (--deploy) one checkout (a production server): nothing changed
11
+ // by hand, on the expected branch, on the remote's
12
+ // latest commit.
13
+ //
14
+ // Same behaviour and output as the python client (tockward/git.py).
15
+
16
+ const { spawnSync } = require('child_process');
17
+ const crypto = require('crypto');
18
+ const fs = require('fs');
19
+ const os = require('os');
20
+ const path = require('path');
21
+
22
+ const HOSTED = /(^|[@/.])(github\.com|gitlab\.com|bitbucket\.org)[:/]/i;
23
+ const GIT_TIMEOUT = 60000;
24
+
25
+ class CheckError extends Error {}
26
+
27
+ function git(dir, args, { allowFail = false } = {}) {
28
+ const r = spawnSync('git', ['-C', dir, ...args], {
29
+ encoding: 'utf8',
30
+ timeout: GIT_TIMEOUT,
31
+ stdio: ['ignore', 'pipe', 'pipe'],
32
+ env: { ...process.env, GIT_TERMINAL_PROMPT: '0', LC_ALL: 'C' },
33
+ });
34
+ if (r.error) {
35
+ if (r.error.code === 'ENOENT') throw new CheckError('git is not installed');
36
+ if (allowFail) return null;
37
+ throw new CheckError(r.error.code === 'ETIMEDOUT' ? `git ${args[0]} timed out` : r.error.message);
38
+ }
39
+ if (r.status !== 0) {
40
+ if (allowFail) return null;
41
+ const lines = (r.stderr || '').split('\n').map(l => l.trim()).filter(Boolean);
42
+ const why = lines.find(l => /^(fatal|error):/.test(l)) || lines[0] || `exit ${r.status}`;
43
+ throw new CheckError(why.replace(/^(fatal|error): /, ''));
44
+ }
45
+ return r.stdout;
46
+ }
47
+
48
+ // "30m", "2h", "90s", "1d" → seconds.
49
+ function parseDuration(text) {
50
+ const m = /^(\d+)\s*([smhd]?)$/i.exec(String(text || '').trim());
51
+ if (!m) throw new CheckError(`can't read the duration "${text}" (use e.g. 30m, 2h, 1d)`);
52
+ return Number(m[1]) * { '': 60, s: 1, m: 60, h: 3600, d: 86400 }[m[2].toLowerCase()];
53
+ }
54
+
55
+ function parseArgs(args) {
56
+ const o = { folder: '.', deploy: false, branch: null, remote: null, behindAfter: 0, depth: 3 };
57
+ for (let i = 0; i < args.length; i++) {
58
+ const a = args[i];
59
+ const value = () => {
60
+ if (i + 1 >= args.length) throw new CheckError(`${a} needs a value`);
61
+ return args[++i];
62
+ };
63
+ if (a === '--deploy') o.deploy = true;
64
+ else if (a === '--branch') o.branch = value();
65
+ else if (a === '--remote') o.remote = value();
66
+ else if (a === '--behind-after') o.behindAfter = parseDuration(value());
67
+ else if (a === '--depth') o.depth = Math.max(0, parseInt(value(), 10) || 0);
68
+ else if (a.startsWith('--')) throw new CheckError(`unknown option ${a}`);
69
+ else o.folder = a;
70
+ }
71
+ return o;
72
+ }
73
+
74
+ const isRepo = dir => fs.existsSync(path.join(dir, '.git'))
75
+ || (fs.existsSync(path.join(dir, 'HEAD')) && fs.existsSync(path.join(dir, 'objects')) && fs.existsSync(path.join(dir, 'refs')));
76
+
77
+ // Repos at or under the folder, up to depth levels down; hidden folders and
78
+ // node_modules are skipped, and nothing inside a repo is searched.
79
+ function findRepos(root, depth) {
80
+ const found = [];
81
+ const walk = (dir, level) => {
82
+ if (isRepo(dir)) return found.push(dir);
83
+ if (level >= depth) return;
84
+ let entries;
85
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; }
86
+ for (const e of entries.sort((a, b) => a.name.localeCompare(b.name))) {
87
+ if (e.isDirectory() && !e.name.startsWith('.') && e.name !== 'node_modules') walk(path.join(dir, e.name), level + 1);
88
+ }
89
+ };
90
+ walk(root, 0);
91
+ return found;
92
+ }
93
+
94
+ // The remote to compare with: --remote, else a hosted one, else origin.
95
+ function pickRemote(dir, wanted) {
96
+ const names = (git(dir, ['remote']) || '').split('\n').filter(Boolean);
97
+ if (wanted) return names.includes(wanted) ? wanted : null;
98
+ for (const n of names) {
99
+ const url = git(dir, ['remote', 'get-url', n], { allowFail: true }) || '';
100
+ if (HOSTED.test(url.trim())) return n;
101
+ }
102
+ return names.includes('origin') ? 'origin' : null;
103
+ }
104
+
105
+ function refMap(text) {
106
+ const map = new Map();
107
+ for (const line of (text || '').split('\n')) {
108
+ const [hash, ref] = line.split(/\s+/);
109
+ if (hash && ref && !ref.endsWith('^{}')) map.set(ref, hash);
110
+ }
111
+ return map;
112
+ }
113
+
114
+ const hasObject = (dir, hash) => git(dir, ['cat-file', '-e', `${hash}^{commit}`], { allowFail: true }) !== null;
115
+ const isAncestor = (dir, a, b) => git(dir, ['merge-base', '--is-ancestor', a, b], { allowFail: true }) !== null;
116
+ const short = h => h.slice(0, 7);
117
+ const shortRef = r => r.replace(/^refs\/(heads|tags)\//, '');
118
+
119
+ function names(list) {
120
+ const shown = list.slice(0, 3).join(', ');
121
+ return list.length > 3 ? `${shown} and ${list.length - 3} more` : shown;
122
+ }
123
+
124
+ // One repo against its remote. Returns { problems: [{kind, text}], skipped }.
125
+ function checkMirror(dir, label, remoteWanted) {
126
+ const remote = pickRemote(dir, remoteWanted);
127
+ if (!remote && remoteWanted) return { problems: [{ kind: 'error', text: `${label}: no remote ${remoteWanted}` }] };
128
+ if (!remote) return { skipped: true };
129
+ let theirs;
130
+ try {
131
+ theirs = refMap(git(dir, ['ls-remote', '--heads', '--tags', remote]));
132
+ } catch (err) {
133
+ return { problems: [{ kind: 'error', text: `${label}: ${remote} unreachable (${err.message})` }] };
134
+ }
135
+ const ours = refMap(git(dir, ['for-each-ref', '--format=%(objectname) %(refname)', 'refs/heads', 'refs/tags']));
136
+ const behind = [], ahead = [], differs = [];
137
+ for (const [ref, hash] of theirs) {
138
+ const mine = ours.get(ref);
139
+ if (mine === hash) continue;
140
+ const name = shortRef(ref);
141
+ if (!mine) behind.push(name);
142
+ else if (ref.startsWith('refs/tags/')) differs.push(`tag ${name}`);
143
+ else if (!hasObject(dir, hash)) behind.push(name);
144
+ else if (isAncestor(dir, mine, hash)) behind.push(name);
145
+ else if (isAncestor(dir, hash, mine)) ahead.push(name);
146
+ else differs.push(name);
147
+ }
148
+ const problems = [];
149
+ if (differs.length) problems.push({ kind: 'differs', text: `${label}: ${names(differs)} differ${differs.length === 1 ? 's' : ''} from ${remote}` });
150
+ if (behind.length) problems.push({ kind: 'behind', key: label, text: `${label}: ${names(behind)} behind ${remote}` });
151
+ if (ahead.length) problems.push({ kind: 'ahead', text: `${label}: ${names(ahead)} ahead of ${remote}` });
152
+ return { problems };
153
+ }
154
+
155
+ function checkDeploy(dir, o) {
156
+ if (!fs.existsSync(path.join(dir, '.git'))) throw new CheckError(`${dir} is not a git checkout`);
157
+ const problems = [];
158
+ const changed = git(dir, ['--no-optional-locks', 'status', '--porcelain']).split('\n').filter(Boolean).length;
159
+ if (changed) problems.push({ kind: 'changed', text: `${changed} file${changed === 1 ? '' : 's'} changed on the server` });
160
+
161
+ const remote = pickRemote(dir, o.remote);
162
+ if (!remote) throw new CheckError(o.remote ? `${dir} has no remote ${o.remote}` : `${dir} has no remote to compare with`);
163
+ const current = (git(dir, ['symbolic-ref', '--short', '-q', 'HEAD'], { allowFail: true }) || '').trim();
164
+ const head = git(dir, ['rev-parse', 'HEAD']).trim();
165
+ let branch = o.branch || current;
166
+ if (!branch) {
167
+ // Detached HEAD without --branch: the remote's default branch.
168
+ try {
169
+ const sym = /ref: refs\/heads\/(\S+)\s+HEAD/.exec(git(dir, ['ls-remote', '--symref', remote, 'HEAD']));
170
+ branch = sym ? sym[1] : null;
171
+ } catch (err) {
172
+ return { problems: [...problems, { kind: 'error', text: `${remote} unreachable (${err.message})` }] };
173
+ }
174
+ if (!branch) throw new CheckError('detached HEAD: say which branch with --branch');
175
+ }
176
+ if (o.branch && current && current !== o.branch) problems.push({ kind: 'branch', text: `on branch ${current}, expected ${o.branch}` });
177
+
178
+ let latest;
179
+ try {
180
+ latest = refMap(git(dir, ['ls-remote', '--heads', remote, branch])).get(`refs/heads/${branch}`);
181
+ } catch (err) {
182
+ return { problems: [...problems, { kind: 'error', text: `${remote} unreachable (${err.message})` }] };
183
+ }
184
+ if (!latest) problems.push({ kind: 'error', text: `${remote} has no branch ${branch}` });
185
+ else if (latest !== head) {
186
+ if (hasObject(dir, latest) && isAncestor(dir, latest, head)) {
187
+ const n = parseInt(git(dir, ['rev-list', '--count', `${latest}..${head}`]), 10) || 0;
188
+ problems.push({ kind: 'ahead', text: `${n} commit${n === 1 ? '' : 's'} on the server that ${remote}/${branch} doesn't have` });
189
+ } else {
190
+ problems.push({ kind: 'behind', key: 'deploy', text: `not on the latest ${branch}: on ${short(head)}, ${remote}/${branch} is at ${short(latest)}` });
191
+ }
192
+ }
193
+ return { problems, branch, head };
194
+ }
195
+
196
+ // --behind-after: "behind" only counts once it has lasted that long; the
197
+ // first time seen is kept per token and folder in ~/.cache/tockward/.
198
+ function applyBehindAfter(problems, seconds, token, folder) {
199
+ if (!seconds) return { problems, waiting: [] };
200
+ const dir = path.join(process.env.XDG_CACHE_HOME || path.join(os.homedir(), '.cache'), 'tockward');
201
+ const file = path.join(dir, `git-${crypto.createHash('sha256').update(`${token}\n${folder}`).digest('hex').slice(0, 16)}.json`);
202
+ let seen = {};
203
+ try { seen = JSON.parse(fs.readFileSync(file, 'utf8')); } catch {}
204
+ const now = Math.floor(Date.now() / 1000);
205
+ const next = {}, kept = [], waiting = [];
206
+ for (const p of problems) {
207
+ if (p.kind !== 'behind') { kept.push(p); continue; }
208
+ const since = seen[p.key] || now;
209
+ next[p.key] = since;
210
+ if (now - since >= seconds) kept.push(p);
211
+ else waiting.push(p);
212
+ }
213
+ try { fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(file, JSON.stringify(next)); } catch {}
214
+ return { problems: kept, waiting };
215
+ }
216
+
217
+ const ORDER = ['error', 'differs', 'changed', 'branch', 'ahead', 'behind'];
218
+ const fmtDuration = s => (s % 86400 === 0 ? `${s / 86400} d` : s % 3600 === 0 ? `${s / 3600} h` : s >= 60 ? `${Math.round(s / 60)} min` : `${s} s`);
219
+
220
+ // Runs the check. Returns { code, message, lines }: code 0 ok, 1 problems,
221
+ // 2 the check itself failed; message is what goes to Tockward.
222
+ function run(token, args) {
223
+ let o;
224
+ try {
225
+ o = parseArgs(args);
226
+ const folder = path.resolve(o.folder);
227
+ if (!fs.existsSync(folder)) throw new CheckError(`${o.folder} does not exist`);
228
+ let problems = [], summary;
229
+ if (o.deploy) {
230
+ const r = checkDeploy(folder, o);
231
+ problems = r.problems;
232
+ summary = r.head ? `on ${r.branch} at ${short(r.head)}` : 'checked';
233
+ } else {
234
+ const repos = findRepos(folder, o.depth);
235
+ if (!repos.length) throw new CheckError(`no git repos found in ${o.folder}`);
236
+ let skipped = 0;
237
+ for (const dir of repos) {
238
+ const label = path.relative(folder, dir) || path.basename(dir);
239
+ const r = checkMirror(dir, label, o.remote);
240
+ if (r.skipped) skipped++;
241
+ else problems.push(...r.problems);
242
+ }
243
+ const checked = repos.length - skipped;
244
+ summary = `${checked} repo${checked === 1 ? '' : 's'} checked${skipped ? `, ${skipped} without a remote skipped` : ''}`;
245
+ }
246
+ const { problems: kept, waiting } = applyBehindAfter(problems, o.behindAfter, token, folder);
247
+ kept.sort((a, b) => ORDER.indexOf(a.kind) - ORDER.indexOf(b.kind));
248
+ if (!kept.length) {
249
+ const ok = waiting.length
250
+ ? `ok for now: ${summary}; behind for less than ${fmtDuration(o.behindAfter)}`
251
+ : `${o.deploy ? 'up to date' : 'in sync'}: ${summary}`;
252
+ return { code: 0, message: ok, lines: [ok, ...waiting.map(p => ` waiting: ${p.text}`)] };
253
+ }
254
+ const lines = kept.map(p => p.text);
255
+ return { code: 1, message: lines.join('\n'), lines };
256
+ } catch (err) {
257
+ if (!(err instanceof CheckError)) throw err;
258
+ return { code: 2, message: `git check failed: ${err.message}`, lines: [`git check failed: ${err.message}`] };
259
+ }
260
+ }
261
+
262
+ module.exports = { run, parseDuration, parseArgs, findRepos };
package/index.js CHANGED
@@ -5,6 +5,7 @@
5
5
  // await tockward.ping('abc123'); // "I ran"
6
6
  // await tockward.fail('abc123'); // "I failed"
7
7
  // await tockward.ping('abc123', { ms: 4200 }); // with the run's duration
8
+ // await tockward.fail('abc123', { message: 'disk full' }); // say why
8
9
  //
9
10
  // A token can also be a full ping URL (https://.../v1/beat/<token>), so URLs
10
11
  // copied from the dashboard work as they are. TOCKWARD_URL overrides the base.
@@ -25,13 +26,18 @@ function beatUrl(token, ok, ms) {
25
26
  return url;
26
27
  }
27
28
 
28
- async function send(token, ok, { ms, timeout = 10000, retries = 2 } = {}) {
29
+ // The server keeps up to 500 characters; the first line is the alert's reason.
30
+ const MESSAGE_MAX = 500;
31
+
32
+ async function send(token, ok, { ms, message, timeout = 10000, retries = 2 } = {}) {
29
33
  const url = beatUrl(token, ok, ms);
34
+ const body = message ? String(message).slice(0, MESSAGE_MAX) : undefined;
35
+ const headers = body ? { 'Content-Type': 'text/plain; charset=utf-8' } : undefined;
30
36
  let lastError;
31
37
  for (let attempt = 0; attempt <= retries; attempt++) {
32
38
  if (attempt) await new Promise(r => setTimeout(r, 1000 * attempt));
33
39
  try {
34
- const res = await fetch(url, { method: 'POST', signal: AbortSignal.timeout(timeout) });
40
+ const res = await fetch(url, { method: 'POST', headers, body, signal: AbortSignal.timeout(timeout) });
35
41
  if (res.ok) return true;
36
42
  if (res.status === 404) throw Object.assign(new Error('unknown monitor (check the token)'), { final: true });
37
43
  lastError = new Error(`HTTP ${res.status}`);
@@ -43,7 +49,41 @@ async function send(token, ok, { ms, timeout = 10000, retries = 2 } = {}) {
43
49
  throw lastError;
44
50
  }
45
51
 
52
+ // Remembers the last lines a command printed, for the failure message.
53
+ // Colour codes and progress-bar redraws (\r) are left out.
54
+ class OutputTail {
55
+ constructor(maxLines = 20) { this.max = maxLines; this.lines = []; this.partial = ''; }
56
+ write(chunk) {
57
+ const text = this.partial + String(chunk).replace(/\x1b\[[0-9;?]*[ -\/]*[@-~]/g, '');
58
+ const parts = text.split('\n');
59
+ this.partial = parts.pop().slice(-1000);
60
+ for (const p of parts) this.push(p);
61
+ }
62
+ push(line) {
63
+ const clean = line.split('\r').filter(Boolean).pop() || '';
64
+ if (!clean.trim()) return;
65
+ this.lines.push(clean.trimEnd().slice(0, 300));
66
+ if (this.lines.length > this.max) this.lines.shift();
67
+ }
68
+ get last() { if (this.partial) { this.push(this.partial); this.partial = ''; } return this.lines; }
69
+ }
70
+
71
+ // "exited with code 3: <last line>", then as much of the last output as fits.
72
+ function failureMessage(headline, lines) {
73
+ const first = (lines.length ? `${headline}: ${lines[lines.length - 1].trim()}` : headline).slice(0, 200);
74
+ const kept = [];
75
+ let size = first.length + '\n\nLast output:'.length;
76
+ for (let i = lines.length - 1; i >= 0; i--) {
77
+ if (size + lines[i].length + 1 > MESSAGE_MAX) break;
78
+ size += lines[i].length + 1;
79
+ kept.unshift(lines[i]);
80
+ }
81
+ return kept.length ? `${first}\n\nLast output:\n${kept.join('\n')}` : first;
82
+ }
83
+
46
84
  module.exports = {
85
+ OutputTail,
86
+ failureMessage,
47
87
  ping: (token, opts) => send(token, true, opts),
48
88
  fail: (token, opts) => send(token, false, opts),
49
89
  beatUrl,
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "tockward",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Heartbeat client for Tockward: know when your cron jobs, scripts and devices go silent.",
5
5
  "main": "index.js",
6
6
  "bin": { "tockward": "bin/tockward.js" },
7
- "files": ["index.js", "bin/", "README.md", "LICENSE"],
7
+ "files": ["index.js", "git.js", "bin/", "README.md", "LICENSE"],
8
8
  "engines": { "node": ">=18" },
9
9
  "keywords": ["cron", "monitoring", "heartbeat", "dead-mans-switch", "cronjob", "uptime", "alerting"],
10
10
  "homepage": "https://tockward.com",