ituran-axi 0.1.2 → 0.1.4
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 +19 -4
- package/dist/bin/ituran-axi.js +6 -1
- package/dist/cli/run.js +33 -10
- package/dist/command-lock.js +225 -0
- package/dist/commands/catalog.js +19 -4
- package/dist/commands/readings.js +25 -11
- package/dist/commands/reports.js +94 -6
- package/dist/commands/vehicles.js +80 -13
- package/dist/http.js +13 -4
- package/dist/time.js +23 -0
- package/dist/version.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -14,7 +14,7 @@ ituran-axi is an AXI, an [agent experience interface](https://axi.md). Every com
|
|
|
14
14
|
|
|
15
15
|
It replaces [`ituran-mcp`](https://github.com/ituranlabs/ituran-mcp) for agents that have a shell: 24 commands instead of 152 tool schemas, which cost about 43,000 tokens per conversation. It was built to run inside Comis, behind the Comis Gate, and it also works on its own.
|
|
16
16
|
|
|
17
|
-
> **Status:** early development (0.x).
|
|
17
|
+
> **Status:** early development (0.x). Command families have been checked against production. New changes are tested against a fake Ituran; see each pull request for live-validation coverage.
|
|
18
18
|
|
|
19
19
|
## Requirements
|
|
20
20
|
|
|
@@ -54,10 +54,10 @@ ituran-axi odometer <plate>... | --all GPS odometer estimates with their re
|
|
|
54
54
|
ituran-axi centers [--near <plate|lat,lon>] Ituran service centers, nearest first
|
|
55
55
|
ituran-axi drivers [<text>] | driver <id>
|
|
56
56
|
ituran-axi places [<text>] | place <id> [--vehicles]
|
|
57
|
-
ituran-axi groups [<id>]
|
|
57
|
+
ituran-axi groups [<id>] [--vehicles]
|
|
58
58
|
ituran-axi events [--all] | event <id> event states, and the vehicles in each now
|
|
59
59
|
ituran-axi alerts [--plate <plate>] alert definitions
|
|
60
|
-
ituran-axi diagnostics <plate>... | --all [--names a,b] [--history --date <d>]
|
|
60
|
+
ituran-axi diagnostics <plate>... | --all [--names a,b] [--history --date <d>] [--page N]
|
|
61
61
|
ituran-axi report daily|periodic|idle [<plate>...] [--drivers] [window]
|
|
62
62
|
ituran-axi report speed|events|engine|full|diagnostics|heat-map <plate>... [window] [--over <km/h>]
|
|
63
63
|
ituran-axi safety [totals|vehicles|drivers|groups|periodic|ubi-vehicles|ubi-drivers] [window]
|
|
@@ -67,6 +67,14 @@ ituran-axi logout
|
|
|
67
67
|
ituran-axi help [<command>] every flag of a command
|
|
68
68
|
```
|
|
69
69
|
|
|
70
|
+
Position fields include `age_seconds` alongside the rounded `age`, plus `driver_id`, `groups` and `group_ids`. Select them with `where --fields` or `vehicles --fields`; `vehicle` includes the age in `position` and a `groups` list. `age_seconds` converts the timestamp using the account zone's offset at that time, so it measures elapsed seconds across DST changes; negative values indicate future timestamps. Repeated fall-back times and nonexistent spring-forward times return `null` because they have no unique instant. The rounded `age` retains its existing wall-clock display.
|
|
71
|
+
|
|
72
|
+
`groups <id>` requests the member plates Ituran lists for that group. `groups --vehicles` includes counts and plates throughout the tree. `report daily|periodic|idle --group <id>` filters by those plates and adds `group_km` for all matching rows before output paging. Membership is current. Child-group lists are not merged, and whether the parent's plate list includes descendants remains unverified until a live run. These reads cannot reconstruct historical membership. Group totals are `null` if the report walk is partial or member report rows or distance fields are missing. `group_reported_vehicles` and `group_unreported_vehicles` show that coverage. The coverage rule assumes a BI row per member. Whether BI omits stationary vehicles and whether idle rows carry distance are unverified until a live run; conservative totals may remain `null`. Fleet-wide idle totals are omitted when filtering to plates or a group.
|
|
73
|
+
|
|
74
|
+
`report events|full <plate>... --place <id> [window]` reads dated saved-place evidence, including place IDs and names. It requires explicit plates. Records do not establish complete arrival/departure times or continuous visits. `events --all` shows current states, including empty ones; use `report events` for history. `report speed` requires `--over <km/h>`.
|
|
75
|
+
|
|
76
|
+
`maintenance` preserves its existing columns and adds `next.date`, `next.odometer` and `next.engine_hours` when present. `without_due_target` counts records with no date or positive odometer/engine-hours target. Missing targets do not mean overdue. `diagnostics --page N --limit N` pages the readings after all vehicle pages have been read; each reading retains its own age. Pages re-read current data and can shift between calls. `--full` lifts output size bounds, while `--limit` and `--page` still control rows.
|
|
77
|
+
|
|
70
78
|
A **window** is `--since 90m|24h|7d`, `--from <t> [--to <t>]`, or `--date YYYY-MM-DD`. Times are local to the account's time zone, which the home view shows, and take the form `YYYY-MM-DD` or `YYYY-MM-DDTHH:mm`. **Lists** take `--limit`, `--page`, `--fields` and `--full`.
|
|
71
79
|
|
|
72
80
|
```console
|
|
@@ -88,7 +96,7 @@ code: not_found
|
|
|
88
96
|
usage: "ituran-axi vehicle <plate> [--full]"
|
|
89
97
|
```
|
|
90
98
|
|
|
91
|
-
[`docs/recipes.md`](docs/recipes.md) has tested shell combinations for common questions about the vehicles.
|
|
99
|
+
[`docs/round2-gaps.md`](docs/round2-gaps.md) records the API evidence and remaining limits. [`docs/recipes.md`](docs/recipes.md) has tested shell combinations for common questions about the vehicles.
|
|
92
100
|
|
|
93
101
|
### Ituran's own rules
|
|
94
102
|
|
|
@@ -101,6 +109,12 @@ ituran-axi handles these, and says so in its output where it matters:
|
|
|
101
109
|
- Keypad driver codes above 2^53 stay exact.
|
|
102
110
|
- A model year or odometer of 0 means "not set".
|
|
103
111
|
|
|
112
|
+
Commands sharing a user's cache 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 `~/.cache/ituran-axi/command.lock` (or under `XDG_CACHE_HOME`). Waiting is limited to 30 seconds, or the remaining `COMIS_DEADLINE` minus one second. 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 cache storage is unavailable, the client tries a shared per-user lock under the system temporary directory. If that is also unavailable, it continues without a process lock, with the same output. Cache and cleanup errors never replace a successful result. Separate users, cache directories and hosts need their own coordination; the 400 ms gap between commands also depends on writable cache storage.
|
|
115
|
+
|
|
116
|
+
Request timeouts cover the response body too: 60 seconds for reads, 30 seconds for sign-in, shortened by `COMIS_DEADLINE` when set. A timeout aborts the request and cancels the response body. The CLI flushes its output and exits, releasing Node's proxy dispatcher sockets even if a proxy has not answered CONNECT.
|
|
117
|
+
|
|
104
118
|
## Output and errors
|
|
105
119
|
|
|
106
120
|
- **Size:** a value is cut at 500 characters and the whole output at about 4,000. `--full` lifts both limits, up to 256 KB.
|
|
@@ -119,6 +133,7 @@ ituran-axi handles these, and says so in its output where it matters:
|
|
|
119
133
|
| `not_entitled`, `feature_off`, `needs_app_id` | This account does not include that service |
|
|
120
134
|
| `rejected` | Ituran refused the request; its message is shown |
|
|
121
135
|
| `rate_limited`, `ituran_error`, `unreachable` | Ituran limited the request, failed, or could not be reached |
|
|
136
|
+
| `busy` | Another local command holds the process lock. Wait for it to finish before trying again. |
|
|
122
137
|
| `reconnect_needed`, `refused` | Inside Comis: the owner must reconnect, or the Gate refused |
|
|
123
138
|
| `output_too_large` | Even `--full` would exceed 256 KB; narrow the query |
|
|
124
139
|
| `internal_error` | A bug in ituran-axi; please [report it](https://github.com/comisai/ituran-axi/issues) |
|
package/dist/bin/ituran-axi.js
CHANGED
|
@@ -7,7 +7,7 @@ process.stdout.on('error', (error) => {
|
|
|
7
7
|
process.exit(0);
|
|
8
8
|
throw error;
|
|
9
9
|
});
|
|
10
|
-
|
|
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';
|
|
@@ -69,7 +70,7 @@ export const COMMANDS = [
|
|
|
69
70
|
flags: {
|
|
70
71
|
fields: {
|
|
71
72
|
...FIELDS,
|
|
72
|
-
summary: 'Columns: plate, name, model, make, year, status, color, age, time, speed, limit, lat, lon, address, odometer, driver, places',
|
|
73
|
+
summary: 'Columns: plate, name, model, make, year, status, color, age, age_seconds, time, speed, limit, lat, lon, address, odometer, driver, driver_id, groups, group_ids, places',
|
|
73
74
|
},
|
|
74
75
|
limit: LIMIT,
|
|
75
76
|
page: PAGE,
|
|
@@ -87,7 +88,7 @@ export const COMMANDS = [
|
|
|
87
88
|
summary: "Also the VIN, IDs and the driver's phone",
|
|
88
89
|
},
|
|
89
90
|
},
|
|
90
|
-
summary: 'One vehicle: position, driver and saved places',
|
|
91
|
+
summary: 'One vehicle: position with age in seconds, driver, groups and saved places',
|
|
91
92
|
run: vehicle,
|
|
92
93
|
},
|
|
93
94
|
{
|
|
@@ -115,7 +116,7 @@ export const COMMANDS = [
|
|
|
115
116
|
},
|
|
116
117
|
fields: {
|
|
117
118
|
...FIELDS,
|
|
118
|
-
summary: 'Columns: plate, name, model, make, year, status, age, time, speed, limit, lat, lon, address, odometer, driver, places, km',
|
|
119
|
+
summary: 'Columns: plate, name, model, make, year, status, age, age_seconds, time, speed, limit, lat, lon, address, odometer, driver, driver_id, groups, group_ids, places, km',
|
|
119
120
|
},
|
|
120
121
|
limit: LIMIT,
|
|
121
122
|
page: PAGE,
|
|
@@ -256,8 +257,14 @@ export const COMMANDS = [
|
|
|
256
257
|
{
|
|
257
258
|
name: 'groups',
|
|
258
259
|
args: [{ name: '<id>', required: false }],
|
|
259
|
-
flags: {
|
|
260
|
-
|
|
260
|
+
flags: {
|
|
261
|
+
vehicles: {
|
|
262
|
+
type: 'boolean',
|
|
263
|
+
summary: 'Include listed member counts and plates in the group tree',
|
|
264
|
+
},
|
|
265
|
+
full: FULL,
|
|
266
|
+
},
|
|
267
|
+
summary: 'Vehicle groups, or one group with its listed member plates',
|
|
261
268
|
run: groups,
|
|
262
269
|
},
|
|
263
270
|
{
|
|
@@ -266,7 +273,7 @@ export const COMMANDS = [
|
|
|
266
273
|
flags: {
|
|
267
274
|
all: {
|
|
268
275
|
type: 'boolean',
|
|
269
|
-
summary: 'Include
|
|
276
|
+
summary: 'Include empty current states; use report events for history',
|
|
270
277
|
},
|
|
271
278
|
limit: LIMIT,
|
|
272
279
|
full: FULL,
|
|
@@ -312,9 +319,10 @@ export const COMMANDS = [
|
|
|
312
319
|
},
|
|
313
320
|
date: WINDOW.date,
|
|
314
321
|
limit: LIMIT,
|
|
322
|
+
page: PAGE,
|
|
315
323
|
full: FULL,
|
|
316
324
|
},
|
|
317
|
-
summary: '
|
|
325
|
+
summary: 'Paged sensor readings, latest or over one day',
|
|
318
326
|
run: diagnostics,
|
|
319
327
|
},
|
|
320
328
|
{
|
|
@@ -329,10 +337,20 @@ export const COMMANDS = [
|
|
|
329
337
|
type: 'boolean',
|
|
330
338
|
summary: 'By driver instead of by vehicle (daily, periodic, idle)',
|
|
331
339
|
},
|
|
340
|
+
group: {
|
|
341
|
+
type: 'string',
|
|
342
|
+
value: '<id>',
|
|
343
|
+
summary: 'Current listed group plates; daily, periodic or idle by vehicle, with group km total',
|
|
344
|
+
},
|
|
345
|
+
place: {
|
|
346
|
+
type: 'string',
|
|
347
|
+
value: '<id>',
|
|
348
|
+
summary: 'Saved-place event evidence; report events or full, with explicit plates',
|
|
349
|
+
},
|
|
332
350
|
over: {
|
|
333
351
|
type: 'string',
|
|
334
352
|
value: '<km/h>',
|
|
335
|
-
summary: '
|
|
353
|
+
summary: 'Required for report speed: the speed to report above',
|
|
336
354
|
},
|
|
337
355
|
limit: LIMIT,
|
|
338
356
|
page: PAGE,
|
|
@@ -371,7 +389,7 @@ export const COMMANDS = [
|
|
|
371
389
|
limit: LIMIT,
|
|
372
390
|
full: FULL,
|
|
373
391
|
},
|
|
374
|
-
summary: 'Maintenance
|
|
392
|
+
summary: 'Maintenance date, odometer and engine-hours targets',
|
|
375
393
|
run: maintenance,
|
|
376
394
|
service: 'maintenance',
|
|
377
395
|
},
|
|
@@ -509,7 +527,12 @@ export async function main(argv, io) {
|
|
|
509
527
|
io.stdout(commandHelp(found));
|
|
510
528
|
return 0;
|
|
511
529
|
}
|
|
512
|
-
|
|
530
|
+
// Help and local logout do not need network serialization. Validate the
|
|
531
|
+
// connection before creating a lock so missing settings stay actionable.
|
|
532
|
+
const input = { ...parsed, io };
|
|
533
|
+
const out = spec.name === 'logout'
|
|
534
|
+
? await spec.run(input)
|
|
535
|
+
: await withCommandLock(io.env, connected(io.env).deadline, () => spec.run(input));
|
|
513
536
|
remember(spec, io, null);
|
|
514
537
|
io.stdout(out);
|
|
515
538
|
return 0;
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
// One network command at a time per user's cache, 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 { homedir, hostname, tmpdir } 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
|
+
const root = env.XDG_CACHE_HOME || join(env.HOME || homedir(), '.cache');
|
|
134
|
+
const owner = {
|
|
135
|
+
pid: process.pid,
|
|
136
|
+
hostname: hostname(),
|
|
137
|
+
token: randomUUID(),
|
|
138
|
+
};
|
|
139
|
+
const held = (await acquire(join(root, 'ituran-axi'), until, owner)) ??
|
|
140
|
+
(await acquire(join(tmpdir(), `ituran-axi-${process.getuid?.() ?? 'user'}`), until, owner));
|
|
141
|
+
// Cache storage is an optimization. Preserve reads even if both locations
|
|
142
|
+
// are unavailable; contention on a usable lock never takes this fallback.
|
|
143
|
+
if (!held)
|
|
144
|
+
return fn();
|
|
145
|
+
const ownsPath = () => {
|
|
146
|
+
try {
|
|
147
|
+
return snapshot(held.lock).owner?.token === owner.token;
|
|
148
|
+
}
|
|
149
|
+
catch {
|
|
150
|
+
return false;
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
const heartbeat = setInterval(() => {
|
|
154
|
+
try {
|
|
155
|
+
const now = new Date();
|
|
156
|
+
// Refresh this inode, even if the pathname now belongs to someone else.
|
|
157
|
+
futimesSync(held.fd, now, now);
|
|
158
|
+
}
|
|
159
|
+
catch {
|
|
160
|
+
/* a failed refresh expires the lease */
|
|
161
|
+
}
|
|
162
|
+
}, HEARTBEAT_MS);
|
|
163
|
+
heartbeat.unref();
|
|
164
|
+
let released = false;
|
|
165
|
+
const release = () => {
|
|
166
|
+
if (released)
|
|
167
|
+
return;
|
|
168
|
+
released = true;
|
|
169
|
+
clearInterval(heartbeat);
|
|
170
|
+
try {
|
|
171
|
+
if (ownsPath()) {
|
|
172
|
+
try {
|
|
173
|
+
writeFileSync(held.next, String(Date.now() + GAP_MS), {
|
|
174
|
+
mode: 0o600,
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
catch {
|
|
178
|
+
/* a cache failure must not replace the command result */
|
|
179
|
+
}
|
|
180
|
+
finally {
|
|
181
|
+
if (ownsPath())
|
|
182
|
+
rmSync(held.lock, { force: true });
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
catch {
|
|
187
|
+
/* cleanup must not replace the command result */
|
|
188
|
+
}
|
|
189
|
+
finally {
|
|
190
|
+
try {
|
|
191
|
+
closeSync(held.fd);
|
|
192
|
+
}
|
|
193
|
+
catch {
|
|
194
|
+
/* already closed */
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
};
|
|
198
|
+
const interrupt = () => process.exit(130);
|
|
199
|
+
const terminate = () => process.exit(143);
|
|
200
|
+
process.once('exit', release);
|
|
201
|
+
process.once('SIGINT', interrupt);
|
|
202
|
+
process.once('SIGTERM', terminate);
|
|
203
|
+
try {
|
|
204
|
+
let notBefore = 0;
|
|
205
|
+
try {
|
|
206
|
+
notBefore = Number(readFileSync(held.next, 'utf8'));
|
|
207
|
+
}
|
|
208
|
+
catch {
|
|
209
|
+
/* an unavailable gap cache does not block reads */
|
|
210
|
+
}
|
|
211
|
+
const gap = Math.min(GAP_MS, notBefore - Date.now());
|
|
212
|
+
if (gap > 0) {
|
|
213
|
+
if (performance.now() + gap >= until)
|
|
214
|
+
throw busy();
|
|
215
|
+
await sleep(gap);
|
|
216
|
+
}
|
|
217
|
+
return await fn();
|
|
218
|
+
}
|
|
219
|
+
finally {
|
|
220
|
+
process.removeListener('SIGINT', interrupt);
|
|
221
|
+
process.removeListener('SIGTERM', terminate);
|
|
222
|
+
process.removeListener('exit', release);
|
|
223
|
+
release();
|
|
224
|
+
}
|
|
225
|
+
}
|
package/dist/commands/catalog.js
CHANGED
|
@@ -17,6 +17,12 @@ function flattenGroups(groups, depth, parent, out) {
|
|
|
17
17
|
depth,
|
|
18
18
|
parent,
|
|
19
19
|
subgroups: children.length,
|
|
20
|
+
vehicles: Array.isArray(g.license_plates)
|
|
21
|
+
? new Set(g.license_plates).size
|
|
22
|
+
: null,
|
|
23
|
+
plates: Array.isArray(g.license_plates)
|
|
24
|
+
? [...new Set(g.license_plates)].join(' ')
|
|
25
|
+
: null,
|
|
20
26
|
});
|
|
21
27
|
flattenGroups(children, depth + 1, String(g.vehicle_group_id ?? g.id ?? ''), out);
|
|
22
28
|
}
|
|
@@ -31,6 +37,7 @@ export async function groups(input) {
|
|
|
31
37
|
const g = obj(await ctx.client.read({
|
|
32
38
|
method: 'GET',
|
|
33
39
|
path: api(ctx, `/vehicle-groups/${id}`),
|
|
40
|
+
query: { additional_fields: ['license_plates'] },
|
|
34
41
|
ctx: { what: `vehicle group ${id}` },
|
|
35
42
|
}));
|
|
36
43
|
return recordOutput(g, full, `ituran-axi groups ${id}`);
|
|
@@ -38,6 +45,9 @@ export async function groups(input) {
|
|
|
38
45
|
const json = await ctx.client.read({
|
|
39
46
|
method: 'GET',
|
|
40
47
|
path: api(ctx, '/vehicle-groups'),
|
|
48
|
+
query: input.values.vehicles === true
|
|
49
|
+
? { additional_fields: ['license_plates'] }
|
|
50
|
+
: {},
|
|
41
51
|
ctx: { what: 'vehicle groups' },
|
|
42
52
|
emptyOn404: true,
|
|
43
53
|
});
|
|
@@ -49,7 +59,9 @@ export async function groups(input) {
|
|
|
49
59
|
? countLine(rows.length, rows.length, 'vehicle group')
|
|
50
60
|
: '0 vehicle groups',
|
|
51
61
|
rows,
|
|
52
|
-
columns:
|
|
62
|
+
columns: input.values.vehicles === true
|
|
63
|
+
? ['id', 'name', 'depth', 'vehicles', 'plates']
|
|
64
|
+
: ['id', 'name', 'depth', 'parent'],
|
|
53
65
|
help: rows.length ? ['Run `ituran-axi groups <id>` for one group'] : [],
|
|
54
66
|
full,
|
|
55
67
|
narrower: 'ituran-axi groups <id>',
|
|
@@ -81,9 +93,12 @@ export async function events(input) {
|
|
|
81
93
|
summary: `${all.length} event states · ${active.length} with vehicles in them now${rows.length < chosen.length ? ` · ${rows.length} shown` : ''}`,
|
|
82
94
|
rows,
|
|
83
95
|
columns: ['id', 'name', 'vehicles'],
|
|
84
|
-
help:
|
|
85
|
-
|
|
86
|
-
|
|
96
|
+
help: [
|
|
97
|
+
...(rows.length
|
|
98
|
+
? ['Run `ituran-axi event <id>` for the vehicles in one state']
|
|
99
|
+
: []),
|
|
100
|
+
'Run `ituran-axi report events <plate> --since 24h` for event history; --all here includes empty current states',
|
|
101
|
+
],
|
|
87
102
|
full: input.values.full === true,
|
|
88
103
|
narrower: 'ituran-axi events --limit <n>',
|
|
89
104
|
});
|
|
@@ -36,6 +36,8 @@ export async function diagnostics(input) {
|
|
|
36
36
|
throw usage('--history reads one vehicle: give one plate.');
|
|
37
37
|
const acc = await account(ctx);
|
|
38
38
|
const limit = intFlag(values.limit, 'limit', 20, 1, MAX_PAGE);
|
|
39
|
+
const page = intFlag(values.page, 'page', 1, 1, 100_000);
|
|
40
|
+
const offset = (page - 1) * limit;
|
|
39
41
|
const names = typeof values.names === 'string'
|
|
40
42
|
? values.names
|
|
41
43
|
.split(',')
|
|
@@ -117,11 +119,11 @@ export async function diagnostics(input) {
|
|
|
117
119
|
key: 'readings',
|
|
118
120
|
summary,
|
|
119
121
|
head: { zone: acc.zone },
|
|
120
|
-
rows: rows.slice(
|
|
122
|
+
rows: rows.slice(offset, offset + limit),
|
|
121
123
|
columns: ['plate', 'channel', 'label', 'value', 'age'],
|
|
122
|
-
help: rows.length > limit
|
|
124
|
+
help: rows.length > offset + limit
|
|
123
125
|
? [
|
|
124
|
-
`Run the same command with --limit ${Math.min(
|
|
126
|
+
`Run the same command with --page ${page + 1} --limit ${limit} for the next ${Math.min(limit, rows.length - offset - limit)} readings`,
|
|
125
127
|
]
|
|
126
128
|
: [],
|
|
127
129
|
full: values.full === true,
|
|
@@ -176,15 +178,27 @@ export async function maintenance(input) {
|
|
|
176
178
|
summary: all.length
|
|
177
179
|
? `${countLine(Math.min(limit, all.length), all.length, 'treatment record')}${plate ? ` for ${plate}` : ''}`
|
|
178
180
|
: `0 treatment records${plate ? ` for ${plate}` : ''}: this account keeps no maintenance records in Ituran`,
|
|
181
|
+
head: {
|
|
182
|
+
without_due_target: all.filter((r) => !r['next.date'] &&
|
|
183
|
+
!['next.odometer', 'next.engine_hours'].some((key) => typeof r[key] === 'number' &&
|
|
184
|
+
Number.isFinite(r[key]) &&
|
|
185
|
+
r[key] > 0)).length,
|
|
186
|
+
note: 'Due targets are next.date, next.odometer and next.engine_hours. Missing targets do not mean overdue; verify stale or inconsistent schedules before planning service.',
|
|
187
|
+
},
|
|
179
188
|
rows: all.slice(0, limit),
|
|
180
|
-
columns:
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
189
|
+
columns: [
|
|
190
|
+
...new Set([
|
|
191
|
+
...pickColumns(all, [
|
|
192
|
+
'license_plate',
|
|
193
|
+
'treatment_name',
|
|
194
|
+
'name',
|
|
195
|
+
'date',
|
|
196
|
+
'odometer',
|
|
197
|
+
'next',
|
|
198
|
+
]),
|
|
199
|
+
...['next.date', 'next.odometer', 'next.engine_hours'].filter((k) => all.some((r) => k in r)),
|
|
200
|
+
]),
|
|
201
|
+
],
|
|
188
202
|
help: [],
|
|
189
203
|
full: values.full === true,
|
|
190
204
|
narrower: 'ituran-axi maintenance <plate>',
|
package/dist/commands/reports.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// filters, so plates are applied here). Operational reports take 1 to 5 plates
|
|
3
3
|
// and less than three days per request, page with an inclusive cursor, and can
|
|
4
4
|
// repeat a row at a page boundary; the walk splits and removes repeats.
|
|
5
|
-
import { usage } from '../errors.js';
|
|
5
|
+
import { AxiError, usage } from '../errors.js';
|
|
6
6
|
import { normalizePlate } from '../plates.js';
|
|
7
7
|
import { hoursMinutes, naiveMs, windowOf, yesterday } from '../time.js';
|
|
8
8
|
import { pickColumns } from './catalog.js';
|
|
@@ -77,6 +77,17 @@ function recordRow(r) {
|
|
|
77
77
|
lon: point.lon ?? null,
|
|
78
78
|
odometer: r.odometer ?? null,
|
|
79
79
|
id: r.record_id ?? null,
|
|
80
|
+
driver_id: driver.driver_id ?? null,
|
|
81
|
+
places: Array.isArray(r.places)
|
|
82
|
+
? r.places
|
|
83
|
+
.map((p) => str(p.name) ?? str(p.place_name))
|
|
84
|
+
.filter(Boolean)
|
|
85
|
+
.join('; ') || null
|
|
86
|
+
: null,
|
|
87
|
+
place_ids: Array.isArray(r.places)
|
|
88
|
+
? r.places.map((p) => String(p.id ?? p.place_id)).join(' ') ||
|
|
89
|
+
null
|
|
90
|
+
: null,
|
|
80
91
|
};
|
|
81
92
|
}
|
|
82
93
|
async function biReport(ctx, input, name, plates, zone) {
|
|
@@ -85,6 +96,23 @@ async function biReport(ctx, input, name, plates, zone) {
|
|
|
85
96
|
const w = windowOf(windowFlags(values), zone, ctx.now, '24h', 'date');
|
|
86
97
|
const limit = intFlag(values.limit, 'limit', 20, 1, REPORT_PAGE);
|
|
87
98
|
const page = intFlag(values.page, 'page', 1, 1, 100_000);
|
|
99
|
+
let group = null;
|
|
100
|
+
if (typeof values.group === 'string') {
|
|
101
|
+
group = obj(await ctx.client.read({
|
|
102
|
+
method: 'GET',
|
|
103
|
+
path: api(ctx, `/vehicle-groups/${values.group}`),
|
|
104
|
+
query: { additional_fields: ['license_plates'] },
|
|
105
|
+
ctx: { what: 'vehicle group membership' },
|
|
106
|
+
}));
|
|
107
|
+
if (!Array.isArray(group.license_plates))
|
|
108
|
+
throw new AxiError('ituran_error', 'Ituran did not return group membership; no group mileage can be calculated.');
|
|
109
|
+
plates = [
|
|
110
|
+
...new Set(group.license_plates.map((p) => normalizePlate(String(p)))),
|
|
111
|
+
];
|
|
112
|
+
}
|
|
113
|
+
let groupKm = null;
|
|
114
|
+
const reported = new Set();
|
|
115
|
+
let partial;
|
|
88
116
|
let idleTotal = null;
|
|
89
117
|
const fetchPage = async (page_number, page_size) => {
|
|
90
118
|
const json = await ctx.client.read({
|
|
@@ -112,12 +140,27 @@ async function biReport(ctx, input, name, plates, zone) {
|
|
|
112
140
|
let rows;
|
|
113
141
|
let total;
|
|
114
142
|
let note;
|
|
115
|
-
if (plates.length) {
|
|
116
|
-
const all =
|
|
143
|
+
if (plates.length || group) {
|
|
144
|
+
const all = plates.length
|
|
145
|
+
? await walkAll(fetchPage, REPORT_PAGE)
|
|
146
|
+
: { rows: [], total: 0 };
|
|
147
|
+
partial = all.partial;
|
|
117
148
|
const wanted = new Set(plates);
|
|
118
149
|
const hits = all.rows.filter((r) => wanted.has(String(r.license_plate)) ||
|
|
119
150
|
(Array.isArray(r.license_plates) &&
|
|
120
151
|
r.license_plates.some((p) => wanted.has(String(p)))));
|
|
152
|
+
if (group)
|
|
153
|
+
for (const r of hits) {
|
|
154
|
+
const plate = String(r.license_plate);
|
|
155
|
+
if (wanted.has(plate))
|
|
156
|
+
reported.add(plate);
|
|
157
|
+
}
|
|
158
|
+
if (group && !partial && reported.size === plates.length) {
|
|
159
|
+
const distances = hits.map((r) => r.distance ?? r.total_distance);
|
|
160
|
+
groupKm = distances.every((km) => typeof km === 'number' && Number.isFinite(km))
|
|
161
|
+
? Math.round(distances.reduce((sum, km) => sum + km, 0) * 10) / 10
|
|
162
|
+
: null;
|
|
163
|
+
}
|
|
121
164
|
total = hits.length;
|
|
122
165
|
rows = hits.slice((page - 1) * limit, page * limit);
|
|
123
166
|
note =
|
|
@@ -154,7 +197,19 @@ async function biReport(ctx, input, name, plates, zone) {
|
|
|
154
197
|
summary: `${rows.length ? countLine(rows.length, total, 'row') : '0 rows'} of the ${name} report by ${by.slice(0, -1)}`,
|
|
155
198
|
head: {
|
|
156
199
|
window: `${w.from} to ${w.to} (whole days)`,
|
|
157
|
-
...(
|
|
200
|
+
...(group
|
|
201
|
+
? {
|
|
202
|
+
group: values.group,
|
|
203
|
+
group_name: group.vehicle_group_name ?? null,
|
|
204
|
+
group_vehicles: plates.length,
|
|
205
|
+
group_reported_vehicles: reported.size,
|
|
206
|
+
group_unreported_vehicles: plates.length - reported.size,
|
|
207
|
+
group_km: groupKm,
|
|
208
|
+
membership: 'Current plates listed by Ituran for this group; child-group lists are not merged. Inclusion of descendants is unverified. Membership is not historical.',
|
|
209
|
+
}
|
|
210
|
+
: {}),
|
|
211
|
+
...(partial ? { partial } : {}),
|
|
212
|
+
...(totals && !plates.length && !group && Object.keys(totals).length
|
|
158
213
|
? {
|
|
159
214
|
total: {
|
|
160
215
|
vehicles: totals.vehicles_count ?? null,
|
|
@@ -252,6 +307,9 @@ async function operational(ctx, input, name, plates, zone) {
|
|
|
252
307
|
records_limit: Math.min(RECORDS_LIMIT, Math.max(1, limit - rows.length + 1)),
|
|
253
308
|
...(cursor !== undefined ? { from_record_id: cursor } : {}),
|
|
254
309
|
...(over ? { from_speed: over } : {}),
|
|
310
|
+
...(typeof values.place === 'string'
|
|
311
|
+
? { place_ids: [Number(values.place)] }
|
|
312
|
+
: {}),
|
|
255
313
|
},
|
|
256
314
|
ctx: {
|
|
257
315
|
what: `the ${name} report`,
|
|
@@ -285,9 +343,20 @@ async function operational(ctx, input, name, plates, zone) {
|
|
|
285
343
|
return listOutput({
|
|
286
344
|
key: 'records',
|
|
287
345
|
summary: `${shown.length} records of the ${name} report for ${plates.join(' ')}${more ? ', more exist' : ''}`,
|
|
288
|
-
head: {
|
|
346
|
+
head: {
|
|
347
|
+
window: `${w.from} to ${w.to}`,
|
|
348
|
+
zone,
|
|
349
|
+
...(values.place !== undefined
|
|
350
|
+
? {
|
|
351
|
+
place_id: values.place,
|
|
352
|
+
note: 'Saved-place event evidence only; records do not establish complete arrival/departure times or continuous visits.',
|
|
353
|
+
}
|
|
354
|
+
: {}),
|
|
355
|
+
},
|
|
289
356
|
rows: shown,
|
|
290
|
-
columns:
|
|
357
|
+
columns: values.place !== undefined
|
|
358
|
+
? ['time', 'plate', 'event', 'place_ids', 'places']
|
|
359
|
+
: ['time', 'plate', 'event', 'speed', 'address'],
|
|
291
360
|
help: more
|
|
292
361
|
? [
|
|
293
362
|
`Run the same command with --limit ${Math.min(MAX_PAGE, limit * 5)} or a shorter window for more`,
|
|
@@ -304,6 +373,25 @@ export async function report(input) {
|
|
|
304
373
|
}
|
|
305
374
|
if (input.values.drivers === true && !(name in BI))
|
|
306
375
|
throw usage('--drivers applies to the daily, periodic and idle reports.');
|
|
376
|
+
const { values } = input;
|
|
377
|
+
if (values.group !== undefined) {
|
|
378
|
+
if (!(name in BI) ||
|
|
379
|
+
values.drivers === true ||
|
|
380
|
+
input.positionals.length > 1)
|
|
381
|
+
throw usage('--group applies to daily, periodic or idle by vehicle; give a group instead of plates or --drivers.');
|
|
382
|
+
if (typeof values.group !== 'string' || !/^\d{1,20}$/.test(values.group))
|
|
383
|
+
throw usage('--group takes a numeric group id from `ituran-axi groups`.');
|
|
384
|
+
}
|
|
385
|
+
if (values.place !== undefined) {
|
|
386
|
+
if (name !== 'events' && name !== 'full')
|
|
387
|
+
throw usage('--place applies to report events or report full.');
|
|
388
|
+
if (typeof values.place !== 'string' ||
|
|
389
|
+
!/^\d{1,10}$/.test(values.place) ||
|
|
390
|
+
Number(values.place) > 2147483647)
|
|
391
|
+
throw usage('--place takes a numeric place id from `ituran-axi places`.');
|
|
392
|
+
}
|
|
393
|
+
if (name === 'speed' && values.over === undefined)
|
|
394
|
+
throw usage('report speed needs --over <km/h>, the speed to report above.');
|
|
307
395
|
const ctx = open(input);
|
|
308
396
|
const plates = [...new Set(input.positionals.slice(1).map(normalizePlate))];
|
|
309
397
|
const acc = await account(ctx);
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
import { AxiError } from '../errors.js';
|
|
6
6
|
import { distanceKm, parsePoint, pointOf, roundKm } from '../geo.js';
|
|
7
7
|
import { normalizePlate } from '../plates.js';
|
|
8
|
-
import { age, ageMinutes, parseSpan } from '../time.js';
|
|
8
|
+
import { age, ageMinutes, ageSeconds, parseSpan } from '../time.js';
|
|
9
9
|
import { account, api, columnsFlag, countLine, intFlag, listOutput, MAX_PAGE, open, recordOutput, rowsOf, shellWord, str, strings, totalOf, walkAll, windowRows, } from './common.js';
|
|
10
10
|
const REALTIME = ['LastLocation', 'Driver', 'Places'];
|
|
11
11
|
export const WALK_PAGE = 500;
|
|
@@ -49,6 +49,7 @@ export function vehicleRow(v, now, zone) {
|
|
|
49
49
|
status: str(v.motion_status) ?? null,
|
|
50
50
|
color: str(v.color) ?? null,
|
|
51
51
|
age: age(loc.timestamp, now, zone),
|
|
52
|
+
age_seconds: ageSeconds(loc.timestamp, now, zone),
|
|
52
53
|
time: str(loc.timestamp) ?? null,
|
|
53
54
|
speed: typeof loc.speed === 'number' ? loc.speed : null,
|
|
54
55
|
limit: typeof obj(address).speedlimit === 'number'
|
|
@@ -61,6 +62,16 @@ export function vehicleRow(v, now, zone) {
|
|
|
61
62
|
: (str(obj(address).location) ?? null),
|
|
62
63
|
odometer,
|
|
63
64
|
driver: driverName(driver),
|
|
65
|
+
driver_id: driver.driver_id ?? null,
|
|
66
|
+
groups: Array.isArray(v.vehicle_groups)
|
|
67
|
+
? v.vehicle_groups
|
|
68
|
+
.map((g) => str(g.name))
|
|
69
|
+
.filter(Boolean)
|
|
70
|
+
.join('; ') || null
|
|
71
|
+
: null,
|
|
72
|
+
group_ids: Array.isArray(v.vehicle_groups)
|
|
73
|
+
? v.vehicle_groups.map((g) => String(g.id)).join(' ') || null
|
|
74
|
+
: null,
|
|
64
75
|
places: places.length ? places.join('; ') : null,
|
|
65
76
|
};
|
|
66
77
|
}
|
|
@@ -75,6 +86,10 @@ const KNOWN = [
|
|
|
75
86
|
'status',
|
|
76
87
|
'color',
|
|
77
88
|
'age',
|
|
89
|
+
'age_seconds',
|
|
90
|
+
'driver_id',
|
|
91
|
+
'groups',
|
|
92
|
+
'group_ids',
|
|
78
93
|
'time',
|
|
79
94
|
'speed',
|
|
80
95
|
'limit',
|
|
@@ -86,7 +101,7 @@ const KNOWN = [
|
|
|
86
101
|
'places',
|
|
87
102
|
'km',
|
|
88
103
|
];
|
|
89
|
-
export function listPage(ctx, realtime = []) {
|
|
104
|
+
export function listPage(ctx, realtime = [], additional = []) {
|
|
90
105
|
return async (page_number, page_size) => {
|
|
91
106
|
const json = await ctx.client.read({
|
|
92
107
|
method: 'GET',
|
|
@@ -94,6 +109,7 @@ export function listPage(ctx, realtime = []) {
|
|
|
94
109
|
query: {
|
|
95
110
|
page_number,
|
|
96
111
|
page_size,
|
|
112
|
+
...(additional.length ? { additional_fields: additional } : {}),
|
|
97
113
|
...(realtime.length ? { realtime_fields: realtime } : {}),
|
|
98
114
|
},
|
|
99
115
|
ctx: { what: 'vehicles' },
|
|
@@ -105,7 +121,44 @@ export function listPage(ctx, realtime = []) {
|
|
|
105
121
|
};
|
|
106
122
|
};
|
|
107
123
|
}
|
|
108
|
-
|
|
124
|
+
/** Search has no documented additional_fields; join its rows to the group registry. */
|
|
125
|
+
async function searchGroups(ctx, vehicles) {
|
|
126
|
+
if (!vehicles.length)
|
|
127
|
+
return vehicles;
|
|
128
|
+
const json = await ctx.client.read({
|
|
129
|
+
method: 'GET',
|
|
130
|
+
path: api(ctx, '/vehicle-groups'),
|
|
131
|
+
query: { additional_fields: ['license_plates'] },
|
|
132
|
+
ctx: { what: 'vehicle group membership' },
|
|
133
|
+
emptyOn404: true,
|
|
134
|
+
});
|
|
135
|
+
const byPlate = new Map();
|
|
136
|
+
const key = (plate) => String(plate).replace(/[\s-]+/g, '');
|
|
137
|
+
const visit = (groups) => {
|
|
138
|
+
for (const g of groups) {
|
|
139
|
+
const ref = {
|
|
140
|
+
id: g.vehicle_group_id ?? g.id ?? null,
|
|
141
|
+
name: g.vehicle_group_name ?? g.name ?? null,
|
|
142
|
+
};
|
|
143
|
+
for (const plate of Array.isArray(g.license_plates)
|
|
144
|
+
? g.license_plates
|
|
145
|
+
: []) {
|
|
146
|
+
const refs = byPlate.get(key(plate)) ?? [];
|
|
147
|
+
if (!refs.some((r) => r.id === ref.id))
|
|
148
|
+
refs.push(ref);
|
|
149
|
+
byPlate.set(key(plate), refs);
|
|
150
|
+
}
|
|
151
|
+
if (Array.isArray(g.child_groups))
|
|
152
|
+
visit(g.child_groups);
|
|
153
|
+
}
|
|
154
|
+
};
|
|
155
|
+
visit(rowsOf(json, 'vehicle_groups'));
|
|
156
|
+
return vehicles.map((v) => ({
|
|
157
|
+
...v,
|
|
158
|
+
vehicle_groups: byPlate.get(key(v.license_plate)) ?? [],
|
|
159
|
+
}));
|
|
160
|
+
}
|
|
161
|
+
function searchPage(ctx, body, realtime = [], additional = []) {
|
|
109
162
|
return async (page_number, page_size) => {
|
|
110
163
|
// No match comes back as 404 404.3, which means an empty list.
|
|
111
164
|
const json = await ctx.client.read({
|
|
@@ -120,8 +173,11 @@ function searchPage(ctx, body, realtime = []) {
|
|
|
120
173
|
ctx: { what: 'matching vehicles' },
|
|
121
174
|
emptyOn404: true,
|
|
122
175
|
});
|
|
176
|
+
const rows = rowsOf(json, 'vehicles');
|
|
123
177
|
return {
|
|
124
|
-
rows:
|
|
178
|
+
rows: additional.includes('VehicleGroup')
|
|
179
|
+
? await searchGroups(ctx, rows)
|
|
180
|
+
: rows,
|
|
125
181
|
total: json === null ? 0 : totalOf(json),
|
|
126
182
|
};
|
|
127
183
|
};
|
|
@@ -136,6 +192,8 @@ export async function vehicles(input) {
|
|
|
136
192
|
// These columns come from the realtime blocks: position, driver, places.
|
|
137
193
|
const needsRealtime = columns.some((c) => [
|
|
138
194
|
'age',
|
|
195
|
+
'age_seconds',
|
|
196
|
+
'driver_id',
|
|
139
197
|
'time',
|
|
140
198
|
'speed',
|
|
141
199
|
'limit',
|
|
@@ -147,24 +205,27 @@ export async function vehicles(input) {
|
|
|
147
205
|
'places',
|
|
148
206
|
].includes(c));
|
|
149
207
|
const realtime = needsRealtime ? REALTIME : [];
|
|
208
|
+
const additional = columns.some((c) => ['groups', 'group_ids'].includes(c))
|
|
209
|
+
? ['VehicleGroup']
|
|
210
|
+
: [];
|
|
150
211
|
const acc = needsRealtime ? await account(ctx) : null;
|
|
151
212
|
const zone = acc?.zone ?? 'UTC';
|
|
152
213
|
let got;
|
|
153
214
|
let how = '';
|
|
154
215
|
if (!text) {
|
|
155
|
-
got = await windowRows(listPage(ctx, realtime), page, limit);
|
|
216
|
+
got = await windowRows(listPage(ctx, realtime, additional), page, limit);
|
|
156
217
|
}
|
|
157
218
|
else if (/^[\d\s-]+$/.test(text)) {
|
|
158
219
|
const part = text.replace(/[\s-]+/g, '');
|
|
159
|
-
got = await windowRows(searchPage(ctx, { wildcard_filter: { license_plate: part } }, realtime), page, limit);
|
|
220
|
+
got = await windowRows(searchPage(ctx, { wildcard_filter: { license_plate: part } }, realtime, additional), page, limit);
|
|
160
221
|
how = ` with ${part} in the plate`;
|
|
161
222
|
}
|
|
162
223
|
else {
|
|
163
|
-
got = await windowRows(searchPage(ctx, { wildcard_filter: { nickname: text } }, realtime), page, limit);
|
|
224
|
+
got = await windowRows(searchPage(ctx, { wildcard_filter: { nickname: text } }, realtime, additional), page, limit);
|
|
164
225
|
how = ` named like "${text}"`;
|
|
165
226
|
if (got.total === 0 && page === 1) {
|
|
166
227
|
// Ituran searches names only; make, model and color are matched here.
|
|
167
|
-
const all = await walkAll(listPage(ctx, realtime), WALK_PAGE);
|
|
228
|
+
const all = await walkAll(listPage(ctx, realtime, additional), WALK_PAGE);
|
|
168
229
|
const needle = text.toLowerCase();
|
|
169
230
|
const hits = all.rows.filter((v) => [v.make_name, v.model_name, v.color, v.model_year].some((f) => typeof f === 'string' && f.toLowerCase().includes(needle)));
|
|
170
231
|
got = { rows: hits.slice(0, limit), total: hits.length };
|
|
@@ -204,7 +265,7 @@ export async function vehicle(input) {
|
|
|
204
265
|
const v = (await ctx.client.read({
|
|
205
266
|
method: 'GET',
|
|
206
267
|
path: api(ctx, `/vehicles/${plate}`),
|
|
207
|
-
query: { realtime_fields: REALTIME },
|
|
268
|
+
query: { realtime_fields: REALTIME, additional_fields: ['VehicleGroup'] },
|
|
208
269
|
ctx: { what: `vehicle ${plate}`, plate },
|
|
209
270
|
}));
|
|
210
271
|
if (!v || typeof v !== 'object')
|
|
@@ -224,6 +285,7 @@ export async function vehicle(input) {
|
|
|
224
285
|
? {
|
|
225
286
|
time: r.time,
|
|
226
287
|
age: r.age,
|
|
288
|
+
age_seconds: r.age_seconds,
|
|
227
289
|
speed: r.speed,
|
|
228
290
|
speed_limit: r.limit,
|
|
229
291
|
address: r.address,
|
|
@@ -239,6 +301,7 @@ export async function vehicle(input) {
|
|
|
239
301
|
...(full ? { phone: driver.phone, cellular: driver.cellular } : {}),
|
|
240
302
|
}
|
|
241
303
|
: 'none assigned now',
|
|
304
|
+
groups: Array.isArray(v.vehicle_groups) ? v.vehicle_groups : [],
|
|
242
305
|
places: places.length
|
|
243
306
|
? places.map((p) => str(p.place_name) ?? String(p.place_id ?? ''))
|
|
244
307
|
: 'in no saved place',
|
|
@@ -272,20 +335,24 @@ export async function where(input) {
|
|
|
272
335
|
}
|
|
273
336
|
const columns = columnsFlag(values.fields, near ? ['plate', 'km', 'age', 'status', 'address'] : WHERE_COLUMNS, KNOWN);
|
|
274
337
|
const staleMin = typeof values.stale === 'string' ? parseSpan(values.stale, 'stale') : null;
|
|
338
|
+
const realtime = columns.some((c) => ['driver', 'driver_id', 'places'].includes(c))
|
|
339
|
+
? REALTIME
|
|
340
|
+
: ['LastLocation'];
|
|
341
|
+
const additional = columns.some((c) => ['groups', 'group_ids'].includes(c))
|
|
342
|
+
? ['VehicleGroup']
|
|
343
|
+
: [];
|
|
275
344
|
let raw;
|
|
276
345
|
let partial;
|
|
277
346
|
let missing = [];
|
|
278
347
|
if (plates.length) {
|
|
279
348
|
const unique = [...new Set(plates)];
|
|
280
|
-
const got = await searchPage(ctx, { license_plates: unique },
|
|
281
|
-
'LastLocation',
|
|
282
|
-
])(1, Math.max(10, unique.length));
|
|
349
|
+
const got = await searchPage(ctx, { license_plates: unique }, realtime, additional)(1, Math.max(10, unique.length));
|
|
283
350
|
raw = got.rows;
|
|
284
351
|
const found = new Set(raw.map((v) => str(v.license_plate)));
|
|
285
352
|
missing = unique.filter((p) => !found.has(p));
|
|
286
353
|
}
|
|
287
354
|
else {
|
|
288
|
-
const all = await walkAll(listPage(ctx,
|
|
355
|
+
const all = await walkAll(listPage(ctx, realtime, additional), WALK_PAGE);
|
|
289
356
|
raw = all.rows;
|
|
290
357
|
partial = all.partial;
|
|
291
358
|
}
|
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:
|
|
88
|
+
signal: controller.signal,
|
|
87
89
|
});
|
|
88
90
|
buffer = Buffer.from(await response.arrayBuffer());
|
|
89
91
|
}
|
|
90
|
-
catch
|
|
91
|
-
|
|
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/time.js
CHANGED
|
@@ -164,6 +164,29 @@ export function splitWindow(w, days) {
|
|
|
164
164
|
out.push({ from: w.from, to: naiveFromMs(end) });
|
|
165
165
|
return out;
|
|
166
166
|
}
|
|
167
|
+
/**
|
|
168
|
+
* Elapsed whole seconds from an account-local timestamp. Try the zone offsets
|
|
169
|
+
* on both sides of a possible DST transition, then validate the wall time.
|
|
170
|
+
* Repeated or nonexistent local times have no unique instant and stay unknown.
|
|
171
|
+
*/
|
|
172
|
+
export function ageSeconds(timestamp, now, zone) {
|
|
173
|
+
if (typeof timestamp !== 'string')
|
|
174
|
+
return null;
|
|
175
|
+
const wall = naiveMs(timestamp);
|
|
176
|
+
if (wall === null)
|
|
177
|
+
return null;
|
|
178
|
+
const offsets = new Set();
|
|
179
|
+
for (const delta of [-36, 0, 36]) {
|
|
180
|
+
const sample = wall + delta * 3600_000;
|
|
181
|
+
offsets.add(naiveMs(localTime(new Date(sample), zone)) - sample);
|
|
182
|
+
}
|
|
183
|
+
const matches = [...offsets]
|
|
184
|
+
.map((offset) => wall - offset)
|
|
185
|
+
.filter((instant) => naiveMs(localTime(new Date(instant), zone)) === wall);
|
|
186
|
+
if (matches.length !== 1)
|
|
187
|
+
return null;
|
|
188
|
+
return Math.floor((now.getTime() - matches[0]) / 1000);
|
|
189
|
+
}
|
|
167
190
|
/** How long ago a naive local time was: "3m", "2h", "5d", or null. */
|
|
168
191
|
export function age(timestamp, now, zone) {
|
|
169
192
|
if (typeof timestamp !== 'string')
|
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.
|
|
2
|
+
export const VERSION = '0.1.4';
|