fix(helper): уточнены замеры PoC и поведение выхода
- prevent_exit только при code.is_none(): иначе app.exit(0) блокировался и процесс добивал скрипт - замер ведётся по PrivateBytes — WorkingSetPrivate у простаивающих процессов занижен Windows - capability окон с пустым permissions: команды приложения не входят в ACL, плагинов нет - CSP дополнен connect-src для IPC по кастомному протоколу (Linux/macOS) - first_paint после двойного requestAnimationFrame, лог замера откатывается в temp при недоступности каталога exe Refs: 1.8.1, 1.8.2
This commit is contained in:
1 parent
4abe485e73
commit
82eb829851
5 files changed
+75
-44
No files matched your search
+53
-31
@@ -1,14 +1,18 @@
|
||||
# Замер private working set PoC «Штиль Помощник» (#1.8.1–1.8.2).
|
||||
# Замер памяти PoC «Штиль Помощник» (#1.8.1–1.8.2).
|
||||
#
|
||||
# Запускает release-сборку с флагом --measure-scenario: приложение само
|
||||
# открывает и закрывает окна по таймеру и пишет отметки этапов в
|
||||
# helper-tray-poc.measure.log рядом с exe. Скрипт снимает private working set
|
||||
# по отметкам: покой (30 с), открытое окно (+10 с), после закрытия (+10 с),
|
||||
# повторно открытое окно (+10 с). Время открытия берётся из строк
|
||||
# «window-opened ... ms=N» в том же логе.
|
||||
# helper-tray-poc.measure.log (рядом с exe, при недоступности — в %TEMP%).
|
||||
# Скрипт снимает по отметкам два счётчика дерева процессов:
|
||||
# PrivateBytes — committed private memory (решение принимаем по ней:
|
||||
# Windows урезает рабочий набор простаивающих процессов,
|
||||
# поэтому WorkingSetPrivate для покоя занижен);
|
||||
# WorkingSetPrivate — private working set, для справки.
|
||||
# Отметки: покой (30 с), открытое окно (+10 с), после закрытия (+10 с),
|
||||
# повторно открытое окно (+10 с). Время открытия — из строк
|
||||
# «window-opened ... ms=N» в логе.
|
||||
#
|
||||
# ОЗУ считается как сумма WorkingSetPrivate по дереву процессов:
|
||||
# процесс приложения + все дочерние msedgewebview2.exe (ищем по цепочке
|
||||
# Дерево: процесс приложения + все дочерние msedgewebview2.exe (по цепочке
|
||||
# родителей и по user-data-dir в командной строке).
|
||||
#
|
||||
# Использование: powershell -ExecutionPolicy Bypass -File measure.ps1 [-Runs 5]
|
||||
@@ -22,7 +26,10 @@ param(
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$WebViewMarker = 'ru.tbsoft.shtil.helper.poc'
|
||||
$LogPath = Join-Path (Split-Path $ExePath) 'helper-tray-poc.measure.log'
|
||||
$LogCandidates = @(
|
||||
(Join-Path (Split-Path $ExePath) 'helper-tray-poc.measure.log'),
|
||||
(Join-Path $env:TEMP 'helper-tray-poc.measure.log')
|
||||
)
|
||||
|
||||
if (-not (Test-Path $ExePath)) {
|
||||
throw "Не найден $ExePath — сначала выполните: pnpm tauri build"
|
||||
@@ -33,9 +40,12 @@ function Stop-Poc {
|
||||
Get-CimInstance Win32_Process -Filter "Name='msedgewebview2.exe'" |
|
||||
Where-Object { $_.CommandLine -and $_.CommandLine.Contains($WebViewMarker) } |
|
||||
ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }
|
||||
# Убитые процессы уходят не мгновенно; если не подождать, следующий прогон
|
||||
# посчитает их за свойства нового (fallback ищет по user-data-dir).
|
||||
Start-Sleep -Seconds 2
|
||||
}
|
||||
|
||||
function Get-TreePrivateWsMb([int]$AppPid) {
|
||||
function Get-TreeMemory([int]$AppPid) {
|
||||
$all = Get-CimInstance Win32_Process
|
||||
# Дочерние процессы приложения (WebView2 плодит дерево глубиной 2–3 уровня).
|
||||
$tree = New-Object 'System.Collections.Generic.List[int]'
|
||||
@@ -54,16 +64,18 @@ function Get-TreePrivateWsMb([int]$AppPid) {
|
||||
if (-not $tree.Contains($w.ProcessId)) { $tree.Add($w.ProcessId) }
|
||||
}
|
||||
$perf = Get-CimInstance Win32_PerfFormattedData_PerfProc_Process
|
||||
$app = ($perf | Where-Object IDProcess -eq $AppPid | Select-Object -First 1).WorkingSetPrivate
|
||||
$total = 0.0
|
||||
$pb = 0.0; $ws = 0.0
|
||||
foreach ($tpid in $tree) {
|
||||
$row = $perf | Where-Object IDProcess -eq $tpid | Select-Object -First 1
|
||||
if ($row) { $total += $row.WorkingSetPrivate }
|
||||
if ($row) {
|
||||
$pb += $row.PrivateBytes
|
||||
$ws += $row.WorkingSetPrivate
|
||||
}
|
||||
}
|
||||
[pscustomobject]@{
|
||||
Pids = $tree.Count
|
||||
AppMB = [math]::Round($(if ($app) { $app } else { 0 }) / 1MB, 1)
|
||||
TotalMB = [math]::Round($total / 1MB, 1)
|
||||
PbMB = [math]::Round($pb / 1MB, 1)
|
||||
WsMB = [math]::Round($ws / 1MB, 1)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -75,24 +87,25 @@ function Get-Median([double[]]$Values) {
|
||||
$results = @()
|
||||
for ($run = 1; $run -le $Runs; $run++) {
|
||||
Stop-Poc
|
||||
Remove-Item $LogPath -ErrorAction SilentlyContinue
|
||||
foreach ($log in $LogCandidates) { Remove-Item $log -ErrorAction SilentlyContinue }
|
||||
Write-Host "── Прогон $run из $Runs ──────────────"
|
||||
|
||||
$proc = Start-Process $ExePath -ArgumentList '--measure-scenario' -PassThru
|
||||
$seen = 0
|
||||
$opens = @()
|
||||
$sample = @{}
|
||||
$sample = @{ Done = $false }
|
||||
$deadline = (Get-Date).AddSeconds($TimeoutSec)
|
||||
|
||||
while ((Get-Date) -lt $deadline -and -not $sample.Done) {
|
||||
if (Test-Path $LogPath) {
|
||||
foreach ($line in (Get-Content $LogPath | Select-Object -Skip $seen)) {
|
||||
$logPath = $LogCandidates | Where-Object { Test-Path $_ } | Select-Object -First 1
|
||||
if ($logPath) {
|
||||
foreach ($line in (Get-Content $logPath | Select-Object -Skip $seen)) {
|
||||
$seen++
|
||||
switch -Regex ($line) {
|
||||
'stage open-window-1' { $sample.Idle = Get-TreePrivateWsMb $proc.Id }
|
||||
'stage close-window-1' { $sample.Open = Get-TreePrivateWsMb $proc.Id }
|
||||
'stage open-window-2' { $sample.AfterClose = Get-TreePrivateWsMb $proc.Id }
|
||||
'stage close-window-2' { $sample.WarmOpen = Get-TreePrivateWsMb $proc.Id }
|
||||
'stage open-window-1' { $sample.Idle = Get-TreeMemory $proc.Id }
|
||||
'stage close-window-1' { $sample.Open = Get-TreeMemory $proc.Id }
|
||||
'stage open-window-2' { $sample.AfterClose = Get-TreeMemory $proc.Id }
|
||||
'stage close-window-2' { $sample.WarmOpen = Get-TreeMemory $proc.Id }
|
||||
'window-opened .*ms=(\d+)' { $opens += [int]$Matches[1] }
|
||||
'stage done' { $sample.Done = $true }
|
||||
}
|
||||
@@ -101,7 +114,10 @@ for ($run = 1; $run -le $Runs; $run++) {
|
||||
Start-Sleep -Milliseconds 200
|
||||
}
|
||||
|
||||
$proc | Wait-Process -Timeout 15 -ErrorAction SilentlyContinue
|
||||
# После «stage done» приложение должно завершиться само (app.exit(0)
|
||||
# не блокируется prevent_exit — code задан).
|
||||
$null = $proc | Wait-Process -Timeout 10 -ErrorAction SilentlyContinue
|
||||
$selfExited = $proc.HasExited
|
||||
Stop-Poc
|
||||
|
||||
if (-not $sample.Done) {
|
||||
@@ -111,24 +127,30 @@ for ($run = 1; $run -le $Runs; $run++) {
|
||||
|
||||
$results += [pscustomobject]@{
|
||||
Run = $run
|
||||
IdleMB = $sample.Idle.TotalMB
|
||||
OpenMB = $sample.Open.TotalMB
|
||||
AfterCloseMB = $sample.AfterClose.TotalMB
|
||||
WarmOpenMB = $sample.WarmOpen.TotalMB
|
||||
IdlePbMB = $sample.Idle.PbMB
|
||||
IdleWsMB = $sample.Idle.WsMB
|
||||
OpenPbMB = $sample.Open.PbMB
|
||||
OpenWsMB = $sample.Open.WsMB
|
||||
AfterClosePb = $sample.AfterClose.PbMB
|
||||
AfterCloseWs = $sample.AfterClose.WsMB
|
||||
WarmOpenPb = $sample.WarmOpen.PbMB
|
||||
ColdOpenMs = $opens[0]
|
||||
WarmOpenMs = $opens[1]
|
||||
SelfExit = [bool]$selfExited
|
||||
}
|
||||
Write-Host (" покой {0} МБ · окно {1} МБ · после закрытия {2} МБ · открытие {3}/{4} мс" -f `
|
||||
$sample.Idle.TotalMB, $sample.Open.TotalMB, $sample.AfterClose.TotalMB, $opens[0], $opens[1])
|
||||
Write-Host (" покой {0}/{1} МБ · окно {2}/{3} МБ · после закрытия {4}/{5} МБ · открытие {6}/{7} мс" -f `
|
||||
$sample.Idle.PbMB, $sample.Idle.WsMB, $sample.Open.PbMB, $sample.Open.WsMB, `
|
||||
$sample.AfterClose.PbMB, $sample.AfterClose.WsMB, $opens[0], $opens[1])
|
||||
}
|
||||
|
||||
if (-not $results) { throw "Ни один прогон не завершился" }
|
||||
|
||||
Write-Host ""
|
||||
Write-Host "══ Итог ($($results.Count) прогонов): медиана [min–max] ══"
|
||||
foreach ($m in 'IdleMB','OpenMB','AfterCloseMB','WarmOpenMB','ColdOpenMs','WarmOpenMs') {
|
||||
Write-Host "══ Итог ($($results.Count) прогонов): медиана [min–max], PB = PrivateBytes, WS = WorkingSetPrivate ══"
|
||||
foreach ($m in 'IdlePbMB','IdleWsMB','OpenPbMB','OpenWsMB','AfterClosePb','AfterCloseWs','WarmOpenPb','ColdOpenMs','WarmOpenMs') {
|
||||
$v = @($results | ForEach-Object { [double]$_.$m })
|
||||
$med = Get-Median $v
|
||||
Write-Host (" {0,-13} {1,8} [{2} – {3}]" -f $m, $med, ($v | Measure-Object -Minimum).Minimum, ($v | Measure-Object -Maximum).Maximum)
|
||||
}
|
||||
if (-not ($results.SelfExit -contains $false)) { Write-Host " приложение завершилось само во всех прогонах" } else { Write-Warning "были прогоны без самостоятельного завершения" }
|
||||
$results | Format-Table -AutoSize
|
||||
@@ -1,9 +1,7 @@
|
||||
{
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "helper-windows",
|
||||
"description": "Окна Помощника, создаваемые динамически из меню трея",
|
||||
"description": "Окна Помощника, создаваемые динамически из меню трея. Команды приложения не входят в ACL, плагинов нет — разрешений не нужно",
|
||||
"windows": ["win-*"],
|
||||
"permissions": [
|
||||
"core:default"
|
||||
]
|
||||
"permissions": []
|
||||
}
|
||||
@@ -143,16 +143,21 @@ fn spawn_measure_scenario(app: AppHandle) {
|
||||
}
|
||||
|
||||
fn measure_log_file() -> Option<File> {
|
||||
let dir = std::env::current_exe()
|
||||
let exe_dir = std::env::current_exe()
|
||||
.ok()
|
||||
.and_then(|p| p.parent().map(|d| d.to_path_buf()))
|
||||
.unwrap_or_else(std::env::temp_dir);
|
||||
OpenOptions::new()
|
||||
.and_then(|p| p.parent().map(|d| d.to_path_buf()));
|
||||
for dir in [exe_dir, Some(std::env::temp_dir())].into_iter().flatten() {
|
||||
match OpenOptions::new()
|
||||
.create(true)
|
||||
.write(true)
|
||||
.truncate(true)
|
||||
.open(dir.join("helper-tray-poc.measure.log"))
|
||||
.ok()
|
||||
{
|
||||
Ok(f) => return Some(f),
|
||||
Err(e) => eprintln!("не удалось открыть лог в {}: {}", dir.display(), e),
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg_attr(mobile, tauri::mobile_entry_point)]
|
||||
@@ -181,10 +186,13 @@ pub fn run() {
|
||||
})
|
||||
.build(tauri::generate_context!())
|
||||
.expect("error while building tauri application");
|
||||
// Трею нельзя завершаться при закрытии последнего окна;
|
||||
// app.exit(0) при этом продолжает работать.
|
||||
// Трею нельзя завершаться при закрытии последнего окна (code == None);
|
||||
// при программном выходе code задан — prevent_exit не вызываем,
|
||||
// иначе app.exit(0) был бы заблокирован.
|
||||
app.run(|_handle, event| {
|
||||
if let tauri::RunEvent::ExitRequested { api, .. } = event {
|
||||
if let tauri::RunEvent::ExitRequested { code, api, .. } = event
|
||||
&& code.is_none()
|
||||
{
|
||||
api.prevent_exit();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
"app": {
|
||||
"windows": [],
|
||||
"security": {
|
||||
"csp": "default-src 'self'; style-src 'self' 'unsafe-inline'"
|
||||
"csp": "default-src 'self'; style-src 'self' 'unsafe-inline'; connect-src ipc: http://ipc.localhost"
|
||||
}
|
||||
},
|
||||
"bundle": {
|
||||
|
||||
@@ -17,10 +17,13 @@ const description = ref("");
|
||||
const sent = ref(false);
|
||||
|
||||
onMounted(() => {
|
||||
// Двойной rAF: вторая рамка гарантирует, что первая уже отрисована.
|
||||
requestAnimationFrame(() => {
|
||||
requestAnimationFrame(() => {
|
||||
void invoke("first_paint");
|
||||
});
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
||||
Reference in new issue
Block a user