ai_co_discuss 0.5.36 → 0.5.38
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/backend/server.py +3 -2
- package/backend/windows_thumbnail.py +89 -8
- package/docs/en/guide/remote.md +2 -0
- package/docs/en/guide/rooms.md +4 -2
- package/docs/guide/remote.md +2 -0
- package/docs/guide/rooms.md +4 -2
- package/frontend/locales/en/app.json +2 -0
- package/frontend/locales/en/settings.json +4 -0
- package/package.json +1 -1
- package/runner/discussion_launch.mjs +120 -1
- package/runner/relay_channel.mjs +46 -14
- package/runner/relay_timing.mjs +54 -0
- package/web/admin.js +1 -1
- package/web/app.js +145 -31
- package/web/i18n.js +2 -2
- package/web/markdown.js +5 -5
- package/web/modern.css +1 -1
- package/web/modern.js +66 -66
package/backend/server.py
CHANGED
|
@@ -4108,8 +4108,9 @@ class DiscussionHandler(BaseHTTPRequestHandler):
|
|
|
4108
4108
|
payload = {"site": site}
|
|
4109
4109
|
if command == "room-config" and "participants" in payload:
|
|
4110
4110
|
return self.save_local_room_configuration(command, payload)
|
|
4111
|
-
# The computer's own page plays a project media file straight from disk by a ticket, with ranges for seeking
|
|
4112
|
-
|
|
4111
|
+
# The computer's own page plays a project media file straight from disk by a ticket, with ranges for seeking;
|
|
4112
|
+
# a thumbnail comes back whole, as to another device.
|
|
4113
|
+
if command == "room-media" and not self.bridge_origin and payload.get("thumbnail") is not True:
|
|
4113
4114
|
return self.issue_media_ticket(payload)
|
|
4114
4115
|
# A connected website's page is another device's entry: it gets the same limits as the relay.
|
|
4115
4116
|
return self.run_local_command(command, payload, remote=bool(self.bridge_origin) and command != "machine-link")
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
"""Generate PNG or JPEG previews with the Windows system GDI+ codec."""
|
|
2
2
|
import ctypes
|
|
3
|
+
import os
|
|
4
|
+
import subprocess
|
|
3
5
|
from contextlib import ExitStack
|
|
4
6
|
from functools import lru_cache
|
|
5
7
|
from pathlib import Path
|
|
@@ -39,17 +41,25 @@ def graphics_library():
|
|
|
39
41
|
return library
|
|
40
42
|
|
|
41
43
|
|
|
42
|
-
def encode_preview(path, width, height, max_width=720):
|
|
44
|
+
def encode_preview(path, width, height, max_width=720, project=False):
|
|
43
45
|
"""Resize a bounded image, preserving transparency."""
|
|
44
46
|
if not width or not height or width * height > MAX_SOURCE_PIXELS:
|
|
45
47
|
return None
|
|
46
48
|
library = graphics_library()
|
|
47
|
-
|
|
48
|
-
width, height = max(1, round(width * scale)), max(1, round(height * scale))
|
|
49
|
+
max_height = max_width if project else 1600
|
|
49
50
|
with ExitStack() as cleanup:
|
|
50
51
|
source, bitmap, graphics = c_void_p(), c_void_p(), c_void_p()
|
|
51
52
|
checked(library.GdipLoadImageFromFile(str(path), byref(source)))
|
|
52
53
|
cleanup.callback(library.GdipDisposeImage, source)
|
|
54
|
+
source_width, source_height = c_uint(), c_uint()
|
|
55
|
+
checked(library.GdipGetImageWidth(source, byref(source_width)))
|
|
56
|
+
checked(library.GdipGetImageHeight(source, byref(source_height)))
|
|
57
|
+
if source_width.value * source_height.value > MAX_SOURCE_PIXELS:
|
|
58
|
+
return None
|
|
59
|
+
# JPEG header dimensions may already include EXIF rotation. Draw in native pixel space first.
|
|
60
|
+
scale = min(1, max_width / source_width.value, max_height / source_height.value)
|
|
61
|
+
width = max(1, round(source_width.value * scale))
|
|
62
|
+
height = max(1, round(source_height.value * scale))
|
|
53
63
|
checked(library.GdipCreateBitmapFromScan0(width, height, 0, ARGB32, None, byref(bitmap)))
|
|
54
64
|
cleanup.callback(library.GdipDisposeImage, bitmap)
|
|
55
65
|
checked(library.GdipGetImageGraphicsContext(bitmap, byref(graphics)))
|
|
@@ -60,20 +70,36 @@ def encode_preview(path, width, height, max_width=720):
|
|
|
60
70
|
checked(library.GdipCreateImageAttributes(byref(attributes)))
|
|
61
71
|
cleanup.callback(library.GdipDisposeImageAttributes, attributes)
|
|
62
72
|
checked(library.GdipSetImageAttributesWrapMode(attributes, 3, 0, 0))
|
|
63
|
-
source_width, source_height = c_uint(), c_uint()
|
|
64
|
-
checked(library.GdipGetImageWidth(source, byref(source_width)))
|
|
65
|
-
checked(library.GdipGetImageHeight(source, byref(source_height)))
|
|
66
|
-
if source_width.value * source_height.value > MAX_SOURCE_PIXELS:
|
|
67
|
-
return None
|
|
68
73
|
checked(library.GdipDrawImageRectRectI(graphics, source, 0, 0, width, height, 0, 0,
|
|
69
74
|
source_width, source_height, 2, attributes, None, None))
|
|
70
75
|
encoder = preview_encoder(library, bitmap, width, height)
|
|
76
|
+
if project:
|
|
77
|
+
apply_image_orientation(library, source, bitmap)
|
|
71
78
|
with TemporaryDirectory() as directory:
|
|
72
79
|
output = Path(directory) / "preview"
|
|
73
80
|
checked(library.GdipSaveImageToFile(bitmap, str(output), encoder, None))
|
|
74
81
|
return output.read_bytes()
|
|
75
82
|
|
|
76
83
|
|
|
84
|
+
def apply_image_orientation(library, source, bitmap):
|
|
85
|
+
"""Apply the source EXIF orientation to the rendered bitmap before exporting without metadata."""
|
|
86
|
+
tag = 0x112
|
|
87
|
+
size = c_uint()
|
|
88
|
+
if library.GdipGetPropertyItemSize(source, tag, byref(size)) or not size.value:
|
|
89
|
+
return
|
|
90
|
+
class PropertyItem(Structure):
|
|
91
|
+
_fields_ = [("tag", c_uint), ("length", c_uint), ("type", ctypes.c_ushort), ("value", c_void_p)]
|
|
92
|
+
buffer = ctypes.create_string_buffer(size.value)
|
|
93
|
+
if library.GdipGetPropertyItem(source, tag, size, buffer):
|
|
94
|
+
return
|
|
95
|
+
item = PropertyItem.from_buffer(buffer)
|
|
96
|
+
if item.type == 3 and item.length == 2 and item.value:
|
|
97
|
+
orientation = ctypes.c_ushort.from_address(item.value).value
|
|
98
|
+
rotation = {2: 4, 3: 2, 4: 6, 5: 5, 6: 1, 7: 7, 8: 3}.get(orientation)
|
|
99
|
+
if rotation is not None:
|
|
100
|
+
checked(library.GdipImageRotateFlip(bitmap, rotation))
|
|
101
|
+
|
|
102
|
+
|
|
77
103
|
def preview_encoder(library, bitmap, width, height):
|
|
78
104
|
"""Keep transparency in PNG, otherwise use the system JPEG encoder."""
|
|
79
105
|
pixels = BitmapData()
|
|
@@ -86,3 +112,58 @@ def preview_encoder(library, bitmap, width, height):
|
|
|
86
112
|
return PNG_ENCODER
|
|
87
113
|
finally:
|
|
88
114
|
library.GdipBitmapUnlockBits(bitmap, byref(pixels))
|
|
115
|
+
|
|
116
|
+
def decode_system_webp(path, output):
|
|
117
|
+
"""Use the Windows Imaging Component WebP decoder if registered, keeping transparency."""
|
|
118
|
+
command = r"""
|
|
119
|
+
$ErrorActionPreference = 'Stop'
|
|
120
|
+
Add-Type -AssemblyName PresentationCore
|
|
121
|
+
$decoder = [Windows.Media.Imaging.BitmapDecoder]::Create(
|
|
122
|
+
[Uri]::new($env:CODISCUSS_WEBP_INPUT), 'PreservePixelFormat', 'OnLoad')
|
|
123
|
+
$frame = $decoder.Frames[0]
|
|
124
|
+
$encoder = [Windows.Media.Imaging.PngBitmapEncoder]::new()
|
|
125
|
+
$encoder.Frames.Add($frame)
|
|
126
|
+
$stream = [IO.File]::Create($env:CODISCUSS_WEBP_OUTPUT)
|
|
127
|
+
try { $encoder.Save($stream) } finally { $stream.Dispose() }
|
|
128
|
+
"""
|
|
129
|
+
powershell = Path(os.environ["SystemRoot"]) / "System32/WindowsPowerShell/v1.0/powershell.exe"
|
|
130
|
+
subprocess.run([str(powershell), "-NoProfile", "-NonInteractive", "-Command", command],
|
|
131
|
+
env={**os.environ, "CODISCUSS_WEBP_INPUT": str(path), "CODISCUSS_WEBP_OUTPUT": str(output)},
|
|
132
|
+
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True, timeout=8,
|
|
133
|
+
creationflags=subprocess.CREATE_NO_WINDOW)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
if __name__ == "__main__":
|
|
137
|
+
# The runner supplies an already opened project file as stdin. Never resolve a project-supplied module.
|
|
138
|
+
import sys
|
|
139
|
+
|
|
140
|
+
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
|
141
|
+
from backend.server import image_size
|
|
142
|
+
|
|
143
|
+
with TemporaryDirectory() as directory:
|
|
144
|
+
path = Path(directory) / "source"
|
|
145
|
+
remaining = os.fstat(sys.stdin.fileno()).st_size
|
|
146
|
+
if not 0 < remaining <= 64 * 1024 * 1024:
|
|
147
|
+
sys.exit(0)
|
|
148
|
+
with path.open("wb") as out:
|
|
149
|
+
while remaining:
|
|
150
|
+
chunk = sys.stdin.buffer.read(min(remaining, 1024 * 1024))
|
|
151
|
+
if not chunk:
|
|
152
|
+
sys.exit(0)
|
|
153
|
+
out.write(chunk)
|
|
154
|
+
remaining -= len(chunk)
|
|
155
|
+
with path.open("rb") as source:
|
|
156
|
+
width, height = image_size(source)
|
|
157
|
+
source.seek(0)
|
|
158
|
+
webp = source.read(12)[8:12] == b"WEBP"
|
|
159
|
+
if not width or not height or width * height > MAX_SOURCE_PIXELS:
|
|
160
|
+
sys.exit(0)
|
|
161
|
+
if webp:
|
|
162
|
+
decoded = Path(directory) / "decoded.png"
|
|
163
|
+
decode_system_webp(path, decoded)
|
|
164
|
+
path = decoded
|
|
165
|
+
# The longest side asked for: 1440 for the preview, smaller for the file page's thumbnails.
|
|
166
|
+
side = int(sys.argv[1]) if len(sys.argv) > 1 and sys.argv[1].isdigit() else 1440
|
|
167
|
+
result = encode_preview(path, width, height, max(64, min(side, 1440)), project=True)
|
|
168
|
+
if result and len(result) < os.fstat(sys.stdin.fileno()).st_size:
|
|
169
|
+
sys.stdout.buffer.write(result)
|
package/docs/en/guide/remote.md
CHANGED
|
@@ -58,3 +58,5 @@ Phones support portrait layout only. Tablets support both portrait and landscape
|
|
|
58
58
|
- **Some changes require the computer:** Changing software executable paths, browsing outside Saved projects, and adding a new device must be done at the computer.
|
|
59
59
|
- **Attachment cache:** Pictures and files viewed through the relay are cached in this device’s browser and cleared when you unpair on this device.
|
|
60
60
|
- **Clearing browser data requires pairing again:** Clearing browser data removes the device key. The handoff command also expires after 10 minutes, so keep the phone's clock reasonably accurate.
|
|
61
|
+
|
|
62
|
+
**View file relay timings.** On your phone, open Settings → Account → Paired devices and expand Recent relay timings (ms). The latest 12 file requests show response frame sizes in bytes and estimates for the phone link, site processing, computer link and local processing. The two location codes identify the phone request and computer connection ingress respectively. A dash means unavailable.
|
package/docs/en/guide/rooms.md
CHANGED
|
@@ -42,11 +42,13 @@ Rooms created by a host inherit its folder. Select the arrow to the left of the
|
|
|
42
42
|
|
|
43
43
|
### 3. Set project directories and browse project files
|
|
44
44
|
|
|
45
|
+
When viewing a project image through the relay on another device, supported images open as a “Reduced preview”. Choose “View original” for full detail (under file actions on narrow screens). Save downloads the original file. The local computer displays the original directly, as do other devices when a smaller preview cannot be generated.
|
|
46
|
+
|
|
45
47
|
“File changes” below an answer shows the number of changed files and lines added or removed. Lists of five files or fewer open by default. Select the file count to open a longer list. Read-only visitors can see the list, but only the room owner can view patches.
|
|
46
48
|
|
|
47
49
|
- **Add or remove directories.** A room supports one primary directory and up to eight additional directories. After creating a room, open the “Room” tab at the top of the room and find “Project folder”. Add or remove additional directories there. Changes apply from each member’s next run and do not interrupt a session. A primary directory cannot be changed after it is set. If the room was created without one, you can set it once in the same section. Members can access all room directories subject to their individual project permissions.
|
|
48
|
-
- **Open Files.** In the tabs at the top of the room, select “Files” to browse directories, file sizes, and modification times. Switch between the primary and additional directories at the top. A project directory is required.
|
|
49
|
-
- **Preview files.** Select a file to open its floating preview. Supported previews include plain text, code, rendered Markdown, static HTML with a source view, zoomable and rotatable images, audio and video with speed and full-screen controls, CSV tables, subtitle timelines (SRT, VTT, ASS, LRC), read-only Word, Excel, PowerPoint and PDF, Premiere project XML, and zip archives listed like a folder, where selecting a file inside opens it in a new tab.
|
|
50
|
+
- **Open Files.** In the tabs at the top of the room, select “Files” to browse directories, file sizes, and modification times. Switch between the primary and additional directories at the top. A project directory is required. The “Icon view” button at the top right lays the folder out as tiles, with thumbnails for PNG, JPG, and WebP images; “List view” switches back. Thumbnails are made by the computer and currently only on Windows; other images and files show their icons.
|
|
51
|
+
- **Preview files.** Select a file to open its floating preview. Supported previews include plain text, code, rendered Markdown, static HTML with a source view, zoomable and rotatable images, audio and video with speed and full-screen controls, CSV tables, subtitle timelines (SRT, VTT, ASS, LRC), read-only Word, Excel, PowerPoint and PDF, Premiere project XML, and zip archives listed like a folder, where selecting a file inside opens it in a new tab. Images in Markdown display inline the way message images do; select one to zoom. Paths are accepted as common editors accept them: relative paths, project paths starting with `/`, absolute paths inside the room's project directories (such as `D:\Project\art\a.png` or `file:///D:/Project/art/a.png`), and web addresses. Files outside the room's project directories are not read. Images load as you scroll near them; landscape images fill the width and portrait images fit the window height. Other devices get a copy the computer compressed. Opening a ZIP attachment or project file loads the directory first. Select an entry to read it (up to 64 MiB), or choose “Download” to save the archive.
|
|
50
52
|
- **Tabs, split view, and collapse.** Open multiple files and switch between tabs. Use the preview controls to split the view on the right or use “File location” to return to the containing folder. HTML previews also offer “Open in new tab”. Select “Collapse” in the title bar to keep the preview as a floating button in the corner. It restores the same file and scroll position when you return to the room. Close it to clear the preview.
|
|
51
53
|
- **Quote and annotate.** Select text in a Markdown preview or a member’s answer and choose “Add to conversation”. Enter a note and press Enter. The source is marked with a number and the composer shows the number of notes. On a computer, open the notes list, choose “Edit annotation”, and drag the bottom-right corner of the editor to resize it. Sending the message adds a file path and line number, the member and message ID, or for a message attachment its message ID and attachment ID. An `@` inside a quote does not wake a member.
|
|
52
54
|
- **Manage project files.** Select “Project” at the start of the path bar to open your projects and drafts. Use the top controls to create folders and upload files (up to 20 MB each). File menus offer “Download” (“Download folder” for a folder, packed as a ZIP), “Rename”, “Copy”, “Cut”, and “Delete”. Paste into the destination folder. Deleted files and replaced versions go to “Recycle bin” for 30 days, where they can be restored. In source view, the pencil button edits text files up to 1 MB. Project and draft roots, and folders currently used as room project directories, cannot be renamed, moved, or deleted.
|
package/docs/guide/remote.md
CHANGED
|
@@ -59,3 +59,5 @@ npm 安装默认提供本机站点,没有随包可直接使用的公共线上
|
|
|
59
59
|
- **只能在电脑上改的项**:软件可执行路径、常用项目范围之外的目录、以及添加新设备,都只能在电脑前操作。
|
|
60
60
|
- **附件缓存**:经中转看过的图片和文件会缓存在这台设备的浏览器里,在这台设备上解除配对时清除。
|
|
61
61
|
- **清除浏览器数据需重配**:手机清理浏览器数据会删掉设备密钥,需回到电脑前重新配对;另外转交命令 10 分钟后作废,请保持手机系统时间大致准确。
|
|
62
|
+
|
|
63
|
+
**查看文件中转耗时**:在手机上打开“设置 → 账号 → 已配对的设备”,展开“最近中转耗时(毫秒)”查看最近 12 次文件请求的回应帧字节数与耗时。四列依次估算手机线路、站点内部、电脑线路和本机处理;机房代码依次属于手机请求和电脑连接。缺少测量用横线表示。
|
package/docs/guide/rooms.md
CHANGED
|
@@ -40,11 +40,13 @@
|
|
|
40
40
|
|
|
41
41
|
### 3. 设置多个项目目录并浏览项目文件
|
|
42
42
|
|
|
43
|
+
在手机等设备经中转预览项目图片时,支持的图片先显示“缩小图”。需要细节可点“查看原图”(窄屏在“文件操作”菜单中),保存按钮下载原文件。本机网页直接显示原图;电脑无法生成更小的预览时,其他设备也显示原图。
|
|
44
|
+
|
|
43
45
|
回答下方的“文件改动”显示已修改的文件数和增删行数。改动不超过 5 个文件时默认展开,超过时点击文件数查看清单。可读房间的访客也能看清单,只有房主能看补丁。
|
|
44
46
|
|
|
45
47
|
- **增删项目目录**:一个房间可有 1 个主项目目录和最多 8 个其他项目目录。建房后打开顶部“房间”页,在“项目目录”区域可增删其他目录,保存后从各成员下一次执行起生效,不中断会话。主目录设置后不能更改;建房时未设的,可在同一行补设一次。成员按各自项目权限读写全部目录。
|
|
46
|
-
-
|
|
47
|
-
- **预览文件**:点击文件打开悬浮预览,支持纯文本、代码、Markdown 渲染、HTML 静态渲染并可切换源码;图片可缩放、旋转;音视频带倍速与全屏直接播放;CSV 显示为表格,字幕(SRT、VTT、ASS、LRC)显示为时间轴;Word、Excel、PowerPoint 与 PDF 只读预览;Premiere 工程显示其 XML;zip 压缩包像文件夹一样列出其中的文件夹与文件,点击其中的文件在新标签中预览。Markdown
|
|
48
|
+
- **打开“文件”页**:房间顶部的标签栏点“文件”,浏览目录、文件大小与修改时间,上方可切换主目录与其他项目目录。浏览文件需要已设置项目目录。右上角的“图标视图”按钮把列表换成图标排列,PNG、JPG、WebP 图片显示缩略图,再点“列表视图”换回;缩略图由这台电脑生成,目前只在 Windows 电脑上有,其他图片和文件显示图标。
|
|
49
|
+
- **预览文件**:点击文件打开悬浮预览,支持纯文本、代码、Markdown 渲染、HTML 静态渲染并可切换源码;图片可缩放、旋转;音视频带倍速与全屏直接播放;CSV 显示为表格,字幕(SRT、VTT、ASS、LRC)显示为时间轴;Word、Excel、PowerPoint 与 PDF 只读预览;Premiere 工程显示其 XML;zip 压缩包像文件夹一样列出其中的文件夹与文件,点击其中的文件在新标签中预览。Markdown 中的图片与消息里的图片显示方式相同,在正文中直接显示,点击可放大查看。支持常见编辑器的写法:相对路径、以 `/` 开头的项目内路径、房间项目目录内的绝对路径(如 `D:\项目\插图\a.png`、`file:///D:/项目/插图/a.png`)与网络地址;房间项目目录之外的文件不会读取。滚动到附近才载入,横图铺满宽度、竖图按窗口高度显示;在其他设备上看到的是电脑压缩过的版本。打开房间附件或项目中的 ZIP 时先显示目录,点包内文件才读取内容。单个文件最多预览 64 MiB,也可以点“下载”保存整个压缩包。
|
|
48
50
|
- **多标签、分屏与收起**:可同时打开多个文件以标签切换,在预览栏切换为右侧分屏、或点“文件位置”回到所在文件夹。HTML 预览还可以“在新标签页打开”。点标题栏“收起”缩成内容区角落的悬浮按钮,切到其他房间后点它即可回到原文件与滚动位置,关闭才清空。
|
|
49
51
|
- **摘录批注**:在 Markdown 预览或成员回答正文中选中文字点“添加到对话”,可输入批注并回车,原文标出编号,输入框上方显示“N 条注释”。在电脑上,打开注释列表,点“修改批注”,可拖动编辑框右下角调整宽高。发送时自动附带文件路径+行号、成员+消息编号,或消息附件所属的消息编号与附件 ID,引用中的 `@` 不会唤醒成员。
|
|
50
52
|
- **整理文件**:点路径栏最前面的“项目”,可以打开你所有的项目和草稿。上方按钮用于新建文件夹和上传文件(单个不超过 20 MB);每行的菜单里有“下载”(文件夹为“下载文件夹”,打包成 ZIP)、“重命名”、“复制”、“剪切”、“删除”,复制或剪切后到目标文件夹点“粘贴”。删除的文件和被替换掉的旧版放进“回收区”,保留 30 天,可以还原。在源码视图点铅笔按钮可以编辑文本文件(不超过 1 MB)。项目、草稿文件夹本身,以及房间正在用作项目目录的文件夹,都不能改名、移动或删除。
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
{
|
|
2
|
+
"最近中转耗时(毫秒)": "Recent relay timings (ms)",
|
|
3
|
+
"手机线路 {mobile} · 站点 {site} · 电脑线路 {link} · 本机 {local}": "Phone link {mobile} · Site {site} · Computer link {link} · Local {local}",
|
|
2
4
|
"需连接本机服务": "Local service connection required",
|
|
3
5
|
"读取中…": "Loading…",
|
|
4
6
|
"{value1} · 未配置": "{value1} · Not configured",
|
|
@@ -478,6 +480,8 @@
|
|
|
478
480
|
"正在读取项目目录": "Loading project folder",
|
|
479
481
|
"重新读取目录": "Reload folder",
|
|
480
482
|
"此文件夹为空": "This folder is empty",
|
|
483
|
+
"列表视图": "List view",
|
|
484
|
+
"图标视图": "Icon view",
|
|
481
485
|
"{value1} 项": "{value1} items",
|
|
482
486
|
",已显示 {value1} 项": "; {value1} shown",
|
|
483
487
|
"正在排版 Word 文档…": "Laying out Word document…",
|
package/package.json
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { ensure_global_experts_migrated, replace_global_experts, change_project_expert, project_experts } from './experts.mjs';
|
|
2
|
-
import { local_settings } from './discussion_setup.mjs';
|
|
2
|
+
import { detect_python, local_settings } from './discussion_setup.mjs';
|
|
3
3
|
/** Shared launch configuration for an existing AI conversation and the local website. */
|
|
4
4
|
import { spawn } from 'node:child_process';
|
|
5
5
|
import { createHash, randomUUID } from 'node:crypto';
|
|
@@ -739,6 +739,72 @@ export async function room_page(home, raw, { trust = false, parts = false } = {}
|
|
|
739
739
|
// Through the relay a media file comes whole, in parts, so another device plays at most this much.
|
|
740
740
|
export const REMOTE_MEDIA_MAX_BYTES = 64 * 1024 * 1024;
|
|
741
741
|
|
|
742
|
+
const PROJECT_PREVIEW_SLOTS = 12;
|
|
743
|
+
const PROJECT_PREVIEW_CONCURRENCY = 2;
|
|
744
|
+
const PROJECT_PREVIEW_MAX = 8 * 1024 * 1024;
|
|
745
|
+
// The file page's icon view: the longest side of an image's thumbnail, and how many of them the computer keeps.
|
|
746
|
+
const PROJECT_THUMBNAIL_SIDE = 256;
|
|
747
|
+
const PROJECT_THUMBNAIL_SLOTS = 400;
|
|
748
|
+
|
|
749
|
+
/** Keep completed previews in an LRU; queued and running versions share a promise until encoding finishes. */
|
|
750
|
+
export function project_preview_reader(probe, slots = PROJECT_PREVIEW_SLOTS) {
|
|
751
|
+
const cached = new Map(), pending = new Map(), waiting = [];
|
|
752
|
+
let python, running = 0;
|
|
753
|
+
async function generate(home, key, encode) {
|
|
754
|
+
if (running === PROJECT_PREVIEW_CONCURRENCY) await new Promise(resolve => waiting.push(resolve));
|
|
755
|
+
else running++;
|
|
756
|
+
try {
|
|
757
|
+
python ??= Promise.resolve().then(() => probe(home));
|
|
758
|
+
const bytes = await encode(await python);
|
|
759
|
+
if (bytes) {
|
|
760
|
+
cached.set(key, bytes);
|
|
761
|
+
if (cached.size > slots) cached.delete(cached.keys().next().value);
|
|
762
|
+
}
|
|
763
|
+
return bytes;
|
|
764
|
+
} catch { return null; }
|
|
765
|
+
finally {
|
|
766
|
+
pending.delete(key);
|
|
767
|
+
if (waiting.length) waiting.shift()();
|
|
768
|
+
else running--;
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
return (home, key, encode) => {
|
|
772
|
+
if (cached.has(key)) {
|
|
773
|
+
const bytes = cached.get(key);
|
|
774
|
+
cached.delete(key);
|
|
775
|
+
cached.set(key, bytes);
|
|
776
|
+
return bytes;
|
|
777
|
+
}
|
|
778
|
+
if (!pending.has(key)) pending.set(key, generate(home, key, encode));
|
|
779
|
+
return pending.get(key);
|
|
780
|
+
};
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
const project_preview_bytes = project_preview_reader(home => detect_python(local_settings(home).python));
|
|
784
|
+
const project_thumbnail_bytes = project_preview_reader(home => detect_python(local_settings(home).python), PROJECT_THUMBNAIL_SLOTS);
|
|
785
|
+
|
|
786
|
+
async function encode_project_preview(preview_python, file, side = 1440) {
|
|
787
|
+
const script = join(import.meta.dirname, '..', 'backend', 'windows_thumbnail.py');
|
|
788
|
+
const fd = openSync(file, 'r');
|
|
789
|
+
let child;
|
|
790
|
+
try {
|
|
791
|
+
child = spawn(preview_python, ['-I', '-B', script, String(side)], {
|
|
792
|
+
windowsHide: true, timeout: 15000, stdio: [fd, 'pipe', 'ignore'], cwd: dirname(script),
|
|
793
|
+
});
|
|
794
|
+
} finally { closeSync(fd); }
|
|
795
|
+
return new Promise((resolve, reject) => {
|
|
796
|
+
let size = 0;
|
|
797
|
+
const chunks = [];
|
|
798
|
+
child.stdout.on('data', chunk => {
|
|
799
|
+
size += chunk.length;
|
|
800
|
+
if (size <= PROJECT_PREVIEW_MAX) chunks.push(chunk);
|
|
801
|
+
else child.kill();
|
|
802
|
+
});
|
|
803
|
+
child.on('error', reject);
|
|
804
|
+
child.on('close', code => resolve(code === 0 && size && size <= PROJECT_PREVIEW_MAX ? Buffer.concat(chunks) : null));
|
|
805
|
+
});
|
|
806
|
+
}
|
|
807
|
+
|
|
742
808
|
/**
|
|
743
809
|
* One image, video or audio file of the room's project (see `project_media`). For the computer's own page it names
|
|
744
810
|
* the real file, which the local site streams by a ticket and never shows the page; with `parts` (another device,
|
|
@@ -747,12 +813,18 @@ export const REMOTE_MEDIA_MAX_BYTES = 64 * 1024 * 1024;
|
|
|
747
813
|
*/
|
|
748
814
|
export async function room_media(home, raw, { trust = false, parts = false } = {}) {
|
|
749
815
|
const { input, config } = await member_room_context(home, raw, { trust });
|
|
816
|
+
// A Markdown file may name an image by its absolute path on this computer: it is read from the room directory holding
|
|
817
|
+
// it. `/…` is such a path where one exists (macOS, Linux), otherwise a path from the project folder, as editors take it.
|
|
818
|
+
const named = String(input.path || '');
|
|
819
|
+
if (/^([a-zA-Z]:[\\/]|\\\\)/.test(named)) Object.assign(input, absolute_room_path(config, named, win32));
|
|
820
|
+
else if (named.startsWith('/')) Object.assign(input, (process.platform !== 'win32' && absolute_room_path(config, named, posix, false)) || { path: named.replace(/^\/+/, '') });
|
|
750
821
|
const root = input.root ?? 0;
|
|
751
822
|
const offset = input.offset ?? 0;
|
|
752
823
|
const directory = files_root(home, config, root);
|
|
753
824
|
if (!Number.isSafeInteger(offset) || offset < 0) throw new Error('文件读取位置无效');
|
|
754
825
|
// `download` reads any regular file for saving, not only the kinds the preview shows.
|
|
755
826
|
const { file, ...media } = project_media(directory, input.path, { download: input.download === true });
|
|
827
|
+
if (input.thumbnail === true) return { room_id: input.room_id, root, ...media, ...await project_thumbnail(home, directory, input.path, file, media) };
|
|
756
828
|
// The folder goes to the computer's own website alone, for a page opened in a tab (it never reaches a page).
|
|
757
829
|
if (!parts) return { room_id: input.room_id, root, ...media, file, directory };
|
|
758
830
|
if (media.size > REMOTE_MEDIA_MAX_BYTES) {
|
|
@@ -760,12 +832,59 @@ export async function room_media(home, raw, { trust = false, parts = false } = {
|
|
|
760
832
|
? `文件 ${Math.ceil(media.size / 1024 / 1024)} MB,超过其他设备可下载的 ${REMOTE_MEDIA_MAX_BYTES / 1024 / 1024} MB 上限;请在这台电脑上取用,或让 AI 处理`
|
|
761
833
|
: `文件 ${Math.ceil(media.size / 1024 / 1024)} MB,超过其他设备可播放的 ${REMOTE_MEDIA_MAX_BYTES / 1024 / 1024} MB 上限;请在这台电脑上打开`);
|
|
762
834
|
}
|
|
835
|
+
if (process.platform === 'win32' && input.preview === true && !input.download && /^image\/(png|jpeg|webp)$/.test(media.content_type)) {
|
|
836
|
+
const preview_version = createHash('sha256').update(JSON.stringify([file, media.version, '1440-v2'])).digest('hex');
|
|
837
|
+
if (!offset && input.known_preview === preview_version) return { ...media, preview_version, unchanged: true };
|
|
838
|
+
const bytes = await project_preview_bytes(home, preview_version, python => {
|
|
839
|
+
const ready = project_media(directory, input.path);
|
|
840
|
+
if (ready.file !== file || ready.version !== media.version) return null;
|
|
841
|
+
return encode_project_preview(python, file);
|
|
842
|
+
});
|
|
843
|
+
const current = project_media(directory, input.path);
|
|
844
|
+
if (current.file !== file || current.version !== media.version) throw new Error('文件在读取时发生了变化,请重试');
|
|
845
|
+
if (bytes && bytes.length < media.size) {
|
|
846
|
+
const content_type = bytes[0] === 0xff ? 'image/jpeg' : 'image/png';
|
|
847
|
+
return { room_id: input.room_id, root, ...media, preview_version, content_type, total: bytes.length,
|
|
848
|
+
offset, data: bytes.subarray(offset, offset + PAGE_PART_BYTES).toString('base64') };
|
|
849
|
+
}
|
|
850
|
+
}
|
|
763
851
|
const part = Buffer.alloc(Math.max(0, Math.min(PAGE_PART_BYTES, media.size - offset)));
|
|
764
852
|
const handle = openSync(file, 'r');
|
|
765
853
|
try { readSync(handle, part, 0, part.length, offset); } finally { closeSync(handle); }
|
|
766
854
|
return { room_id: input.room_id, root, ...media, total: media.size, offset, data: part.toString('base64') };
|
|
767
855
|
}
|
|
768
856
|
|
|
857
|
+
/**
|
|
858
|
+
* `{ root, path }` of an absolute path (`paths`: node's win32 or posix) inside one of the room's directories; elsewhere
|
|
859
|
+
* refused, or null when not `required`.
|
|
860
|
+
*/
|
|
861
|
+
function absolute_room_path(config, path, paths, required = true) {
|
|
862
|
+
const target = paths.resolve(path);
|
|
863
|
+
for (const [root, directory] of room_directories(config).entries()) {
|
|
864
|
+
const inside = paths.relative(paths.resolve(directory), target);
|
|
865
|
+
if (inside && !inside.startsWith('..') && !paths.isAbsolute(inside)) return { root, path: inside.replaceAll('\\', '/') };
|
|
866
|
+
}
|
|
867
|
+
if (!required) return null;
|
|
868
|
+
throw new Error('图片不在房间的项目目录内,无法读取');
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
/**
|
|
872
|
+
* The small copy of one project image the file page's icon view shows, made on this computer for both its own page and
|
|
873
|
+
* another device: `{ data, content_type }` (base64, whole), or `{ data: null }` where none can be made (not a PNG, JPEG
|
|
874
|
+
* or WebP, not Windows, an image too large to decode), and the page keeps the file's icon.
|
|
875
|
+
*/
|
|
876
|
+
async function project_thumbnail(home, directory, path, file, media) {
|
|
877
|
+
if (process.platform !== 'win32' || !/^image\/(png|jpeg|webp)$/.test(media.content_type)) return { data: null };
|
|
878
|
+
const key = createHash('sha256').update(JSON.stringify([file, media.version, `${PROJECT_THUMBNAIL_SIDE}-v1`])).digest('hex');
|
|
879
|
+
const bytes = await project_thumbnail_bytes(home, key, python => {
|
|
880
|
+
const ready = project_media(directory, path);
|
|
881
|
+
if (ready.file !== file || ready.version !== media.version) return null;
|
|
882
|
+
return encode_project_preview(python, file, PROJECT_THUMBNAIL_SIDE);
|
|
883
|
+
});
|
|
884
|
+
if (!bytes || bytes.length > PAGE_PART_BYTES) return { data: null };
|
|
885
|
+
return { content_type: bytes[0] === 0xff ? 'image/jpeg' : 'image/png', data: bytes.toString('base64') };
|
|
886
|
+
}
|
|
887
|
+
|
|
769
888
|
/** `room-media` asked for by another device, answered inside the relay's own process in parts. */
|
|
770
889
|
export async function remote_room_media(home, input) {
|
|
771
890
|
assert_shared_home(home);
|
package/runner/relay_channel.mjs
CHANGED
|
@@ -10,6 +10,7 @@ import { join } from 'node:path';
|
|
|
10
10
|
import timers from 'node:timers/promises';
|
|
11
11
|
import { gzipSync } from 'node:zlib';
|
|
12
12
|
|
|
13
|
+
import { accept_timing, remember_timing } from './relay_timing.mjs';
|
|
13
14
|
import { atomic_json } from './files.mjs';
|
|
14
15
|
import { network_failure, reconnect_reader } from './relay_health.mjs';
|
|
15
16
|
import { t } from './i18n.mjs';
|
|
@@ -101,6 +102,8 @@ export async function seal_compressed(key, value, label) {
|
|
|
101
102
|
function relay_read_route(payload) {
|
|
102
103
|
if ((payload?.method ?? 'GET') !== 'GET' || typeof payload?.path !== 'string') return '';
|
|
103
104
|
const path = payload.path.split('?', 1)[0];
|
|
105
|
+
if (/\/attachments\/[^/]+\/(content|thumbnail)$/.test(path)) return path.endsWith('/thumbnail') ? 'thumbnail' : 'attachment';
|
|
106
|
+
if (path.endsWith('/room-media')) return 'room-media';
|
|
104
107
|
if (path === '/api/rooms') return 'directory';
|
|
105
108
|
if (/^\/api\/rooms\/[A-Za-z0-9_-]+$/.test(path)) return 'room';
|
|
106
109
|
if (/^\/api\/rooms\/[A-Za-z0-9_-]+\/messages$/.test(path)) return 'messages';
|
|
@@ -279,19 +282,51 @@ async function run_command(home, command, run) {
|
|
|
279
282
|
|
|
280
283
|
/** Answer one relayed request: room routes and uploads go to the local website, everything else to the local entrypoint as before. */
|
|
281
284
|
export async function answer_request(home, site, link, frame, { run = run_launch_command, fetcher, report, timing } = {}) {
|
|
285
|
+
const started = timing?.received_at ?? performance.now();
|
|
282
286
|
const { id, envelope } = frame;
|
|
283
287
|
const key = await relay_cipher(link.private_key, envelope.key);
|
|
284
288
|
const sealed = await unseal(key, envelope, id);
|
|
285
|
-
let response, request = {};
|
|
289
|
+
let response, request = {}, device = null;
|
|
290
|
+
async function finish_response(value) {
|
|
291
|
+
const label = `${id}:response`;
|
|
292
|
+
let envelope = await seal_compressed(key, value, label);
|
|
293
|
+
let answer = { type: 'response', id, envelope };
|
|
294
|
+
let frame_bytes = Buffer.byteLength(JSON.stringify(answer));
|
|
295
|
+
if (frame_bytes > FRAME_MAX_BYTES) {
|
|
296
|
+
value = { status: 413, body: { error: '回应超过中转单帧上限,未能送出' } };
|
|
297
|
+
report?.({ action: request.action, route: '', status: 413 });
|
|
298
|
+
envelope = await seal_compressed(key, value, label);
|
|
299
|
+
answer = { type: 'response', id, envelope, oversized: true };
|
|
300
|
+
frame_bytes = Buffer.byteLength(JSON.stringify({ type: 'response', id, envelope }));
|
|
301
|
+
}
|
|
302
|
+
const elapsed = Math.round(performance.now() - started);
|
|
303
|
+
const action = request.action;
|
|
304
|
+
const category = action === 'room-api' ? relay_read_route(request.payload) || 'room-api'
|
|
305
|
+
: ROOM_ACTIONS.has(action) || DEVICE_ACTIONS.has(action) || ['computer-site', 'room-upload', 'room-media'].includes(action) ? action : 'other';
|
|
306
|
+
if (request.timing_version === 1 && action !== 'timing-report') {
|
|
307
|
+
// Seal the small measurement separately, after the business response has been compressed and encrypted.
|
|
308
|
+
try {
|
|
309
|
+
const diagnostic = await seal_compressed(key, { computer_ms: elapsed, category }, `${id}:timing`);
|
|
310
|
+
const extra_bytes = Buffer.byteLength(JSON.stringify(diagnostic)) + ',"timing":'.length;
|
|
311
|
+
if (frame_bytes + extra_bytes <= FRAME_MAX_BYTES) {
|
|
312
|
+
envelope.timing = diagnostic;
|
|
313
|
+
frame_bytes += extra_bytes;
|
|
314
|
+
}
|
|
315
|
+
} catch { /* A failed timing attachment must not hide a completed operation. */ }
|
|
316
|
+
}
|
|
317
|
+
if (action !== 'timing-report') {
|
|
318
|
+
const measurement = timing ?? {};
|
|
319
|
+
measurement.frame_bytes = frame_bytes;
|
|
320
|
+
remember_timing(home, site, device, id, category, elapsed, value.status, measurement);
|
|
321
|
+
}
|
|
322
|
+
return answer;
|
|
323
|
+
}
|
|
286
324
|
// An external member's request (or an invite being redeemed) goes to the external gateway alone: it never reaches the
|
|
287
325
|
// device actions, the local entrypoint or the bridge, and never gains this computer's owner credential.
|
|
288
326
|
if (is_external_request(sealed)) {
|
|
289
327
|
({ request, response } = await answer_external(home, { machine_id: link.id, link, fetcher, on_change: () => sync_remote_launches(home) }, id, sealed));
|
|
290
328
|
report?.({ action: request.action, route: '', status: response.status });
|
|
291
|
-
|
|
292
|
-
if (JSON.stringify(answer).length <= FRAME_MAX_BYTES) return answer;
|
|
293
|
-
return { type: 'response', id, oversized: true,
|
|
294
|
-
envelope: await seal_compressed(key, { status: 413, body: { error: '回应超过中转单帧上限,未能送出' } }, `${id}:response`) };
|
|
329
|
+
return finish_response(response);
|
|
295
330
|
}
|
|
296
331
|
try {
|
|
297
332
|
// Only a paired device's signed request runs; an unpaired browser may only prove a pairing code.
|
|
@@ -300,8 +335,9 @@ export async function answer_request(home, site, link, frame, { run = run_launch
|
|
|
300
335
|
const { action, payload, target } = request;
|
|
301
336
|
if (timing && action === 'room-api' && RELAY_READ_ID.test(id)) timing.route = relay_read_route(payload);
|
|
302
337
|
claim_relayed_command(home, id, request.sent_at);
|
|
303
|
-
|
|
304
|
-
|
|
338
|
+
device = opened.device_id;
|
|
339
|
+
accept_timing(home, site, device, request.timing_reports);
|
|
340
|
+
response = action === 'timing-report' && device ? { status: 200, body: {} } : DEVICE_ACTIONS.has(action) ? await device_command(home, { site, machine_id: link.id, device_id: device, on_change: () => sync_remote_launches(home) }, action, payload)
|
|
305
341
|
: action === 'computer-site' ? { status: 200, body: { site: local_origin(home) } }
|
|
306
342
|
: action === 'room-api' ? await room_api(home, site, payload, { fetcher, device, timing })
|
|
307
343
|
: action === 'room-upload' ? await room_upload(home, site, payload, { fetcher })
|
|
@@ -309,17 +345,13 @@ export async function answer_request(home, site, link, frame, { run = run_launch
|
|
|
309
345
|
if (timing?.local_request_at !== undefined) timing.local_response_at = performance.now();
|
|
310
346
|
} catch (error) { response = { status: 400, body: { error: error.message, ...(error.need ? { need: error.need } : {}), ...(error.error_text ? { error_text: error.error_text } : {}) } }; }
|
|
311
347
|
// Remote writes go to this computer's audit log: kind, route, device and outcome, never content. Reads are not logged.
|
|
312
|
-
if (request.action && !(request.action === 'room-api' && (request.payload?.method || 'GET') === 'GET') && !DEVICE_ACTIONS.has(request.action) && request.action !== 'computer-site') {
|
|
348
|
+
if (request.action && request.action !== 'timing-report' && !(request.action === 'room-api' && (request.payload?.method || 'GET') === 'GET') && !DEVICE_ACTIONS.has(request.action) && request.action !== 'computer-site') {
|
|
313
349
|
audit(home, { event: 'command', action: request.action, route: typeof request.payload?.path === 'string' ? request.payload.path.split('?')[0] : '',
|
|
314
350
|
device: sealed.device_id || null, status: response.status });
|
|
315
351
|
}
|
|
316
352
|
// Only what kind of request it was and how it ended: never its content or query.
|
|
317
353
|
report?.({ action: request.action, route: typeof request.payload?.path === 'string' ? request.payload.path.split('?')[0] : '', status: response.status });
|
|
318
|
-
|
|
319
|
-
if (JSON.stringify(answer).length <= FRAME_MAX_BYTES) return answer;
|
|
320
|
-
report?.({ action: request.action, route: typeof request.payload?.path === 'string' ? request.payload.path.split('?')[0] : '', status: 413 });
|
|
321
|
-
return { type: 'response', id, oversized: true,
|
|
322
|
-
envelope: await seal_compressed(key, { status: 413, body: { error: '回应超过中转单帧上限,未能送出' } }, `${id}:response`) };
|
|
354
|
+
return finish_response(response);
|
|
323
355
|
}
|
|
324
356
|
|
|
325
357
|
/** Pass the local website's change notices to the devices while the relay is connected. */
|
|
@@ -516,10 +548,10 @@ async function hold_channel(home, site, { connected, log, signal, health, watch
|
|
|
516
548
|
const { oversized, ...frame_out } = answer;
|
|
517
549
|
if (open) {
|
|
518
550
|
const outgoing = JSON.stringify(frame_out);
|
|
551
|
+
timing.queued_before_send = socket.bufferedAmount;
|
|
519
552
|
socket.send(outgoing);
|
|
520
553
|
if (timing.route) {
|
|
521
554
|
timing.sent_at = performance.now();
|
|
522
|
-
timing.frame_bytes = Buffer.byteLength(outgoing);
|
|
523
555
|
timing.buffered_bytes = socket.bufferedAmount || 0;
|
|
524
556
|
}
|
|
525
557
|
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/** Best-effort, bounded diagnostic output. The writer accepts only fixed numeric fields and categories. */
|
|
2
|
+
import { appendFile, stat, truncate } from 'node:fs/promises';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
|
|
5
|
+
const pending = new Map();
|
|
6
|
+
const LIMIT = 4 * 1024 * 1024;
|
|
7
|
+
const MAX_PENDING = 256;
|
|
8
|
+
const MAX_MS = 600000;
|
|
9
|
+
let writes = Promise.resolve();
|
|
10
|
+
let queued = 0;
|
|
11
|
+
const millis = value => Number.isInteger(value) && value >= 0 && value <= MAX_MS ? value : null;
|
|
12
|
+
const colo = value => typeof value === 'string' && /^[A-Z]{3}$/.test(value) ? value : null;
|
|
13
|
+
|
|
14
|
+
function finish(key, report = {}) {
|
|
15
|
+
const entry = pending.get(key);
|
|
16
|
+
if (!entry) return;
|
|
17
|
+
clearTimeout(entry.timer);
|
|
18
|
+
pending.delete(key);
|
|
19
|
+
const { home, row, measurement } = entry;
|
|
20
|
+
row.frame_bytes = measurement.frame_bytes;
|
|
21
|
+
row.buffered_bytes = measurement.queued_before_send ?? null;
|
|
22
|
+
const total = millis(report.total), worker = millis(report.worker), relay = millis(report.relay);
|
|
23
|
+
const diff = (a, b) => a !== null && b !== null ? millis(a - b) : null;
|
|
24
|
+
Object.assign(row, { mobile_ms: diff(total, worker), site_ms: diff(worker, relay),
|
|
25
|
+
link_ms: diff(relay, row.local_ms), device_colo: colo(report.dc), machine_colo: colo(report.mc) });
|
|
26
|
+
if (queued >= MAX_PENDING) return;
|
|
27
|
+
queued++;
|
|
28
|
+
writes = writes.then(async () => {
|
|
29
|
+
const file = join(home, 'relay-timing.jsonl');
|
|
30
|
+
const line = JSON.stringify(row) + '\n';
|
|
31
|
+
const size = await stat(file).then(s => s.size, e => { if (e.code === 'ENOENT') return 0; throw e; });
|
|
32
|
+
if (size + Buffer.byteLength(line) > LIMIT) await truncate(file, 0);
|
|
33
|
+
await appendFile(file, line, { mode: 0o600 });
|
|
34
|
+
}).catch(() => {}).finally(() => { queued--; });
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Match feedback only to requests authenticated for this device and site. */
|
|
38
|
+
export function accept_timing(home, site, device, reports) {
|
|
39
|
+
if (!device || !Array.isArray(reports)) return;
|
|
40
|
+
for (const report of reports.slice(0, 16)) {
|
|
41
|
+
if (report && typeof report.id === 'string') finish(JSON.stringify([home, site, device, report.id]), report);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Flush locally observed requests even if a browser closes before reporting. */
|
|
46
|
+
export function remember_timing(home, site, device, id, category, elapsed, status, measurement) {
|
|
47
|
+
const key = JSON.stringify([home, site, device, id]);
|
|
48
|
+
if (pending.has(key)) finish(key);
|
|
49
|
+
if (pending.size >= MAX_PENDING) finish(pending.keys().next().value);
|
|
50
|
+
const timer = setTimeout(() => finish(key), 30000);
|
|
51
|
+
timer.unref();
|
|
52
|
+
const request_id = typeof id === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(id) ? id : null;
|
|
53
|
+
pending.set(key, { timer, home, measurement, row: { at: Date.now(), request_id, category, local_ms: millis(elapsed), status } });
|
|
54
|
+
}
|