dsh-scnet 0.6.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,11 +4,19 @@
4
4
 
5
5
  DSH-SCNet (`dsh-scnet` on npm) is a community-maintained DSH bundle for operating Supercomputing Network (SCNet). It packages the source [`scnet-hpc`](https://github.com/lql341/scnet-hpc) Skill, profile-aware utilities, and bounded tools for SSH, Slurm, OpenAPI files, regional resources, and Notebook discovery.
6
6
 
7
- Current release: **0.6.0**
7
+ Current release: **0.6.1**
8
8
 
9
9
  > This is an independent community project. It is compatible with DeepSeek Harness but is not an official DeepSeek product and does not imply endorsement, partnership, or authorization by DeepSeek.
10
10
 
11
- ## What's new in 0.6.0
11
+ ## What's new in 0.6.1
12
+
13
+ - Job details now fall back to the history endpoint when realtime records expire, with complete
14
+ normalized terminal states.
15
+ - Added compact `scnet_job_list`, `scnet_limits`, and `scnet_file_transfer` tools.
16
+ - File uploads now make the remote-directory contract explicit: the local filename is preserved
17
+ and must not be passed as the remote directory.
18
+
19
+ ## 0.6.0 highlights
12
20
 
13
21
  - Added first-class DSH tools for submitting jobs, inspecting job status, reading logs, and
14
22
  cancelling jobs through the existing SSH/OpenAPI backends.
@@ -53,11 +61,14 @@ See [Installation](./docs/installation.md) for npm, GitHub, and local-checkout w
53
61
  | `scnet_status` | Read the saved backend, SSH profile, and OpenAPI configuration |
54
62
  | `scnet_openapi_regions` | List authorized OpenAPI regions without exposing tokens |
55
63
  | `scnet_job_queues` | Query regional Slurm queues and live resource availability |
64
+ | `scnet_job_list` | List active or historical jobs with compact normalized records |
65
+ | `scnet_limits` | Read user and scheduler resource limits |
56
66
  | `scnet_submit_job` | Submit a job through OpenAPI or SSH; `dry_run=true` only previews the request |
57
67
  | `scnet_job_show` | Read one job's state, resources, and log paths |
58
68
  | `scnet_job_logs` | Read job logs by explicit path, or by `job_id` + `work_dir` |
59
69
  | `scnet_job_cancel` | Cancel a job; `dry_run=true` only previews the request |
60
70
  | `scnet_file_list` | List shared-storage files through the common file API |
71
+ | `scnet_file_transfer` | Upload or download one file without overwriting by default |
61
72
  | `scnet_notebook_regions` | List Notebook-capable regions |
62
73
  | `scnet_notebook_resources` | Query Notebook CPU/GPU/DCU resources |
63
74
  | `scnet_notebook_list` | List Notebook instances with sensitive fields redacted |
@@ -102,12 +113,18 @@ synchronizes the skill and version into `dsh-scnet` and `codex-scnet-hpc`. Publi
102
113
  `dsh-scnet` npm package only after that downstream change is reviewed.
103
114
 
104
115
  For a synchronized release, run the package validation on `main`, then trigger the repository's
105
- `Publish DSH-SCNet` workflow with the exact value from `package.json` (currently `0.6.0`). The
116
+ `Publish DSH-SCNet` workflow with the exact value from `package.json` (currently `0.6.1`). The
106
117
  workflow verifies the package/Skill version match, runs validation, creates the tarball, publishes
107
118
  stable releases with the `latest` tag, and creates the matching Git tag. Do not bump only
108
119
  `package.json`: `skills/scnet-hpc/VERSION`, the package version, and both README release markers
109
120
  must stay aligned.
110
121
 
122
+ The workflow uses npm Trusted Publishing through GitHub OIDC, so account 2FA/Passkey should remain
123
+ enabled and no long-lived `NPM_TOKEN` is required. Configure `lql341/dsh-scnet` and
124
+ `.github/workflows/publish.yml` as a trusted publisher in the npm package settings before the
125
+ first OIDC release. A granular read/write token with 2FA bypass is a fallback only when Trusted
126
+ Publishing cannot be enabled.
127
+
111
128
  ## Validation
112
129
 
113
130
  ```sh
package/README_CN.md CHANGED
@@ -4,10 +4,16 @@
4
4
 
5
5
  <p align="center">在 DeepSeek Harness 里操作超算互联网(SCNet):配置 SSH、管理 Slurm 作业、查询 OpenAPI 区域和文件、检查 Notebook 资源与实例,并保留海光 DCU/DTK 诊断能力。</p>
6
6
 
7
- 当前版本:**0.6.0**
7
+ 当前版本:**0.6.1**
8
8
 
9
9
  > 本项目是独立维护的社区项目,与 DeepSeek Harness 兼容,但不是 DeepSeek 官方产品,也不表示 DeepSeek 对本项目提供背书、合作或授权。
10
10
 
11
+ ## 0.6.1 更新
12
+
13
+ - 作业实时记录过期时自动回退历史接口,并补全终态映射。
14
+ - 新增紧凑的 `scnet_job_list`、`scnet_limits`、`scnet_file_transfer` 工具。
15
+ - 明确 OpenAPI 上传参数是远端目录,文件名沿用本地文件名,不能把文件名当作远端目录传入。
16
+
11
17
  ## 0.6.0 更新
12
18
 
13
19
  - 新增作业提交、状态查询、日志读取和取消作业的 DSH 工具,复用现有 SSH/OpenAPI backend。
@@ -60,11 +66,14 @@ git 源、本地目录安装以及验证步骤见[安装说明](./docs/installat
60
66
  | scnet_status | 只读查看 backend、SSH profile 和 OpenAPI 配置 |
61
67
  | scnet_openapi_regions | 列出授权 OpenAPI 区域,不暴露 token |
62
68
  | scnet_job_queues | 查询区域 Slurm 队列和实时空闲资源 |
69
+ | scnet_job_list | 紧凑列出当前或历史作业 |
70
+ | scnet_limits | 查询用户和调度器资源限制 |
63
71
  | scnet_submit_job | 通过 OpenAPI 或 SSH 提交作业;dry_run=true 只预览请求 |
64
72
  | scnet_job_show | 查询单个作业的状态、资源与日志路径 |
65
73
  | scnet_job_logs | 按显式 path,或按 job_id + work_dir 读取作业日志 |
66
74
  | scnet_job_cancel | 取消作业;dry_run=true 只预览请求 |
67
75
  | scnet_file_list | 通过通用文件 API 列出共享存储 |
76
+ | scnet_file_transfer | 上传或下载单个文件,默认不覆盖 |
68
77
  | scnet_notebook_regions | 列出支持 Notebook 的区域 |
69
78
  | scnet_notebook_resources | 查询 Notebook CPU/GPU/DCU 资源 |
70
79
  | scnet_notebook_list | 列出 Notebook 实例并脱敏敏感字段 |
@@ -117,11 +126,16 @@ git 源、本地目录安装以及验证步骤见[安装说明](./docs/installat
117
126
  才能发布对应版本的 `dsh-scnet` npm 包。
118
127
 
119
128
  下游同步合并到 `main` 后,先运行本地校验,再手动触发仓库的 `Publish DSH-SCNet` workflow,
120
- 输入 `package.json` 中的精确版本(当前为 `0.6.0`)。workflow 会校验 package 与 Skill
129
+ 输入 `package.json` 中的精确版本(当前为 `0.6.1`)。workflow 会校验 package 与 Skill
121
130
  版本一致,执行验证、生成 tarball、以稳定版 `latest` 标签发布,并创建对应 Git tag。
122
131
  不要只修改 `package.json`;`skills/scnet-hpc/VERSION`、package 版本和两份 README 的版本
123
132
  标记必须保持一致。
124
133
 
134
+ 该 workflow 使用 GitHub OIDC 的 npm Trusted Publishing,因此应保留账号的 2FA/Passkey,
135
+ 不需要长期保存 `NPM_TOKEN`。首次使用 OIDC 发布前,请在 npm package 设置中把
136
+ `lql341/dsh-scnet` 与 `.github/workflows/publish.yml` 配置为 trusted publisher。只有无法
137
+ 启用 Trusted Publishing 时,才考虑使用具备 2FA bypass 的 granular read/write token。
138
+
125
139
  ## 隐私与安全
126
140
 
127
141
  - 仓库不含私钥、token、用户名、密钥指纹。
package/docs/testing.md CHANGED
@@ -40,11 +40,14 @@ Confirm that the composed configuration includes:
40
40
  | `scnet_status` | Returns redacted local SCNet configuration |
41
41
  | `scnet_openapi_regions` | Returns authorized regions without tokens |
42
42
  | `scnet_job_queues` | Returns live regional Slurm queues |
43
+ | `scnet_job_list` | Lists active or historical jobs |
44
+ | `scnet_limits` | Returns user and scheduler resource limits |
43
45
  | `scnet_submit_job` | Submits a job through OpenAPI or SSH; `dry_run=true` returns the pending request only |
44
46
  | `scnet_job_show` | Returns one job's state, resources, and log paths |
45
47
  | `scnet_job_logs` | Reads job logs by explicit path, or by `job_id` + `work_dir` |
46
48
  | `scnet_job_cancel` | Cancels one job; `dry_run=true` returns the pending request only |
47
49
  | `scnet_file_list` | Lists shared-storage files without modification |
50
+ | `scnet_file_transfer` | Uploads or downloads one file; defaults to no overwrite |
48
51
  | `scnet_notebook_regions` | Lists Notebook-capable regions |
49
52
  | `scnet_notebook_resources` | Returns Notebook resource groups |
50
53
  | `scnet_notebook_list` | Lists redacted Notebook instances |
@@ -61,12 +61,15 @@ DEEPSEEK_API_KEY: sk-你的key
61
61
  | 8 | 用 scnet_status 查看当前配置 | 返回脱敏配置 | 只读 |
62
62
  | 9 | 用 scnet_openapi_regions 查看授权区域 | 返回区域且不含 token | 只读 |
63
63
  | 10 | 用 scnet_job_queues 查看昆山队列 | 返回实时队列和空闲资源 | 只读 |
64
+ | 10a | 用 scnet_job_list 列出当前或历史作业 | 返回紧凑作业记录 | 只读 |
65
+ | 10b | 用 scnet_limits 查询资源限制 | 返回用户和调度器限制 | 只读 |
64
66
  | 10a | 用 scnet_submit_job(dry_run=true)预览一次提交 | 返回将要发送的请求,不真正提交 | 只读(dry_run) |
65
67
  | 10b | 用 scnet_submit_job 提交一个 5 秒小作业 | 返回 job_id、作业目录与日志路径 | 高(会消耗配额) |
66
68
  | 10c | 用 scnet_job_show 查该 job_id | 返回状态与 stdout/stderr 路径 | 只读 |
67
69
  | 10d | 用 scnet_job_logs 读该作业日志 | 返回日志内容(同时验证 path 与 job_id+work_dir 两种模式结果一致) | 只读 |
68
70
  | 10e | 用 scnet_job_cancel 取消一个作业 | 建议先用 dry_run=true 预览 | 高(变更) |
69
71
  | 11 | 用 scnet_file_list 查看默认目录 | 返回共享存储文件 | 只读 |
72
+ | 11a | 用 scnet_file_transfer 传输一个文件 | 默认不覆盖目标 | 有副作用 |
70
73
  | 12 | 用 scnet_notebook_regions 查看区域 | 返回 Notebook 可用区域 | 只读 |
71
74
  | 13 | 用 scnet_notebook_resources 查看昆山资源 | 返回 CPU/GPU/DCU 资源 | 只读 |
72
75
  | 14 | 用 scnet_notebook_list 查看实例 | 返回脱敏实例列表 | 只读 |
package/index.mjs CHANGED
@@ -365,6 +365,68 @@ export function apply(ctx) {
365
365
  }),
366
366
  )
367
367
 
368
+ ctx.tools.register(
369
+ defineTool({
370
+ name: 'scnet_job_list',
371
+ description:
372
+ '只读列出 SCNet 作业。默认列出当前区域正在排队或运行的作业;scope=history 时查询最近历史作业。区域、数量和历史天数都可省略,输出保持紧凑。',
373
+ parameters: {
374
+ scope: { type: 'string', description: 'active(默认)或 history' },
375
+ region: { type: 'string', description: '区域名称或 ID;省略时使用已保存的默认区域' },
376
+ limit: { type: 'number', description: '最多返回条数,默认 20,最大 100' },
377
+ days: { type: 'number', description: 'history 模式查询最近天数,默认 30,最大 90' },
378
+ },
379
+ output: {
380
+ schema: { type: 'string' },
381
+ render: (_args, value) => textBlock(value),
382
+ },
383
+ async execute(args) {
384
+ const scope = String(args.scope ?? 'active').trim().toLowerCase()
385
+ if (scope !== 'active' && scope !== 'history') {
386
+ return 'scope 只支持 active 或 history。'
387
+ }
388
+ const argv = ['--backend', 'openapi', ...regionArgs(args.region), 'jobs', '--scope', scope]
389
+ if (args.limit !== undefined) {
390
+ const checked = positiveInt(args.limit, 'limit')
391
+ if (checked?.error) return checked.error
392
+ argv.push('--limit', checked.value)
393
+ }
394
+ if (args.days !== undefined) {
395
+ const checked = positiveInt(args.days, 'days')
396
+ if (checked?.error) return checked.error
397
+ argv.push('--days', checked.value)
398
+ }
399
+ return scnetResult(await runScnet(argv), '查询作业列表')
400
+ },
401
+ }),
402
+ )
403
+
404
+ ctx.tools.register(
405
+ defineTool({
406
+ name: 'scnet_limits',
407
+ description:
408
+ '只读查询当前区域和调度器的用户资源限制。region、scheduler_id 都可省略,后端会自动解析唯一目标。',
409
+ parameters: {
410
+ region: { type: 'string', description: '区域名称或 ID;省略时使用默认区域' },
411
+ scheduler_id: { type: 'string', description: '调度器 ID;只有多个调度器且无法自动选择时填写' },
412
+ },
413
+ output: {
414
+ schema: { type: 'string' },
415
+ render: (_args, value) => textBlock(value),
416
+ },
417
+ async execute(args) {
418
+ const argv = [
419
+ '--backend',
420
+ 'openapi',
421
+ ...regionArgs(args.region),
422
+ ...(args.scheduler_id ? ['--scheduler-id', String(args.scheduler_id)] : []),
423
+ 'limits',
424
+ ]
425
+ return scnetResult(await runScnet(argv), '查询资源限制')
426
+ },
427
+ }),
428
+ )
429
+
368
430
  ctx.tools.register(
369
431
  defineTool({
370
432
  name: 'scnet_submit_job',
@@ -634,6 +696,55 @@ export function apply(ctx) {
634
696
  }),
635
697
  )
636
698
 
699
+ ctx.tools.register(
700
+ defineTool({
701
+ name: 'scnet_file_transfer',
702
+ description:
703
+ '在本地与 SCNet 区域共享存储之间传输一个文件。direction=upload 或 download;upload 的 remote_dir 是目录而不是文件名。默认不覆盖,执行前应确认区域和路径,dry_run=true 只预览。',
704
+ parameters: {
705
+ direction: { type: 'string', required: true, description: 'upload 或 download' },
706
+ local_path: { type: 'string', required: true, description: '本地文件路径' },
707
+ remote_dir: { type: 'string', description: 'upload 时必填:区域共享存储中的绝对目录;文件名由 local_path 保留' },
708
+ remote_path: { type: 'string', description: 'download:区域共享存储中的绝对文件路径' },
709
+ backend: { type: 'string', description: 'openapi(默认)或 ssh' },
710
+ region: { type: 'string', description: 'OpenAPI 区域;省略时使用默认区域' },
711
+ cluster: { type: 'string', description: 'SSH 集群短名;多个 profile 时必须指定' },
712
+ overwrite: { type: 'boolean', description: '是否覆盖已有目标,默认否' },
713
+ dry_run: { type: 'boolean', description: '只预览,不传输(默认否)' },
714
+ },
715
+ output: {
716
+ schema: { type: 'string' },
717
+ render: (_args, value) => textBlock(value),
718
+ },
719
+ async execute(args) {
720
+ const direction = String(args.direction ?? '').trim().toLowerCase()
721
+ if (direction !== 'upload' && direction !== 'download') {
722
+ return 'direction 只支持 upload 或 download。'
723
+ }
724
+ const localPath = String(args.local_path ?? '').trim()
725
+ const remoteDir = String(args.remote_dir ?? '').trim()
726
+ const remotePath = String(args.remote_path ?? '').trim()
727
+ if (!localPath) return '缺少必填参数 local_path。'
728
+ if (direction === 'upload' && !remoteDir) return '缺少必填参数 remote_dir(目录,不是文件名)。'
729
+ if (direction === 'download' && !remotePath) return '缺少必填参数 remote_path。'
730
+ const target = await resolveTarget(args)
731
+ if (target.error) return target.error
732
+ const argv = [...target.argv]
733
+ if (args.dry_run === true) argv.push('--dry-run')
734
+ if (direction === 'upload') {
735
+ argv.push('upload', localPath, remoteDir)
736
+ } else {
737
+ argv.push('download', remotePath, localPath)
738
+ }
739
+ if (args.overwrite === true) argv.push('--cover')
740
+ return scnetResult(
741
+ await runScnet(argv, 180000),
742
+ direction === 'upload' ? '上传文件' : '下载文件',
743
+ )
744
+ },
745
+ }),
746
+ )
747
+
637
748
  ctx.tools.register(
638
749
  defineTool({
639
750
  name: 'scnet_file_list',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-scnet",
3
- "version": "0.6.0",
3
+ "version": "0.6.1",
4
4
  "description": "Community DeepSeek Harness bundle for SCNet SSH and OpenAPI jobs, files, Notebook resources, Slurm diagnostics, and Hygon DCU/DTK guidance.",
5
5
  "type": "module",
6
6
  "main": "./index.mjs",
@@ -1 +1 @@
1
- 0.6.0
1
+ 0.6.1
@@ -110,6 +110,21 @@ python3 scripts/scnet.py --backend openapi --region <id> \
110
110
  Downloads refuse to replace an existing local path unless `--cover` is supplied. Uploads send
111
111
  `uncover` by default and require `--cover` for replacement.
112
112
 
113
+ For uploads, the second argument is always a remote **directory**, not a complete filename.
114
+ The uploaded filename comes from the local file. For example, uploading `mesh.bin` to
115
+ `/public/home/alice/mesh` creates `/public/home/alice/mesh/mesh.bin`; passing
116
+ `/public/home/alice/mesh.bin` as the second argument asks the API to use `mesh.bin` as a
117
+ directory name.
118
+
119
+ List active or historical jobs without supplying a job ID:
120
+
121
+ ```bash
122
+ python3 scripts/scnet.py --backend openapi --region <id> \
123
+ jobs --scope active --limit 20
124
+ python3 scripts/scnet.py --backend openapi --region <id> \
125
+ jobs --scope history --days 30 --limit 20
126
+ ```
127
+
113
128
  Uploads larger than 8 MiB automatically use the documented burst/merge flow. Override the
114
129
  threshold and chunk size with `--chunk-size <bytes>`; use `--chunk-size 0` to force ordinary
115
130
  multipart upload. The current implementation keeps one chunk in memory at a time.
@@ -123,6 +123,11 @@ def build_parser() -> argparse.ArgumentParser:
123
123
  job = subparsers.add_parser("job", help="show one job")
124
124
  job.add_argument("job_id")
125
125
 
126
+ jobs = subparsers.add_parser("jobs", help="list active or historical jobs")
127
+ jobs.add_argument("--scope", choices=("active", "history"), default="active")
128
+ jobs.add_argument("--limit", type=int, default=20)
129
+ jobs.add_argument("--days", type=int, default=30)
130
+
126
131
  logs = subparsers.add_parser("logs", help="read a log file")
127
132
  logs.add_argument("--path", required=True)
128
133
  logs.add_argument("--lines", type=int, default=200)
@@ -166,9 +171,9 @@ def build_parser() -> argparse.ArgumentParser:
166
171
  default="name",
167
172
  )
168
173
 
169
- upload = subparsers.add_parser("upload", help="upload one file")
174
+ upload = subparsers.add_parser("upload", help="upload one file into a remote directory")
170
175
  upload.add_argument("local_path")
171
- upload.add_argument("remote_path")
176
+ upload.add_argument("remote_dir", help="remote destination directory, not a filename")
172
177
  upload.add_argument("--cover", action="store_true")
173
178
  upload.add_argument(
174
179
  "--chunk-size",
@@ -6,6 +6,7 @@ import json
6
6
  import mimetypes
7
7
  import re
8
8
  import uuid
9
+ from datetime import datetime, timedelta, timezone
9
10
  from pathlib import Path
10
11
  from typing import Any, Mapping
11
12
  from urllib.error import HTTPError, URLError
@@ -29,6 +30,12 @@ STATUS_MAP = {
29
30
  "statC": "COMPLETED",
30
31
  "statW": "WAITING",
31
32
  "statX": "OTHER",
33
+ "statDE": "CANCELLED",
34
+ "statD": "FAILED",
35
+ "statEX": "ABNORMAL",
36
+ "statT": "TIMEOUT",
37
+ "statN": "NODE_ERROR",
38
+ "statRQ": "REQUEUED",
32
39
  }
33
40
  WALLTIME_RE = re.compile(r"^(?:[0-9]+-)?[0-9]{1,3}:[0-9]{2}:[0-9]{2}$")
34
41
 
@@ -44,7 +51,12 @@ def _bounded_int(options: Mapping[str, Any], name: str, minimum: int) -> int:
44
51
 
45
52
 
46
53
  def normalize_job(item: Mapping[str, Any]) -> dict[str, Any]:
47
- raw_state = item.get("jobStatus") or item.get("state") or ""
54
+ raw_state = (
55
+ item.get("jobStatus")
56
+ or item.get("jobState")
57
+ or item.get("state")
58
+ or ""
59
+ )
48
60
  return {
49
61
  "job_id": str(item.get("jobId") or item.get("job_id") or ""),
50
62
  "name": item.get("jobName") or item.get("name"),
@@ -76,6 +88,7 @@ class OpenAPIBackend(Backend):
76
88
  "queues",
77
89
  "limits",
78
90
  "job",
91
+ "jobs",
79
92
  "logs",
80
93
  "submit",
81
94
  "cancel",
@@ -335,18 +348,134 @@ class OpenAPIBackend(Backend):
335
348
 
336
349
  def op_job(self, options: Mapping[str, Any]) -> Any:
337
350
  job_id = str(require_option(options, "job_id"))
338
- hpc_url, token, _, _, _ = self._hpc_context(options)
351
+ hpc_url, token, scheduler_id, _, _ = self._hpc_context(options)
352
+ realtime_error: str | None = None
353
+ data: Any = None
354
+ try:
355
+ data = self._json_request(
356
+ "GET",
357
+ service_endpoint(hpc_url, "hpc", f"/openapi/v2/jobs/{quote(job_id)}"),
358
+ token=token,
359
+ )
360
+ except BackendError as exc:
361
+ if not self._is_missing_job_error(str(exc)):
362
+ raise
363
+ realtime_error = str(exc)
364
+
365
+ if isinstance(data, dict):
366
+ candidate = data
367
+ if candidate.get("jobId") or candidate.get("job_id"):
368
+ result = normalize_job(candidate)
369
+ result["source"] = "realtime"
370
+ if options.get("raw"):
371
+ result["raw"] = candidate
372
+ return result
373
+
374
+ history = self._history_job(
375
+ hpc_url,
376
+ token,
377
+ scheduler_id,
378
+ job_id,
379
+ options,
380
+ )
381
+ if not isinstance(history, dict) or not (
382
+ history.get("jobId") or history.get("job_id")
383
+ ):
384
+ detail = "realtime and history endpoints returned no job record"
385
+ if realtime_error:
386
+ detail += f" ({realtime_error})"
387
+ raise BackendError(detail)
388
+ result = normalize_job(history)
389
+ result["source"] = "history"
390
+ if options.get("raw"):
391
+ result["raw"] = history
392
+ return result
393
+
394
+ @staticmethod
395
+ def _is_missing_job_error(text: str) -> bool:
396
+ value = text.lower()
397
+ return any(
398
+ marker in value
399
+ for marker in (
400
+ "unexpected data shape",
401
+ "http 404",
402
+ "not found",
403
+ "does not exist",
404
+ "不存在",
405
+ )
406
+ )
407
+
408
+ def _history_job(
409
+ self,
410
+ hpc_url: str,
411
+ token: str,
412
+ scheduler_id: str,
413
+ job_id: str,
414
+ options: Mapping[str, Any],
415
+ ) -> Any:
416
+ if not scheduler_id:
417
+ raise BackendError("history lookup requires a scheduler id")
418
+ path = f"/openapi/v2/historyjobs/{quote(scheduler_id)}/{quote(job_id)}"
419
+ acct_time = str(options.get("acct_time") or "").strip()
420
+ if acct_time:
421
+ path += "?" + urlencode({"acctTime": acct_time})
422
+ return self._json_request(
423
+ "GET",
424
+ service_endpoint(hpc_url, "hpc", path),
425
+ token=token,
426
+ )
427
+
428
+ def op_jobs(self, options: Mapping[str, Any]) -> Any:
429
+ hpc_url, token, scheduler_id, _, _ = self._hpc_context(options)
430
+ scope = str(options.get("scope") or "active").strip().lower()
431
+ if scope not in {"active", "history"}:
432
+ raise BackendError("scope must be active or history")
433
+ limit = _bounded_int(options, "limit", 1)
434
+ if limit > 100:
435
+ raise BackendError("limit must be <= 100")
436
+ if scope == "active":
437
+ path = "/openapi/v2/jobs"
438
+ params = {
439
+ "strClusterIDList": scheduler_id,
440
+ "start": 0,
441
+ "limit": limit,
442
+ }
443
+ else:
444
+ days = _bounded_int(options, "days", 1)
445
+ if days > 90:
446
+ raise BackendError("days must be <= 90")
447
+ end = datetime.now(timezone.utc)
448
+ start = end - timedelta(days=days)
449
+ path = "/openapi/v2/historyjobs"
450
+ params = {
451
+ "strClusterNameList": scheduler_id,
452
+ "timeType": "CUSTOM",
453
+ "isQueryByQueueTime": "false",
454
+ "start": 0,
455
+ "limit": limit,
456
+ "startTime": start.strftime("%Y-%m-%d %H:%M:%S"),
457
+ "endTime": end.strftime("%Y-%m-%d %H:%M:%S"),
458
+ }
339
459
  data = self._json_request(
340
460
  "GET",
341
- service_endpoint(hpc_url, "hpc", f"/openapi/v2/jobs/{quote(job_id)}"),
461
+ service_endpoint(hpc_url, "hpc", path) + "?" + urlencode(params),
342
462
  token=token,
343
463
  )
344
- if not isinstance(data, dict):
345
- raise BackendError("job endpoint returned an unexpected data shape")
346
- result = normalize_job(data)
347
- if options.get("raw"):
348
- result["raw"] = data
349
- return result
464
+ if isinstance(data, dict):
465
+ items = data.get("items") or data.get("list") or data.get("rows") or []
466
+ total = data.get("total")
467
+ else:
468
+ items = data or []
469
+ total = None
470
+ if not isinstance(items, list):
471
+ raise BackendError("job list endpoint returned an unexpected data shape")
472
+ result = [normalize_job(item) for item in items if isinstance(item, dict)]
473
+ payload = {
474
+ "scope": scope,
475
+ "items": result,
476
+ "total": total if total is not None else len(result),
477
+ }
478
+ return {"data": payload, "raw": data} if options.get("raw") else payload
350
479
 
351
480
  def op_logs(self, options: Mapping[str, Any]) -> Any:
352
481
  path = str(require_option(options, "path"))
@@ -580,14 +709,17 @@ class OpenAPIBackend(Backend):
580
709
 
581
710
  def op_upload(self, options: Mapping[str, Any]) -> Any:
582
711
  local_path = Path(str(require_option(options, "local_path"))).expanduser()
583
- remote_path = str(require_option(options, "remote_path"))
712
+ remote_dir = str(
713
+ options.get("remote_dir")
714
+ or require_option(options, "remote_path")
715
+ )
584
716
  if not local_path.is_file():
585
717
  raise BackendError(f"local file does not exist: {local_path}")
586
718
  if (
587
- not remote_path.startswith("/")
588
- or "\n" in remote_path
589
- or "\r" in remote_path
590
- or "\x00" in remote_path
719
+ not remote_dir.startswith("/")
720
+ or "\n" in remote_dir
721
+ or "\r" in remote_dir
722
+ or "\x00" in remote_dir
591
723
  ):
592
724
  raise BackendError("remote upload directory must be absolute")
593
725
  chunk_size = int(options.get("chunk_size") or 0)
@@ -596,7 +728,7 @@ class OpenAPIBackend(Backend):
596
728
  if chunk_size and chunk_size < 1024 * 1024:
597
729
  raise BackendError("chunk size must be at least 1 MiB or 0")
598
730
  if chunk_size and local_path.stat().st_size > chunk_size:
599
- return self._op_chunked_upload(local_path, remote_path, options, chunk_size)
731
+ return self._op_chunked_upload(local_path, remote_dir, options, chunk_size)
600
732
  efile_url, token, _ = self._efile_context(options)
601
733
  content_type = mimetypes.guess_type(local_path.name)[0] or "application/octet-stream"
602
734
  self._multipart_request(
@@ -604,13 +736,17 @@ class OpenAPIBackend(Backend):
604
736
  token,
605
737
  {
606
738
  "cover": "cover" if options.get("cover") else "uncover",
607
- "path": remote_path,
739
+ "path": remote_dir,
608
740
  },
609
741
  local_path.name,
610
742
  local_path.read_bytes(),
611
743
  content_type,
612
744
  )
613
- return {"local_path": str(local_path), "remote_path": remote_path}
745
+ return {
746
+ "local_path": str(local_path),
747
+ "remote_dir": remote_dir,
748
+ "remote_filename": local_path.name,
749
+ }
614
750
 
615
751
  def _multipart_request(
616
752
  self,
@@ -220,7 +220,10 @@ class SSHBackend(Backend):
220
220
 
221
221
  def op_upload(self, options: Mapping[str, Any]) -> Any:
222
222
  local_path = Path(str(require_option(options, "local_path"))).expanduser()
223
- remote_path = str(require_option(options, "remote_path"))
223
+ remote_path = str(
224
+ options.get("remote_dir")
225
+ or require_option(options, "remote_path")
226
+ )
224
227
  if not local_path.is_file():
225
228
  raise BackendError(f"local file does not exist: {local_path}")
226
229
  if not remote_path.startswith("/") or "\n" in remote_path:
@@ -7,6 +7,7 @@ import hmac
7
7
  import json
8
8
  import os
9
9
  import time
10
+ from pathlib import Path
10
11
  from typing import Any, Mapping
11
12
  from urllib.error import HTTPError, URLError
12
13
  from urllib.parse import urlencode, urlsplit, urlunsplit
@@ -45,6 +46,8 @@ def service_endpoint(base_url: str, service: str, suffix: str) -> str:
45
46
  class SCNetClient:
46
47
  """One authenticated OpenAPI client shared by service-specific domains."""
47
48
 
49
+ TOKEN_CACHE_TTL = 4 * 60 * 60
50
+
48
51
  def __init__(self, context: BackendContext):
49
52
  self.context = context
50
53
  self._regions_cache: list[dict[str, Any]] | None = None
@@ -55,6 +58,79 @@ class SCNetClient:
55
58
  value = os.environ.get(name)
56
59
  return value if value not in (None, "") else default
57
60
 
61
+ @classmethod
62
+ def _token_cache_paths(cls) -> tuple[Path, Path]:
63
+ root = Path(cls.env("XDG_CACHE_HOME", str(Path.home() / ".cache"))) / "scnet-hpc"
64
+ return root / "openapi-regions.json", root / "openapi-regions.lock"
65
+
66
+ @staticmethod
67
+ def _credential_fingerprint(user: str, access_key: str, secret_key: str) -> str:
68
+ value = "\0".join((user, access_key, secret_key)).encode("utf-8")
69
+ return hashlib.sha256(value).hexdigest()
70
+
71
+ @classmethod
72
+ def _read_token_cache(cls, fingerprint: str) -> list[dict[str, Any]] | None:
73
+ path, _ = cls._token_cache_paths()
74
+ try:
75
+ payload = json.loads(path.read_text(encoding="utf-8"))
76
+ if (
77
+ payload.get("fingerprint") != fingerprint
78
+ or time.time() - float(payload.get("created_at", 0)) > cls.TOKEN_CACHE_TTL
79
+ or not isinstance(payload.get("regions"), list)
80
+ ):
81
+ return None
82
+ return [item for item in payload["regions"] if isinstance(item, dict)]
83
+ except (OSError, TypeError, ValueError):
84
+ return None
85
+
86
+ @classmethod
87
+ def _write_token_cache(
88
+ cls, fingerprint: str, regions: list[dict[str, Any]]
89
+ ) -> None:
90
+ path, _ = cls._token_cache_paths()
91
+ path.parent.mkdir(parents=True, mode=0o700, exist_ok=True)
92
+ temporary = path.with_name(f".{path.name}.{os.getpid()}.tmp")
93
+ temporary.write_text(
94
+ json.dumps(
95
+ {
96
+ "created_at": time.time(),
97
+ "fingerprint": fingerprint,
98
+ "regions": regions,
99
+ },
100
+ ensure_ascii=False,
101
+ ),
102
+ encoding="utf-8",
103
+ )
104
+ os.chmod(temporary, 0o600)
105
+ os.replace(temporary, path)
106
+
107
+ @classmethod
108
+ def _acquire_token_cache_lock(cls) -> Path | None:
109
+ _, lock = cls._token_cache_paths()
110
+ lock.parent.mkdir(parents=True, mode=0o700, exist_ok=True)
111
+ for _ in range(50):
112
+ try:
113
+ fd = os.open(lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
114
+ os.close(fd)
115
+ return lock
116
+ except FileExistsError:
117
+ try:
118
+ if time.time() - lock.stat().st_mtime > 30:
119
+ lock.unlink()
120
+ continue
121
+ except OSError:
122
+ pass
123
+ time.sleep(0.2)
124
+ return None
125
+
126
+ @staticmethod
127
+ def _release_token_cache_lock(lock: Path | None) -> None:
128
+ if lock is not None:
129
+ try:
130
+ lock.unlink()
131
+ except FileNotFoundError:
132
+ pass
133
+
58
134
  def request(
59
135
  self,
60
136
  method: str,
@@ -150,25 +226,41 @@ class SCNetClient:
150
226
  "OpenAPI credentials are not configured; run setup or set "
151
227
  + ", ".join(missing)
152
228
  )
153
- timestamp = str(int(time.time()))
154
- signature = canonical_signature(access_key, timestamp, user, secret_key)
155
- auth_base = self.env("SCNET_OPENAPI_AUTH_BASE", "https://api.scnet.cn")
156
- data = self.request(
157
- "POST",
158
- auth_base.rstrip("/") + "/api/user/v3/tokens",
159
- headers={
160
- "user": user,
161
- "accessKey": access_key,
162
- "signature": signature,
163
- "timestamp": timestamp,
164
- },
165
- )
166
- if not isinstance(data, list):
167
- raise BackendError("token endpoint returned an unexpected data shape")
168
- self._regions_cache = [
169
- item for item in data if isinstance(item, dict)
170
- ]
171
- return self._regions_cache
229
+ fingerprint = self._credential_fingerprint(user, access_key, secret_key)
230
+ if not refresh:
231
+ cached = self._read_token_cache(fingerprint)
232
+ if cached:
233
+ self._regions_cache = cached
234
+ return cached
235
+ lock = self._acquire_token_cache_lock()
236
+ try:
237
+ if not refresh:
238
+ cached = self._read_token_cache(fingerprint)
239
+ if cached:
240
+ self._regions_cache = cached
241
+ return cached
242
+ timestamp = str(int(time.time()))
243
+ signature = canonical_signature(access_key, timestamp, user, secret_key)
244
+ auth_base = self.env("SCNET_OPENAPI_AUTH_BASE", "https://api.scnet.cn")
245
+ data = self.request(
246
+ "POST",
247
+ auth_base.rstrip("/") + "/api/user/v3/tokens",
248
+ headers={
249
+ "user": user,
250
+ "accessKey": access_key,
251
+ "signature": signature,
252
+ "timestamp": timestamp,
253
+ },
254
+ )
255
+ if not isinstance(data, list):
256
+ raise BackendError("token endpoint returned an unexpected data shape")
257
+ self._regions_cache = [
258
+ item for item in data if isinstance(item, dict)
259
+ ]
260
+ self._write_token_cache(fingerprint, self._regions_cache)
261
+ return self._regions_cache
262
+ finally:
263
+ self._release_token_cache_lock(lock)
172
264
 
173
265
  def select_region(
174
266
  self, requested: str | None