ituran-axi 0.1.3 → 0.1.5

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
@@ -109,6 +109,14 @@ ituran-axi handles these, and says so in its output where it matters:
109
109
  - Keypad driver codes above 2^53 stay exact.
110
110
  - A model year or odometer of 0 means "not set".
111
111
 
112
+ Commands for the same host user run their HTTP reads one command at a time, including sign-in. Requests within a command keep the existing limit of two in flight, starting at least 400 ms apart. The next command waits at least 400 ms after the previous command finishes. The command lock is `/tmp/ituran-axi-<uid>/command.lock`, independent of `TMPDIR`, `HOME` and `XDG_CACHE_HOME`. Set `ITURAN_AXI_LOCK_DIR` to override its directory. Wrappers with separate filesystem namespaces must set this to the same writable directory shared by every command; keep it stable across accounts and tokens. A busy lock returns `busy` without sending a request. Wait for the other command to finish before trying again.
113
+
114
+ The lock records its owner's PID, hostname and a random token. The holder refreshes its heartbeat every two seconds. A dead PID on the same host, or a heartbeat missing for ten seconds, permits automatic recovery. Release checks the owner token, so an old holder cannot remove a replacement lock. If the selected lock directory is unavailable, reads continue without a process lock, with the same output. Cleanup errors never replace a successful result. Separate users and hosts need external coordination; the gap between commands also depends on writable lock storage.
115
+
116
+ Network commands have a 25-second overall budget, including lock waiting, sign-in, pacing, retries and all pages or windows. `COMIS_DEADLINE` can shorten this budget, with a one-second margin for output and cleanup. Reads and sign-in also have individual timeouts (60 and 30 seconds), shortened to the remaining command budget. Timeouts cover the response body, abort the request and cancel the body. The CLI flushes its error and exits, releasing Node's proxy dispatcher sockets even if a proxy has not answered CONNECT.
117
+
118
+ `trips` accepts at most 56 days per command, including `--by plate`. Longer ranges return a usage error before any trip requests. Split them into shorter windows. `--limit` limits output rows; calculating the exact count still reads each weekly window. This bound keeps counts, page hints and totals consistent for accepted windows.
119
+
112
120
  ## Output and errors
113
121
 
114
122
  - **Size:** a value is cut at 500 characters and the whole output at about 4,000. `--full` lifts both limits, up to 256 KB.
@@ -127,6 +135,7 @@ ituran-axi handles these, and says so in its output where it matters:
127
135
  | `not_entitled`, `feature_off`, `needs_app_id` | This account does not include that service |
128
136
  | `rejected` | Ituran refused the request; its message is shown |
129
137
  | `rate_limited`, `ituran_error`, `unreachable` | Ituran limited the request, failed, or could not be reached |
138
+ | `busy` | Another local command holds the process lock. Wait for it to finish before trying again. |
130
139
  | `reconnect_needed`, `refused` | Inside Comis: the owner must reconnect, or the Gate refused |
131
140
  | `output_too_large` | Even `--full` would exceed 256 KB; narrow the query |
