dsh-remote-deck 0.0.0-stage → 1.46.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/LICENSE +21 -0
- package/README.md +227 -2
- package/README.zh-CN.md +201 -0
- package/client.js +8645 -0
- package/cordis.patch.yml +6 -0
- package/icon.svg +19 -0
- package/index.js +701 -0
- package/lib/api.js +1452 -0
- package/lib/bash-result.js +93 -0
- package/lib/connection.js +1133 -0
- package/lib/delete.js +199 -0
- package/lib/drafts.js +299 -0
- package/lib/encoding.js +247 -0
- package/lib/file-edit.js +339 -0
- package/lib/file-ops.js +402 -0
- package/lib/forwards.js +186 -0
- package/lib/fs-actions.js +235 -0
- package/lib/guide.js +162 -0
- package/lib/metrics.js +523 -0
- package/lib/remote-shells.js +320 -0
- package/lib/remote-terminal.js +427 -0
- package/lib/routing.js +695 -0
- package/lib/ssh-config.js +118 -0
- package/lib/terminal.js +123 -0
- package/lib/tool-forward.js +185 -0
- package/lib/transfer.js +235 -0
- package/lib/upload-chunks.js +306 -0
- package/lib/util.js +154 -0
- package/locale/README.md +160 -0
- package/locale/en-ui.json +477 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +63 -4
- package/vendor/codemirror/LICENSE +21 -0
- package/vendor/codemirror/README.md +18 -0
- package/vendor/codemirror/addon/edit/closebrackets.min.js +8 -0
- package/vendor/codemirror/addon/edit/matchbrackets.min.js +8 -0
- package/vendor/codemirror/addon/search/search.min.js +8 -0
- package/vendor/codemirror/addon/search/searchcursor.min.js +8 -0
- package/vendor/codemirror/addon/selection/active-line.min.js +8 -0
- package/vendor/codemirror/lib/codemirror.css +344 -0
- package/vendor/codemirror/lib/codemirror.min.js +8 -0
- package/vendor/codemirror/mode/clike/clike.min.js +8 -0
- package/vendor/codemirror/mode/css/css.min.js +8 -0
- package/vendor/codemirror/mode/go/go.min.js +8 -0
- package/vendor/codemirror/mode/htmlmixed/htmlmixed.min.js +8 -0
- package/vendor/codemirror/mode/javascript/javascript.min.js +8 -0
- package/vendor/codemirror/mode/markdown/markdown.min.js +8 -0
- package/vendor/codemirror/mode/python/python.min.js +8 -0
- package/vendor/codemirror/mode/rust/rust.min.js +8 -0
- package/vendor/codemirror/mode/shell/shell.min.js +8 -0
- package/vendor/codemirror/mode/xml/xml.min.js +8 -0
- package/vendor/codemirror/mode/yaml/yaml.min.js +8 -0
- package/vendor/node_modules/asn1/Jenkinsfile +65 -0
- package/vendor/node_modules/asn1/LICENSE +19 -0
- package/vendor/node_modules/asn1/README.md +50 -0
- package/vendor/node_modules/asn1/lib/ber/errors.js +13 -0
- package/vendor/node_modules/asn1/lib/ber/index.js +27 -0
- package/vendor/node_modules/asn1/lib/ber/reader.js +262 -0
- package/vendor/node_modules/asn1/lib/ber/types.js +36 -0
- package/vendor/node_modules/asn1/lib/ber/writer.js +317 -0
- package/vendor/node_modules/asn1/lib/index.js +20 -0
- package/vendor/node_modules/asn1/package.json +31 -0
- package/vendor/node_modules/bcrypt-pbkdf/CONTRIBUTING.md +13 -0
- package/vendor/node_modules/bcrypt-pbkdf/LICENSE +66 -0
- package/vendor/node_modules/bcrypt-pbkdf/README.md +45 -0
- package/vendor/node_modules/bcrypt-pbkdf/index.js +556 -0
- package/vendor/node_modules/bcrypt-pbkdf/package.json +15 -0
- package/vendor/node_modules/safer-buffer/LICENSE +21 -0
- package/vendor/node_modules/safer-buffer/Porting-Buffer.md +268 -0
- package/vendor/node_modules/safer-buffer/Readme.md +156 -0
- package/vendor/node_modules/safer-buffer/dangerous.js +58 -0
- package/vendor/node_modules/safer-buffer/package.json +34 -0
- package/vendor/node_modules/safer-buffer/safer.js +77 -0
- package/vendor/node_modules/safer-buffer/tests.js +406 -0
- package/vendor/node_modules/ssh2/LICENSE +19 -0
- package/vendor/node_modules/ssh2/README.md +1529 -0
- package/vendor/node_modules/ssh2/SFTP.md +413 -0
- package/vendor/node_modules/ssh2/lib/Channel.js +295 -0
- package/vendor/node_modules/ssh2/lib/agent.js +1123 -0
- package/vendor/node_modules/ssh2/lib/client.js +2176 -0
- package/vendor/node_modules/ssh2/lib/http-agents.js +84 -0
- package/vendor/node_modules/ssh2/lib/index.js +44 -0
- package/vendor/node_modules/ssh2/lib/keygen.js +582 -0
- package/vendor/node_modules/ssh2/lib/protocol/Protocol.js +2136 -0
- package/vendor/node_modules/ssh2/lib/protocol/SFTP.js +4052 -0
- package/vendor/node_modules/ssh2/lib/protocol/constants.js +356 -0
- package/vendor/node_modules/ssh2/lib/protocol/crypto/binding.gyp +23 -0
- package/vendor/node_modules/ssh2/lib/protocol/crypto/poly1305.js +43 -0
- package/vendor/node_modules/ssh2/lib/protocol/crypto/src/binding.cc +2300 -0
- package/vendor/node_modules/ssh2/lib/protocol/crypto.js +1602 -0
- package/vendor/node_modules/ssh2/lib/protocol/handlers.js +16 -0
- package/vendor/node_modules/ssh2/lib/protocol/handlers.misc.js +1285 -0
- package/vendor/node_modules/ssh2/lib/protocol/kex.js +1908 -0
- package/vendor/node_modules/ssh2/lib/protocol/keyParser.js +1484 -0
- package/vendor/node_modules/ssh2/lib/protocol/node-fs-compat.js +115 -0
- package/vendor/node_modules/ssh2/lib/protocol/utils.js +356 -0
- package/vendor/node_modules/ssh2/lib/protocol/zlib.js +255 -0
- package/vendor/node_modules/ssh2/lib/server.js +1380 -0
- package/vendor/node_modules/ssh2/lib/utils.js +336 -0
- package/vendor/node_modules/ssh2/package.json +49 -0
- package/vendor/node_modules/tweetnacl/AUTHORS.md +28 -0
- package/vendor/node_modules/tweetnacl/CHANGELOG.md +221 -0
- package/vendor/node_modules/tweetnacl/LICENSE +24 -0
- package/vendor/node_modules/tweetnacl/PULL_REQUEST_TEMPLATE.md +20 -0
- package/vendor/node_modules/tweetnacl/README.md +459 -0
- package/vendor/node_modules/tweetnacl/nacl-fast.js +2388 -0
- package/vendor/node_modules/tweetnacl/nacl-fast.min.js +2 -0
- package/vendor/node_modules/tweetnacl/nacl.d.ts +98 -0
- package/vendor/node_modules/tweetnacl/nacl.js +1175 -0
- package/vendor/node_modules/tweetnacl/nacl.min.js +1 -0
- package/vendor/node_modules/tweetnacl/package.json +58 -0
- package/vendor/xterm/LICENSE.addon-fit +19 -0
- package/vendor/xterm/LICENSE.xterm +21 -0
- package/vendor/xterm/README.md +9 -0
- package/vendor/xterm/addon-fit.js +2 -0
- package/vendor/xterm/xterm.css +218 -0
- package/vendor/xterm/xterm.js +2 -0
package/lib/metrics.js
ADDED
|
@@ -0,0 +1,523 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Remote server metrics: one probe command, its parser, and a small per
|
|
3
|
+
* connection manager.
|
|
4
|
+
*
|
|
5
|
+
* Everything is answered in a single shell round trip. Each value carries its
|
|
6
|
+
* own `rd-*` marker so a tool that only exists on one platform degrades that
|
|
7
|
+
* one field instead of failing the sample: `nproc` is missing on macOS,
|
|
8
|
+
* `/proc/stat` does not exist there at all, and minimal Linux images ship
|
|
9
|
+
* without `free`. A value that no probe could produce stays `null` and the
|
|
10
|
+
* browser half renders it as unavailable.
|
|
11
|
+
*
|
|
12
|
+
* The command is POSIX shell; Linux and macOS are both covered. The only
|
|
13
|
+
* platform branch is `/proc/stat`, which Linux alone can answer — the CPU
|
|
14
|
+
* percentage is a difference between two samples of the same connection, so
|
|
15
|
+
* the manager keeps the previous sample per connection id.
|
|
16
|
+
*/
|
|
17
|
+
import { posix } from 'node:path'
|
|
18
|
+
import { errorText, isPosixPath, shellQuote } from './util.js'
|
|
19
|
+
|
|
20
|
+
/** A cached sample younger than this is reused instead of re-running the probe. */
|
|
21
|
+
export const METRICS_MIN_TTL_MS = 5000
|
|
22
|
+
const METRICS_TIMEOUT_MS = 8000
|
|
23
|
+
const METRICS_MAX_BYTES = 64 * 1024
|
|
24
|
+
|
|
25
|
+
export const MONITOR_INTERVAL_MIN_MS = 10000
|
|
26
|
+
export const MONITOR_INTERVAL_MAX_MS = 300000
|
|
27
|
+
export const MONITOR_THRESHOLD_MIN = 1
|
|
28
|
+
export const MONITOR_THRESHOLD_MAX = 100
|
|
29
|
+
|
|
30
|
+
/** Terminal appearance bounds; font sizes move in half-point steps. */
|
|
31
|
+
export const FONT_FAMILY_MAX_LENGTH = 200
|
|
32
|
+
export const FONT_SIZE_MIN = 9
|
|
33
|
+
export const FONT_SIZE_MAX = 24
|
|
34
|
+
export const FONT_SIZE_STEP = 0.5
|
|
35
|
+
export const LINE_HEIGHT_MIN = 1
|
|
36
|
+
export const LINE_HEIGHT_MAX = 2
|
|
37
|
+
export const LETTER_SPACING_MIN = -0.5
|
|
38
|
+
export const LETTER_SPACING_MAX = 2
|
|
39
|
+
|
|
40
|
+
/** A single transfer (upload or archive download) stays inside this range. */
|
|
41
|
+
export const TRANSFER_LIMIT_MIN_BYTES = 1024 * 1024
|
|
42
|
+
export const TRANSFER_LIMIT_MAX_BYTES = 8 * 1024 * 1024 * 1024
|
|
43
|
+
|
|
44
|
+
export const DEFAULT_MONITOR_CONFIG = Object.freeze({
|
|
45
|
+
enabled: true,
|
|
46
|
+
intervalMs: 30000,
|
|
47
|
+
cpu: Object.freeze({ enabled: true, threshold: 90 }),
|
|
48
|
+
mem: Object.freeze({ enabled: true, threshold: 90 }),
|
|
49
|
+
disk: Object.freeze({ enabled: true, threshold: 90 }),
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
export const DEFAULT_TERMINAL_CONFIG = Object.freeze({
|
|
53
|
+
fontFamily: '',
|
|
54
|
+
fontSize: 12.5,
|
|
55
|
+
lineHeight: 1.35,
|
|
56
|
+
letterSpacing: 0,
|
|
57
|
+
})
|
|
58
|
+
|
|
59
|
+
export const DEFAULT_TRANSFER_CONFIG = Object.freeze({ limitBytes: 512 * 1024 * 1024 })
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* The one document the DSH settings page reads and writes: terminal
|
|
63
|
+
* appearance, monitoring and the transfer cap. `monitor` is the same shape the
|
|
64
|
+
* monitor-only endpoints have always used.
|
|
65
|
+
*/
|
|
66
|
+
/** Editor behaviour: auto-save on by default, a second after typing stops. */
|
|
67
|
+
export const EDITOR_AUTOSAVE_MIN_MS = 300
|
|
68
|
+
export const EDITOR_AUTOSAVE_MAX_MS = 10000
|
|
69
|
+
export const DEFAULT_EDITOR_CONFIG = Object.freeze({
|
|
70
|
+
autoSave: true,
|
|
71
|
+
autoSaveDelayMs: 1000,
|
|
72
|
+
})
|
|
73
|
+
|
|
74
|
+
export const DEFAULT_SETTINGS = Object.freeze({
|
|
75
|
+
terminal: DEFAULT_TERMINAL_CONFIG,
|
|
76
|
+
monitor: DEFAULT_MONITOR_CONFIG,
|
|
77
|
+
transfer: DEFAULT_TRANSFER_CONFIG,
|
|
78
|
+
editor: DEFAULT_EDITOR_CONFIG,
|
|
79
|
+
})
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* The storage body a path lives on: `/home/alice/proj` -> `/home`.
|
|
83
|
+
*
|
|
84
|
+
* A relative path, a Windows path or a UNC path has no storage body to ask
|
|
85
|
+
* about, so the caller falls back to `$HOME` on the remote side.
|
|
86
|
+
*/
|
|
87
|
+
export function topLevelDir(dir) {
|
|
88
|
+
if (!isPosixPath(dir)) return null
|
|
89
|
+
const parts = posix.normalize(dir).split('/').filter((part) => part.length > 0)
|
|
90
|
+
if (parts.length === 0) return '/'
|
|
91
|
+
return `/${parts[0]}`
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* The probe script. Every line is independent and swallows its own failure, so
|
|
96
|
+
* one missing tool removes one marker instead of blanking the answer.
|
|
97
|
+
*
|
|
98
|
+
* @param {string | null | undefined} dir remote POSIX directory to measure disk usage for
|
|
99
|
+
* @returns {string} POSIX shell script
|
|
100
|
+
*/
|
|
101
|
+
export function metricsCommand(dir) {
|
|
102
|
+
const top = topLevelDir(dir)
|
|
103
|
+
// A validated POSIX path never looks like an option, so no `--` is needed
|
|
104
|
+
// (BSD `df` does not reliably accept one).
|
|
105
|
+
const diskTarget = top === null ? '"${HOME:-/}"' : shellQuote(top)
|
|
106
|
+
return [
|
|
107
|
+
// cores: GNU, then POSIX getconf, then BSD/macOS
|
|
108
|
+
'__rd_core="$(nproc 2>/dev/null || getconf _NPROCESSORS_ONLN 2>/dev/null || sysctl -n hw.ncpu 2>/dev/null)"',
|
|
109
|
+
`printf 'rd-core %s\\n' "$__rd_core"`,
|
|
110
|
+
// 1 minute load: Linux /proc/loadavg, then BSD/macOS `{ 1.2 3.4 5.6 }`
|
|
111
|
+
`__rd_load="$(awk '{print $1; exit}' /proc/loadavg 2>/dev/null || sysctl -n vm.loadavg 2>/dev/null)"`,
|
|
112
|
+
`printf 'rd-load %s\\n' "$__rd_load"`,
|
|
113
|
+
// Linux only: idle and total jiffies from the first /proc/stat line. The
|
|
114
|
+
// next sample of this connection differentiates them into a real CPU%.
|
|
115
|
+
// The sum stays in shell arithmetic: mawk (Debian's default awk) clamps
|
|
116
|
+
// `printf %d` at INT_MAX, which a busy /proc/stat line passes quickly.
|
|
117
|
+
'__rd_cpu=""',
|
|
118
|
+
'[ -r /proc/stat ] && read -r __rd_tag __rd_u __rd_n __rd_s __rd_idle __rd_w __rd_irq __rd_sirq __rd_steal __rd_rest < /proc/stat || true',
|
|
119
|
+
'[ "$__rd_tag" = "cpu" ] && __rd_total=$((__rd_u + __rd_n + __rd_s + __rd_idle + __rd_w + __rd_irq + __rd_sirq + __rd_steal)) || true',
|
|
120
|
+
'[ -n "$__rd_total" ] && [ "$__rd_total" -gt 0 ] && __rd_cpu="$__rd_idle $__rd_total" || true',
|
|
121
|
+
`[ -n "$__rd_cpu" ] && printf 'rd-cpu %s\\n' "$__rd_cpu" || true`,
|
|
122
|
+
// memory as "totalBytes availableBytes". awk only selects fields here; the
|
|
123
|
+
// multiplications stay in shell arithmetic for the same reason as above: a
|
|
124
|
+
// byte count above 2 GiB cannot survive mawk's `printf %d`.
|
|
125
|
+
'__rd_mem=""',
|
|
126
|
+
`__rd_fields="$(free -b 2>/dev/null | awk '$1=="Mem:"{printf "%s %s", $2, $7; exit}')"`,
|
|
127
|
+
// Never `set --` here: the remote login shell may be zsh, which does not
|
|
128
|
+
// word-split an unquoted expansion, so $2 would stay empty and the reading
|
|
129
|
+
// would silently disappear. POSIX parameter expansion works in every shell.
|
|
130
|
+
'__rd_a="${__rd_fields%% *}"; __rd_b="${__rd_fields#* }"',
|
|
131
|
+
'[ -n "$__rd_a" ] && [ "$__rd_a" != "$__rd_b" ] && __rd_mem="$__rd_a $__rd_b" || true',
|
|
132
|
+
'if [ -z "$__rd_mem" ]; then',
|
|
133
|
+
` __rd_fields="$(awk '/^MemTotal:/{t=$2} /^MemAvailable:/{a=$2} /^MemFree:/{f=$2} END{if(t!="") printf "%s %s", t, (a!=""?a:f)}' /proc/meminfo 2>/dev/null)"`,
|
|
134
|
+
' __rd_a="${__rd_fields%% *}"; __rd_b="${__rd_fields#* }"',
|
|
135
|
+
' [ -n "$__rd_a" ] && [ "$__rd_a" != "$__rd_b" ] && __rd_mem="$(( __rd_a * 1024 )) $(( __rd_b * 1024 ))" || true',
|
|
136
|
+
'fi',
|
|
137
|
+
'if [ -z "$__rd_mem" ]; then',
|
|
138
|
+
' __rd_ram="$(sysctl -n hw.memsize 2>/dev/null)"',
|
|
139
|
+
' __rd_page="$(sysctl -n hw.pagesize 2>/dev/null)"',
|
|
140
|
+
` __rd_pages="$(vm_stat 2>/dev/null | awk '/Pages free:/{fr=$NF+0} /Pages inactive:/{ia=$NF+0} /Pages speculative:/{sp=$NF+0} END{if(fr+ia+sp>0) printf "%d", fr+ia+sp}')"`,
|
|
141
|
+
' [ -n "$__rd_ram" ] && [ -n "$__rd_pages" ] && [ -n "$__rd_page" ] && __rd_mem="$__rd_ram $(( __rd_pages * __rd_page ))" || true',
|
|
142
|
+
'fi',
|
|
143
|
+
`printf 'rd-mem %s\\n' "$__rd_mem"`,
|
|
144
|
+
// The filesystem behind the top level directory, in POSIX form so the
|
|
145
|
+
// mount point (which may contain blanks) is the only free-form field.
|
|
146
|
+
`printf 'rd-disk %s\\n' "$(df -Pk ${diskTarget} 2>/dev/null | tail -n 1)"`,
|
|
147
|
+
].join('\n')
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function round1(value) {
|
|
151
|
+
return Math.round(value * 10) / 10
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function plainObject(value) {
|
|
155
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value) ? value : {}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function numbersIn(raw) {
|
|
159
|
+
const match = String(raw ?? '').match(/-?\d+(?:\.\d+)?/g)
|
|
160
|
+
return match === null ? [] : match.map(Number).filter((value) => Number.isFinite(value))
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function firstInteger(raw) {
|
|
164
|
+
const values = numbersIn(raw)
|
|
165
|
+
return values.length > 0 ? Math.trunc(values[0]) : null
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function positiveInt(raw) {
|
|
169
|
+
const value = firstInteger(raw)
|
|
170
|
+
return value !== null && value > 0 ? value : null
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function nonNegativeNumber(raw) {
|
|
174
|
+
const values = numbersIn(raw)
|
|
175
|
+
return values.length > 0 && values[0] >= 0 ? values[0] : null
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* A `/proc/stat` sample, accepted in any of the shapes we hand around:
|
|
180
|
+
* `{ idle, total }`, a previous full result (`{ cpu: { idle, total } }`), the
|
|
181
|
+
* raw first line, or the two numbers the probe prints.
|
|
182
|
+
*/
|
|
183
|
+
function parseCpuSample(value) {
|
|
184
|
+
if (value === null || value === undefined) return null
|
|
185
|
+
if (Array.isArray(value)) return sampleFromNumbers(value.map(Number))
|
|
186
|
+
if (typeof value === 'object') {
|
|
187
|
+
if (value.cpu !== undefined) return parseCpuSample(value.cpu)
|
|
188
|
+
return sampleFromNumbers([Number(value.idle), Number(value.total)])
|
|
189
|
+
}
|
|
190
|
+
const text = String(value).trim()
|
|
191
|
+
if (text.length === 0) return null
|
|
192
|
+
const numbers = numbersIn(text)
|
|
193
|
+
if (/^cpu\b/.test(text) && numbers.length >= 4) {
|
|
194
|
+
// Raw /proc/stat line: user nice system idle ... -> idle is the 4th field.
|
|
195
|
+
const total = numbers.reduce((sum, part) => sum + part, 0)
|
|
196
|
+
return total > 0 ? { idle: numbers[3], total } : null
|
|
197
|
+
}
|
|
198
|
+
return sampleFromNumbers(numbers.slice(0, 2))
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function sampleFromNumbers(numbers) {
|
|
202
|
+
const [idle, total] = numbers
|
|
203
|
+
if (!Number.isFinite(idle) || !Number.isFinite(total) || total <= 0) return null
|
|
204
|
+
return { idle, total }
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function emptyDisk() {
|
|
208
|
+
return { mount: null, totalBytes: null, usedBytes: null, availableBytes: null, percent: null }
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* `df -Pk` prints, per line:
|
|
213
|
+
* Filesystem 1024-blocks Used Available Capacity Mounted on
|
|
214
|
+
* The capacity column is the anchor: the three fields before it are total,
|
|
215
|
+
* used and available, and everything after it is the mount point (which may
|
|
216
|
+
* contain spaces). Locating it instead of counting from the left also survives
|
|
217
|
+
* device names that contain spaces (`map auto_home` on macOS).
|
|
218
|
+
*/
|
|
219
|
+
function parseDiskLine(raw) {
|
|
220
|
+
const text = String(raw ?? '').trim()
|
|
221
|
+
if (text.length === 0 || /^Filesystem\b/i.test(text)) return emptyDisk()
|
|
222
|
+
const fields = text.split(/\s+/)
|
|
223
|
+
const capacityAt = fields.findIndex((field) => /^\d+%$/.test(field))
|
|
224
|
+
let totalKb = null
|
|
225
|
+
let availableKb = null
|
|
226
|
+
let mount = null
|
|
227
|
+
if (capacityAt >= 3) {
|
|
228
|
+
totalKb = firstInteger(fields[capacityAt - 3])
|
|
229
|
+
availableKb = firstInteger(fields[capacityAt - 1])
|
|
230
|
+
mount = fields.slice(capacityAt + 1).join(' ')
|
|
231
|
+
} else if (fields.length >= 6) {
|
|
232
|
+
totalKb = firstInteger(fields[1])
|
|
233
|
+
availableKb = firstInteger(fields[3])
|
|
234
|
+
mount = fields.slice(5).join(' ')
|
|
235
|
+
}
|
|
236
|
+
if (totalKb === null || totalKb <= 0 || availableKb === null) return emptyDisk()
|
|
237
|
+
const totalBytes = totalKb * 1024
|
|
238
|
+
const availableBytes = Math.max(0, availableKb) * 1024
|
|
239
|
+
const usedBytes = Math.max(0, totalBytes - availableBytes)
|
|
240
|
+
return {
|
|
241
|
+
mount: mount === null || mount.length === 0 ? null : mount,
|
|
242
|
+
totalBytes,
|
|
243
|
+
usedBytes,
|
|
244
|
+
availableBytes,
|
|
245
|
+
percent: round1((usedBytes / totalBytes) * 100),
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
function markerValues(text) {
|
|
250
|
+
const values = new Map()
|
|
251
|
+
for (const rawLine of String(text ?? '').split(/\r?\n/)) {
|
|
252
|
+
const match = /^(rd-[a-z]+)\s*(.*)$/.exec(rawLine.trim())
|
|
253
|
+
if (match !== null) values.set(match[1], match[2].trim())
|
|
254
|
+
}
|
|
255
|
+
return values
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* Parse one probe answer. Markers may arrive in any order and may be missing
|
|
260
|
+
* or empty; every section is always present, with `null` for what the remote
|
|
261
|
+
* could not answer.
|
|
262
|
+
*
|
|
263
|
+
* @param {string} text probe stdout
|
|
264
|
+
* @param {{ idle: number, total: number } | null | undefined} previous last `/proc/stat` sample of the same connection
|
|
265
|
+
*/
|
|
266
|
+
export function parseMetrics(text, previous) {
|
|
267
|
+
const values = markerValues(text)
|
|
268
|
+
const cores = positiveInt(values.get('rd-core'))
|
|
269
|
+
const load1 = nonNegativeNumber(values.get('rd-load'))
|
|
270
|
+
const sample = parseCpuSample(values.get('rd-cpu'))
|
|
271
|
+
const before = parseCpuSample(previous)
|
|
272
|
+
|
|
273
|
+
let percent = null
|
|
274
|
+
let source = null
|
|
275
|
+
if (sample !== null && before !== null) {
|
|
276
|
+
const totalDelta = sample.total - before.total
|
|
277
|
+
const idleDelta = sample.idle - before.idle
|
|
278
|
+
// Counters reset on reboot and may be read out of order; a nonsensical
|
|
279
|
+
// delta falls through to the load average instead of reporting garbage.
|
|
280
|
+
if (totalDelta > 0 && idleDelta >= 0 && idleDelta <= totalDelta) {
|
|
281
|
+
percent = round1(((totalDelta - idleDelta) / totalDelta) * 100)
|
|
282
|
+
source = 'stat'
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
if (percent === null && load1 !== null && cores !== null) {
|
|
286
|
+
percent = round1(Math.min(100, (load1 / cores) * 100))
|
|
287
|
+
source = 'load'
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
const memNumbers = numbersIn(values.get('rd-mem'))
|
|
291
|
+
const memTotal = memNumbers.length > 0 && memNumbers[0] > 0 ? memNumbers[0] : null
|
|
292
|
+
const memAvailable = memNumbers.length > 1 ? Math.max(0, memNumbers[1]) : null
|
|
293
|
+
const memUsed = memTotal !== null && memAvailable !== null ? Math.max(0, memTotal - memAvailable) : null
|
|
294
|
+
const memPercent = memTotal !== null && memUsed !== null ? round1(Math.min(100, (memUsed / memTotal) * 100)) : null
|
|
295
|
+
|
|
296
|
+
return {
|
|
297
|
+
cpu: { percent, cores, load1, source },
|
|
298
|
+
mem: { totalBytes: memTotal, usedBytes: memUsed, percent: memPercent },
|
|
299
|
+
disk: parseDiskLine(values.get('rd-disk')),
|
|
300
|
+
sampledAt: new Date().toISOString(),
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
function cloneMetrics(value) {
|
|
305
|
+
return {
|
|
306
|
+
cpu: { ...value.cpu },
|
|
307
|
+
mem: { ...value.mem },
|
|
308
|
+
disk: { ...value.disk },
|
|
309
|
+
sampledAt: value.sampledAt,
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
function hasData(value) {
|
|
314
|
+
return (
|
|
315
|
+
value.cpu.cores !== null ||
|
|
316
|
+
value.cpu.percent !== null ||
|
|
317
|
+
value.cpu.load1 !== null ||
|
|
318
|
+
value.mem.totalBytes !== null ||
|
|
319
|
+
value.disk.totalBytes !== null
|
|
320
|
+
)
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
function firstLine(text) {
|
|
324
|
+
const line = String(text ?? '').trim().split(/\r?\n/)[0].trim()
|
|
325
|
+
return line.length > 200 ? `${line.slice(0, 200)}…` : line
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/**
|
|
329
|
+
* Per connection metric reads with a short cache.
|
|
330
|
+
*
|
|
331
|
+
* The cache is keyed by connection *and* directory, because the disk answer is
|
|
332
|
+
* about the storage behind that directory; the CPU sample is keyed by
|
|
333
|
+
* connection alone, because it is a difference between two reads of the same
|
|
334
|
+
* machine. Concurrent reads of the same key share one probe.
|
|
335
|
+
*/
|
|
336
|
+
export class MetricsManager {
|
|
337
|
+
constructor({ hostFor, onLog, ttlMs, now } = {}) {
|
|
338
|
+
this.hostFor = hostFor
|
|
339
|
+
this.onLog = typeof onLog === 'function' ? onLog : () => {}
|
|
340
|
+
// `ttlMs` and `now` are test seams; the floor keeps a busy UI from ever
|
|
341
|
+
// probing the remote host more often than every five seconds.
|
|
342
|
+
this.ttlMs = Math.max(METRICS_MIN_TTL_MS, Number.isFinite(ttlMs) ? Math.round(ttlMs) : METRICS_MIN_TTL_MS)
|
|
343
|
+
this.now = typeof now === 'function' ? now : Date.now
|
|
344
|
+
this.cache = new Map()
|
|
345
|
+
this.inflight = new Map()
|
|
346
|
+
this.samples = new Map()
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/** The last `/proc/stat` sample of a connection, or null before the first read. */
|
|
350
|
+
sampleFor(connectionId) {
|
|
351
|
+
return this.samples.get(String(connectionId)) ?? null
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
async read(connectionId, dir) {
|
|
355
|
+
const id = String(connectionId)
|
|
356
|
+
const target = typeof dir === 'string' ? dir.trim() : ''
|
|
357
|
+
const key = `${id}\u0000${target}`
|
|
358
|
+
const cached = this.cache.get(key)
|
|
359
|
+
if (cached !== undefined && this.now() - cached.at < this.ttlMs) return cloneMetrics(cached.value)
|
|
360
|
+
let pending = this.inflight.get(key)
|
|
361
|
+
if (pending === undefined) {
|
|
362
|
+
pending = this.#collect(id, target, key)
|
|
363
|
+
this.inflight.set(key, pending)
|
|
364
|
+
const clear = () => {
|
|
365
|
+
if (this.inflight.get(key) === pending) this.inflight.delete(key)
|
|
366
|
+
}
|
|
367
|
+
pending.then(clear, clear)
|
|
368
|
+
}
|
|
369
|
+
return cloneMetrics(await pending)
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
async #collect(connectionId, dir, key) {
|
|
373
|
+
const host = this.hostFor(connectionId)
|
|
374
|
+
if (host === undefined) throw new Error('connection not found')
|
|
375
|
+
let result
|
|
376
|
+
try {
|
|
377
|
+
result = await host.runCommand(metricsCommand(dir), null, { maxBytes: METRICS_MAX_BYTES, timeoutMs: METRICS_TIMEOUT_MS })
|
|
378
|
+
} catch (error) {
|
|
379
|
+
this.onLog('metrics failed', connectionId, errorText(error))
|
|
380
|
+
throw error
|
|
381
|
+
}
|
|
382
|
+
if (result.transportError) {
|
|
383
|
+
this.onLog('metrics failed', connectionId, result.transportError)
|
|
384
|
+
throw new Error(result.transportError)
|
|
385
|
+
}
|
|
386
|
+
const value = parseMetrics(result.stdout, this.samples.get(connectionId) ?? null)
|
|
387
|
+
const sample = parseCpuSample(markerValues(result.stdout).get('rd-cpu'))
|
|
388
|
+
if (sample !== null) this.samples.set(connectionId, sample)
|
|
389
|
+
if (!hasData(value)) {
|
|
390
|
+
const message = firstLine(result.stderr) || 'the remote host returned no metrics'
|
|
391
|
+
this.onLog('metrics unavailable', connectionId, message)
|
|
392
|
+
throw new Error(message)
|
|
393
|
+
}
|
|
394
|
+
this.cache.set(key, { at: this.now(), value })
|
|
395
|
+
return value
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
function clampInt(value, min, max, fallback) {
|
|
400
|
+
if (typeof value !== 'number' || !Number.isFinite(value)) return fallback
|
|
401
|
+
return Math.min(max, Math.max(min, Math.round(value)))
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
function booleanOr(value, fallback) {
|
|
405
|
+
return typeof value === 'boolean' ? value : fallback
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
function normalizeSection(value, fallback) {
|
|
409
|
+
const source = plainObject(value)
|
|
410
|
+
return {
|
|
411
|
+
enabled: booleanOr(source.enabled, fallback.enabled),
|
|
412
|
+
threshold: clampInt(source.threshold, MONITOR_THRESHOLD_MIN, MONITOR_THRESHOLD_MAX, fallback.threshold),
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
/**
|
|
417
|
+
* Fill in what a stored or posted monitor config left out, clamp what is out of
|
|
418
|
+
* range and drop unknown fields. `base` is the previously stored config, so a
|
|
419
|
+
* partial update keeps the settings it does not mention.
|
|
420
|
+
*/
|
|
421
|
+
export function normalizeMonitorConfig(value, base) {
|
|
422
|
+
const source = plainObject(value)
|
|
423
|
+
const fallback = base === undefined ? DEFAULT_MONITOR_CONFIG : normalizeMonitorConfig(base, undefined)
|
|
424
|
+
return {
|
|
425
|
+
enabled: booleanOr(source.enabled, fallback.enabled),
|
|
426
|
+
intervalMs: clampInt(source.intervalMs, MONITOR_INTERVAL_MIN_MS, MONITOR_INTERVAL_MAX_MS, fallback.intervalMs),
|
|
427
|
+
cpu: normalizeSection(source.cpu, fallback.cpu),
|
|
428
|
+
mem: normalizeSection(source.mem, fallback.mem),
|
|
429
|
+
disk: normalizeSection(source.disk, fallback.disk),
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
function roundTo(value, decimals) {
|
|
434
|
+
const factor = 10 ** decimals
|
|
435
|
+
return Math.round(value * factor) / factor
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
function clampNumber(value, min, max, decimals, fallback) {
|
|
439
|
+
if (typeof value !== 'number' || !Number.isFinite(value)) return fallback
|
|
440
|
+
return Math.min(max, Math.max(min, roundTo(value, decimals)))
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
function quantize(value, min, max, step, fallback) {
|
|
444
|
+
if (typeof value !== 'number' || !Number.isFinite(value)) return fallback
|
|
445
|
+
return Math.min(max, Math.max(min, roundTo(Math.round(value / step) * step, 2)))
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
const FONT_FAMILY_FORBIDDEN = /[;{}<>"'\\`]/g
|
|
449
|
+
const FONT_FAMILY_BREAKS = /[\r\n\u2028\u2029]/g
|
|
450
|
+
|
|
451
|
+
/**
|
|
452
|
+
* A font family lands in a CSS declaration, so only what a font stack can
|
|
453
|
+
* legitimately contain survives: the statement delimiters `;{}<>`, quotes,
|
|
454
|
+
* backslash and backtick are dropped, line breaks vanish, and every other
|
|
455
|
+
* whitespace run collapses to one space. Nothing left means "use the built-in
|
|
456
|
+
* font" (`''`).
|
|
457
|
+
*/
|
|
458
|
+
export function sanitizeFontFamily(value) {
|
|
459
|
+
if (typeof value !== 'string') return ''
|
|
460
|
+
return value
|
|
461
|
+
.replace(FONT_FAMILY_FORBIDDEN, '')
|
|
462
|
+
.replace(FONT_FAMILY_BREAKS, '')
|
|
463
|
+
.replace(/[\u0000-\u001f\u007f]+/g, ' ')
|
|
464
|
+
.replace(/\s+/g, ' ')
|
|
465
|
+
.trim()
|
|
466
|
+
.slice(0, FONT_FAMILY_MAX_LENGTH)
|
|
467
|
+
.trim()
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
function normalizeTerminalConfig(value, fallback) {
|
|
471
|
+
const source = plainObject(value)
|
|
472
|
+
return {
|
|
473
|
+
// Absent keeps the stored family; anything that is not a usable string
|
|
474
|
+
// clears back to the built-in font.
|
|
475
|
+
fontFamily: source.fontFamily === undefined ? fallback.fontFamily : sanitizeFontFamily(source.fontFamily),
|
|
476
|
+
fontSize: quantize(source.fontSize, FONT_SIZE_MIN, FONT_SIZE_MAX, FONT_SIZE_STEP, fallback.fontSize),
|
|
477
|
+
lineHeight: clampNumber(source.lineHeight, LINE_HEIGHT_MIN, LINE_HEIGHT_MAX, 2, fallback.lineHeight),
|
|
478
|
+
letterSpacing: clampNumber(source.letterSpacing, LETTER_SPACING_MIN, LETTER_SPACING_MAX, 2, fallback.letterSpacing),
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
function normalizeTransferConfig(value, fallback) {
|
|
483
|
+
const source = plainObject(value)
|
|
484
|
+
return {
|
|
485
|
+
limitBytes: clampInt(source.limitBytes, TRANSFER_LIMIT_MIN_BYTES, TRANSFER_LIMIT_MAX_BYTES, fallback.limitBytes),
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
/**
|
|
490
|
+
* Fill in what a stored or posted settings document left out (deep merge over
|
|
491
|
+
* `base`, the stored document), clamp what is out of range and drop unknown
|
|
492
|
+
* fields. Every call returns the complete three-section shape.
|
|
493
|
+
*/
|
|
494
|
+
export function normalizeSettings(value, base) {
|
|
495
|
+
const source = plainObject(value)
|
|
496
|
+
const fallback = base === undefined ? DEFAULT_SETTINGS : normalizeSettings(base, undefined)
|
|
497
|
+
return {
|
|
498
|
+
terminal: normalizeTerminalConfig(source.terminal, fallback.terminal),
|
|
499
|
+
monitor: normalizeMonitorConfig(source.monitor, fallback.monitor),
|
|
500
|
+
transfer: normalizeTransferConfig(source.transfer, fallback.transfer),
|
|
501
|
+
editor: {
|
|
502
|
+
autoSave: booleanOr(source.editor?.autoSave, fallback.editor.autoSave),
|
|
503
|
+
autoSaveDelayMs: clampInt(
|
|
504
|
+
source.editor?.autoSaveDelayMs,
|
|
505
|
+
EDITOR_AUTOSAVE_MIN_MS,
|
|
506
|
+
EDITOR_AUTOSAVE_MAX_MS,
|
|
507
|
+
fallback.editor.autoSaveDelayMs,
|
|
508
|
+
),
|
|
509
|
+
},
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
/**
|
|
514
|
+
* The settings document for a data directory that may still hold only the old
|
|
515
|
+
* `monitor.json`: its config becomes `settings.monitor`, so a saved interval or
|
|
516
|
+
* threshold survives the upgrade. A monitor section in the stored settings
|
|
517
|
+
* always wins; the legacy file is consulted only while none has been saved.
|
|
518
|
+
*/
|
|
519
|
+
export function migrateSettings(stored, legacyMonitor) {
|
|
520
|
+
const source = plainObject(stored)
|
|
521
|
+
if (source.monitor !== undefined) return normalizeSettings(source)
|
|
522
|
+
return normalizeSettings({ ...source, monitor: legacyMonitor })
|
|
523
|
+
}
|