132
141
  | `internal_error` | A bug in ituran-axi; please [report it](https://github.com/comisai/ituran-axi/issues) |
@@ -7,7 +7,7 @@ process.stdout.on('error', (error) => {
7
7
  process.exit(0);
8
8
  throw error;
9
9
  });
10
- process.exitCode = await main(process.argv.slice(2), {
10
+ const code = await main(process.argv.slice(2), {
11
11
  stdout: (text) => {
12
12
  process.stdout.write(text);
13
13
  },
@@ -15,3 +15,8 @@ process.exitCode = await main(process.argv.slice(2), {
15
15
  now: () => new Date(),
16
16
  http: defaultDeps,
17
17
  });
18
+ // Node's environment-proxy dispatcher can keep a CONNECT socket alive even
19
+ // after fetch has aborted. This is a one-command process: once cleanup has
20
+ // finished and stdout has drained, exit to release the dispatcher and sockets.
21
+ // Setting only exitCode leaves that socket holding the process open.
22
+ process.stdout.end(() => process.exit(code));
package/dist/cli/run.js CHANGED
@@ -3,6 +3,7 @@
3
3
  import { encode } from '@toon-format/toon';
4
4
  import { cacheDir, noteAvailable, noteUnavailable } from '../account.js';
5
5
  import { forgetToken } from '../auth.js';
6
+ import { withCommandLock } from '../command-lock.js';
6
7
  import { alerts, event, events, groups } from '../commands/catalog.js';
7
8
  import { centers } from '../commands/centers.js';
8
9
  import { driver, drivers } from '../commands/drivers.js';
@@ -142,7 +143,7 @@ export const COMMANDS = [
142
143
  page: PAGE,
143
144
  full: FULL,
144
145
  },
145
- summary: 'Trips in a window, default the last 24h',
146
+ summary: 'Trips, default 24h, at most 56 days',
146
147
  run: trips,
147
148
  },
148
149
  {
@@ -485,6 +486,7 @@ function remember(spec, io, error) {
485
486
  }
486
487
  }
487
488
  export async function main(argv, io) {
489
+ const commandDeadline = Date.now() + 25_000;
488
490
  let spec = HOME;
489
491
  let usageText = `${BIN} [command] [flags]`;
490
492
  try {
@@ -526,7 +528,23 @@ export async function main(argv, io) {
526
528
  io.stdout(commandHelp(found));
527
529
  return 0;
528
530
  }
529
- const out = await spec.run({ ...parsed, io });
531
+ // Help and local logout do not need network serialization. Validate the
532
+ // connection before creating a lock so missing settings stay actionable.
533
+ let out;
534
+ if (spec.name === 'logout') {
535
+ out = await spec.run({ ...parsed, io });
536
+ }
537
+ else {
538
+ const settings = connected(io.env);
539
+ const deadline = Math.min(commandDeadline, settings.deadline ?? Infinity);
540
+ // One deadline covers lock waiting, sign-in, pacing, retries and every
541
+ // page/window. A task deadline further in the future cannot extend it.
542
+ const commandIo = {
543
+ ...io,
544
+ env: { ...io.env, COMIS_DEADLINE: String(deadline) },
545
+ };
546
+ out = await withCommandLock(commandIo.env, deadline, () => spec.run({ ...parsed, io: commandIo }));
547
+ }
530
548
  remember(spec, io, null);
531
549
  io.stdout(out);
532
550
  return 0;
@@ -0,0 +1,228 @@
1
+ // One network command at a time per host user, across accounts and tokens.
2
+ // A heartbeat lease and owner token let killed processes recover without
3
+ // deleting or refreshing a replacement owner's lock.
4
+ import { randomUUID } from 'node:crypto';
5
+ import { closeSync, fstatSync, futimesSync, linkSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeFileSync, } from 'node:fs';
6
+ import { hostname } from 'node:os';
7
+ import { join } from 'node:path';
8
+ import { setTimeout as sleep } from 'node:timers/promises';
9
+ import { AxiError } from './errors.js';
10
+ import { GAP_MS } from './pace.js';
11
+ export const LOCK_WAIT_MS = 30_000;
12
+ const POLL_MS = 100;
13
+ const HEARTBEAT_MS = 2000;
14
+ const LEASE_MS = 10_000;
15
+ function snapshot(file) {
16
+ const fd = openSync(file, 'r');
17
+ try {
18
+ const stat = fstatSync(fd);
19
+ let owner;
20
+ try {
21
+ const value = JSON.parse(readFileSync(fd, 'utf8'));
22
+ if (Number.isSafeInteger(value?.pid) &&
23
+ value.pid > 0 &&
24
+ typeof value.hostname === 'string' &&
25
+ typeof value.token === 'string' &&
26
+ value.token.length > 0)
27
+ owner = value;
28
+ }
29
+ catch {
30
+ // An interrupted creation or an old-format file still has a lease.
31
+ }
32
+ return { stat, owner };
33
+ }
34
+ finally {
35
+ closeSync(fd);
36
+ }
37
+ }
38
+ function stale(value) {
39
+ if (Date.now() - value.stat.mtimeMs > LEASE_MS)
40
+ return true;
41
+ if (value.owner?.hostname === hostname()) {
42
+ try {
43
+ process.kill(value.owner.pid, 0);
44
+ }
45
+ catch (error) {
46
+ return error.code === 'ESRCH';
47
+ }
48
+ }
49
+ return false;
50
+ }
51
+ /** Move out of the way, then re-check the inode, owner and heartbeat. */
52
+ function recover(lock) {
53
+ const before = snapshot(lock);
54
+ if (!stale(before))
55
+ return;
56
+ const moved = `${lock}.${randomUUID()}.stale`;
57
+ renameSync(lock, moved);
58
+ try {
59
+ const after = snapshot(moved);
60
+ if (before.stat.dev === after.stat.dev &&
61
+ before.stat.ino === after.stat.ino &&
62
+ before.owner?.token === after.owner?.token &&
63
+ stale(after))
64
+ return;
65
+ // A heartbeat or another contender changed the lock before the rename.
66
+ // Restore without overwriting any owner that has since acquired the path.
67
+ linkSync(moved, lock);
68
+ }
69
+ finally {
70
+ rmSync(moved, { force: true });
71
+ }
72
+ }
73
+ const busy = () => new AxiError('busy', 'Another ituran-axi command is running. Wait for it to finish, then run this command again.');
74
+ async function acquire(dir, until, owner) {
75
+ const lock = join(dir, 'command.lock');
76
+ try {
77
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
78
+ }
79
+ catch {
80
+ return null;
81
+ }
82
+ for (;;) {
83
+ if (performance.now() >= until)
84
+ throw busy();
85
+ let fd;
86
+ try {
87
+ fd = openSync(lock, 'wx', 0o600);
88
+ }
89
+ catch (error) {
90
+ if (error.code !== 'EEXIST')
91
+ return null;
92
+ try {
93
+ recover(lock);
94
+ }
95
+ catch (error) {
96
+ const code = error.code;
97
+ if (code !== 'ENOENT' && code !== 'EEXIST')
98
+ return null;
99
+ }
100
+ await sleep(Math.min(POLL_MS, Math.max(0, until - performance.now())));
101
+ continue;
102
+ }
103
+ try {
104
+ writeFileSync(fd, JSON.stringify(owner));
105
+ return { fd, lock, next: join(dir, 'command.next') };
106
+ }
107
+ catch {
108
+ try {
109
+ const current = snapshot(lock).stat;
110
+ const created = fstatSync(fd);
111
+ if (current.dev === created.dev && current.ino === created.ino)
112
+ rmSync(lock, { force: true });
113
+ }
114
+ catch {
115
+ /* cache failure */
116
+ }
117
+ try {
118
+ closeSync(fd);
119
+ }
120
+ catch {
121
+ /* cache failure */
122
+ }
123
+ return null;
124
+ }
125
+ }
126
+ }
127
+ export async function withCommandLock(env, deadline, fn) {
128
+ const waitMs = Math.min(LOCK_WAIT_MS, deadline === undefined ? LOCK_WAIT_MS : deadline - Date.now() - 1000);
129
+ if (waitMs <= 0) {
130
+ throw new AxiError('unreachable', 'The time for this command ran out before Ituran was asked.');
131
+ }
132
+ const until = performance.now() + waitMs;
133
+ // Never derive this from TMPDIR or XDG_CACHE_HOME: workbench commands
134
+ // can each receive different temporary and cache directories. Wrappers
135
+ // with private /tmp mounts must supply one shared, writable directory.
136
+ const dir = env.ITURAN_AXI_LOCK_DIR ||
137
+ join('/tmp', `ituran-axi-${process.getuid?.() ?? 'user'}`);
138
+ const owner = {
139
+ pid: process.pid,
140
+ hostname: hostname(),
141
+ token: randomUUID(),
142
+ };
143
+ const held = await acquire(dir, until, owner);
144
+ // Preserve reads when the selected directory is unavailable. A usable
145
+ // lock's contention never takes this unlocked fallback.
146
+ if (!held)
147
+ return fn();
148
+ const ownsPath = () => {
149
+ try {
150
+ return snapshot(held.lock).owner?.token === owner.token;
151
+ }
152
+ catch {
153
+ return false;
154
+ }
155
+ };
156
+ const heartbeat = setInterval(() => {
157
+ try {
158
+ const now = new Date();
159
+ // Refresh this inode, even if the pathname now belongs to someone else.
160
+ futimesSync(held.fd, now, now);
161
+ }
162
+ catch {
163
+ /* a failed refresh expires the lease */
164
+ }
165
+ }, HEARTBEAT_MS);
166
+ heartbeat.unref();
167
+ let released = false;
168
+ const release = () => {
169
+ if (released)
170
+ return;
171
+ released = true;
172
+ clearInterval(heartbeat);
173
+ try {
174
+ if (ownsPath()) {
175
+ try {
176
+ writeFileSync(held.next, String(Date.now() + GAP_MS), {
177
+ mode: 0o600,
178
+ });
179
+ }
180
+ catch {
181
+ /* a cache failure must not replace the command result */
182
+ }
183
+ finally {
184
+ if (ownsPath())
185
+ rmSync(held.lock, { force: true });
186
+ }
187
+ }
188
+ }
189
+ catch {
190
+ /* cleanup must not replace the command result */
191
+ }
192
+ finally {
193
+ try {
194
+ closeSync(held.fd);
195
+ }
196
+ catch {
197
+ /* already closed */
198
+ }
199
+ }
200
+ };
201
+ const interrupt = () => process.exit(130);
202
+ const terminate = () => process.exit(143);
203
+ process.once('exit', release);
204
+ process.once('SIGINT', interrupt);
205
+ process.once('SIGTERM', terminate);
206
+ try {
207
+ let notBefore = 0;
208
+ try {
209
+ notBefore = Number(readFileSync(held.next, 'utf8'));
210
+ }
211
+ catch {
212
+ /* an unavailable gap cache does not block reads */
213
+ }
214
+ const gap = Math.min(GAP_MS, notBefore - Date.now());
215
+ if (gap > 0) {
216
+ if (performance.now() + gap >= until)
217
+ throw busy();
218
+ await sleep(gap);
219
+ }
220
+ return await fn();
221
+ }
222
+ finally {
223
+ process.removeListener('SIGINT', interrupt);
224
+ process.removeListener('SIGTERM', terminate);
225
+ process.removeListener('exit', release);
226
+ release();
227
+ }
228
+ }
@@ -11,6 +11,7 @@ const round1 = (v) => typeof v === 'number' ? Math.round(v * 10) / 10 : null;
11
11
  const RECENT_HOURS = 6;
12
12
  /** Ituran fails an account-wide month of trips with HTTP 500, but answers a week. */
13
13
  export const TRIP_SPAN_DAYS = 7;
14
+ const MAX_TRIP_DAYS = 56;
14
15
  const LATE_NOTE = 'Ituran matches trips by their end time and lists a trip up to a few hours after it ends.';
15
16
  function windowFlags(values) {
16
17
  return {
@@ -116,6 +117,12 @@ export async function trips(input) {
116
117
  const plates = [...new Set(input.positionals.map(normalizePlate))];
117
118
  const acc = await account(ctx);
118
119
  const w = windowOf(windowFlags(values), acc.zone, ctx.now, '24h');
120
+ // joinedRows reads every week's count, even for --limit 1. Bound that
121
+ // work before scheduling any trip requests, including --by plate.
122
+ if (naiveMs(w.to) - naiveMs(w.from) >=
123
+ MAX_TRIP_DAYS * 86_400_000) {
124
+ throw usage('Trips cover at most 56 days per command. Ask for a shorter window; --limit only limits output rows.');
125
+ }
119
126
  const by = str(values.by);
120
127
  if (by !== undefined) {
121
128
  if (by !== 'plate')
package/dist/http.js CHANGED
@@ -77,22 +77,31 @@ export async function fetchAnswer(deps, url, init, timeoutMs) {
77
77
  throw new AxiError('unreachable', 'The time for this command ran out before Ituran was asked.');
78
78
  }
79
79
  const started = performance.now();
80
+ const controller = new AbortController();
81
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
80
82
  let response;
81
83
  let buffer;
82
84
  try {
83
85
  response = await deps.fetch(url, {
84
86
  ...init,
85
87
  redirect: 'manual',
86
- signal: AbortSignal.timeout(timeoutMs),
88
+ signal: controller.signal,
87
89
  });
88
90
  buffer = Buffer.from(await response.arrayBuffer());
89
91
  }
90
- catch (error) {
91
- const timedOut = error instanceof Error && error.name === 'TimeoutError';
92
- throw new AxiError('unreachable', timedOut
92
+ catch {
93
+ throw new AxiError('unreachable', controller.signal.aborted
93
94
  ? `Ituran did not answer within ${Math.round(timeoutMs / 1000)} s.`
94
95
  : 'Ituran could not be reached. Check the network, or whether the Gate is running.');
95
96
  }
97
+ finally {
98
+ clearTimeout(timer);
99
+ // Stop receiving even when buffering failed. The body may already be
100
+ // consumed or cancelled by fetch; cancelling it again is harmless.
101
+ controller.abort();
102
+ if (response?.body)
103
+ await response.body.cancel().catch(() => { });
104
+ }
96
105
  const text = buffer.toString('utf8');
97
106
  let json;
98
107
  try {
package/dist/version.js CHANGED
@@ -1,2 +1,2 @@
1
1
  // Kept equal to package.json by test/unit/version.test.ts.
2
- export const VERSION = '0.1.3';
2
+ export const VERSION = '0.1.5';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ituran-axi",
3
- "version": "0.1.3",
3
+ "version": "0.1.5",
4
4
  "description": "A read-only command-line tool that lets AI agents read Ituran vehicle tracking",
5
5
  "license": "MIT",
6
6
  "type": "module",