@tama-create/sf-tools 0.0.0-stage → 1.4.0-dev.10

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.
Files changed (164) hide show
  1. package/LICENSE +24 -0
  2. package/README.md +212 -2
  3. package/bin/sft.js +22 -0
  4. package/config/changeset-types.txt +350 -0
  5. package/config/install/gitmessage +6 -0
  6. package/config/install/release/README.md +26 -0
  7. package/config/install/release/deploy-target.txt +368 -0
  8. package/config/install/release/remove-target.txt +279 -0
  9. package/config/metadata-capability.txt +118 -0
  10. package/config/metadata-dirs.txt +79 -0
  11. package/config/metasync-detect.txt +52 -0
  12. package/config/metasync-extra.txt +30 -0
  13. package/config/metasync-fingerprint.txt +90 -0
  14. package/dist/cli.js +35 -0
  15. package/dist/commands/admin.js +46 -0
  16. package/dist/commands/check.js +20 -0
  17. package/dist/commands/ci.js +123 -0
  18. package/dist/commands/deploy.js +31 -0
  19. package/dist/commands/doctor.js +11 -0
  20. package/dist/commands/dryrun.js +17 -0
  21. package/dist/commands/hook.js +46 -0
  22. package/dist/commands/index.js +37 -0
  23. package/dist/commands/job.js +31 -0
  24. package/dist/commands/launcher.js +57 -0
  25. package/dist/commands/log.js +58 -0
  26. package/dist/commands/metasync.js +21 -0
  27. package/dist/commands/pr.js +32 -0
  28. package/dist/commands/project.js +102 -0
  29. package/dist/commands/push.js +16 -0
  30. package/dist/commands/release.js +19 -0
  31. package/dist/commands/start.js +67 -0
  32. package/dist/commands/switch-org.js +12 -0
  33. package/dist/commands/update-cli.js +11 -0
  34. package/dist/commands/version.js +18 -0
  35. package/dist/core/admin-clone.js +79 -0
  36. package/dist/core/ai-answers.js +40 -0
  37. package/dist/core/branches.js +88 -0
  38. package/dist/core/check-targets.js +170 -0
  39. package/dist/core/check.js +34 -0
  40. package/dist/core/ci-check-branch.js +150 -0
  41. package/dist/core/ci-login-steps.js +73 -0
  42. package/dist/core/ci-release-steps.js +193 -0
  43. package/dist/core/ci-sequence-steps.js +188 -0
  44. package/dist/core/ci-validate-steps.js +140 -0
  45. package/dist/core/cli-update-notice.js +47 -0
  46. package/dist/core/command.js +25 -0
  47. package/dist/core/create-connect.js +519 -0
  48. package/dist/core/create-setup.js +358 -0
  49. package/dist/core/create-state.js +82 -0
  50. package/dist/core/delegate.js +45 -0
  51. package/dist/core/deploy.js +66 -0
  52. package/dist/core/diag.js +200 -0
  53. package/dist/core/doctor.js +211 -0
  54. package/dist/core/eca.js +259 -0
  55. package/dist/core/exit-codes.js +12 -0
  56. package/dist/core/gh-identity.js +46 -0
  57. package/dist/core/hook-install.js +130 -0
  58. package/dist/core/hook.js +116 -0
  59. package/dist/core/identity.js +48 -0
  60. package/dist/core/job.js +243 -0
  61. package/dist/core/launcher-status.js +215 -0
  62. package/dist/core/lines.js +25 -0
  63. package/dist/core/log-auto.js +56 -0
  64. package/dist/core/log-box.js +109 -0
  65. package/dist/core/log-collector.js +370 -0
  66. package/dist/core/log-format.js +44 -0
  67. package/dist/core/log-pull.js +565 -0
  68. package/dist/core/log-select.js +126 -0
  69. package/dist/core/log-session.js +362 -0
  70. package/dist/core/log-start.js +421 -0
  71. package/dist/core/log-status.js +223 -0
  72. package/dist/core/log-summarize.js +127 -0
  73. package/dist/core/logger.js +71 -0
  74. package/dist/core/login-url.js +50 -0
  75. package/dist/core/manifest-build.js +118 -0
  76. package/dist/core/mask.js +70 -0
  77. package/dist/core/metadata-types.js +79 -0
  78. package/dist/core/metasync.js +684 -0
  79. package/dist/core/new-version.js +93 -0
  80. package/dist/core/org.js +115 -0
  81. package/dist/core/origin.js +62 -0
  82. package/dist/core/package-xml.js +157 -0
  83. package/dist/core/pr.js +217 -0
  84. package/dist/core/project-create.js +733 -0
  85. package/dist/core/project-reconnect.js +126 -0
  86. package/dist/core/project-status.js +246 -0
  87. package/dist/core/project-tier.js +374 -0
  88. package/dist/core/project-upgrade.js +138 -0
  89. package/dist/core/project-verify.js +517 -0
  90. package/dist/core/promote-check.js +401 -0
  91. package/dist/core/promote.js +141 -0
  92. package/dist/core/push.js +163 -0
  93. package/dist/core/release.js +256 -0
  94. package/dist/core/scoped-box.js +29 -0
  95. package/dist/core/start.js +155 -0
  96. package/dist/core/switch-org.js +49 -0
  97. package/dist/core/test-types.js +212 -0
  98. package/dist/core/toolbox.js +4 -0
  99. package/dist/core/update-cli.js +156 -0
  100. package/dist/core/update-secret.js +301 -0
  101. package/dist/core/update-workflows.js +132 -0
  102. package/dist/core/verify-gh.js +286 -0
  103. package/dist/core/verify-samples.js +152 -0
  104. package/dist/core/windows-shim.js +21 -0
  105. package/dist/io/capability-file.js +11 -0
  106. package/dist/io/create-deps.js +69 -0
  107. package/dist/io/doctor-deps.js +32 -0
  108. package/dist/io/hook-install-deps.js +11 -0
  109. package/dist/io/job-deps.js +39 -0
  110. package/dist/io/key-file.js +17 -0
  111. package/dist/io/keys.js +172 -0
  112. package/dist/io/log-deps.js +107 -0
  113. package/dist/io/metasync-deps.js +22 -0
  114. package/dist/io/open-browser.js +21 -0
  115. package/dist/io/package-version.js +10 -0
  116. package/dist/io/pinned-project.js +111 -0
  117. package/dist/io/promote-deps.js +28 -0
  118. package/dist/io/push-refs.js +20 -0
  119. package/dist/io/resolve.js +74 -0
  120. package/dist/io/run.js +201 -0
  121. package/dist/io/switch-org-deps.js +10 -0
  122. package/dist/io/temp-dir.js +24 -0
  123. package/dist/io/tool-versions.js +14 -0
  124. package/dist/io/toolbox.js +68 -0
  125. package/dist/io/update-cli-deps.js +75 -0
  126. package/dist/io/update-secret-deps.js +27 -0
  127. package/dist/launch.js +152 -0
  128. package/dist/ui/confirm.js +18 -0
  129. package/dist/ui/launcher.js +163 -0
  130. package/dist/ui/prompt.js +66 -0
  131. package/lib/apexlog.js +819 -0
  132. package/lib/metasync.js +1364 -0
  133. package/lib/package.json +4 -0
  134. package/lib/typecheck.js +547 -0
  135. package/package.json +44 -4
  136. package/templates/.forceignore +12 -0
  137. package/templates/.gitattributes +58 -0
  138. package/templates/.github/workflows/wf-metasync.yml +177 -0
  139. package/templates/.github/workflows/wf-release.yml +454 -0
  140. package/templates/.github/workflows/wf-sequence.yml +292 -0
  141. package/templates/.github/workflows/wf-validate.yml +389 -0
  142. package/templates/.prettierignore +11 -0
  143. package/templates/.prettierrc +17 -0
  144. package/templates/.vscode/extensions.json +9 -0
  145. package/templates/.vscode/launch.json +16 -0
  146. package/templates/.vscode/settings.json +39 -0
  147. package/templates/AGENTS.md +3 -0
  148. package/templates/CLAUDE.md +4 -0
  149. package/templates/README.md +11 -0
  150. package/templates/config/project-scratch-def.json +13 -0
  151. package/templates/eslint.config.js +55 -0
  152. package/templates/force-app/main/default/.gitkeep +0 -0
  153. package/templates/gitignore.template +62 -0
  154. package/templates/jest.config.js +6 -0
  155. package/templates/package.json +29 -0
  156. package/templates/scripts/apex/hello.apex +10 -0
  157. package/templates/scripts/soql/account.soql +6 -0
  158. package/templates/sf-tools/config/branches.txt +24 -0
  159. package/templates/sf-tools/config/metadata.txt +576 -0
  160. package/templates/sfdx-project.json +12 -0
  161. package/templates-ts/.github/workflows/wf-metasync.yml +109 -0
  162. package/templates-ts/.github/workflows/wf-release.yml +263 -0
  163. package/templates-ts/.github/workflows/wf-sequence.yml +153 -0
  164. package/templates-ts/.github/workflows/wf-validate.yml +185 -0
@@ -0,0 +1,565 @@
1
+ // sft log pull: 新しいデバッグログを組織から取り、AI が最初に読む要約(logs/apex/latest.md)を作る。
2
+ // sf-log.sh pull(phases/log/pull.sh の 8 章・phases/log/fetch.sh の 7 章)の、取得役がいないときの道の移し先。組織には書き込まない。
3
+ // 1. 接続先(-o > SF_TARGET_ORG > sf org display)。予約名・本番・種類を確認できない組織は止める。自分のユーザー ID と組織 ID
4
+ // 2. 取得役(node。log-collector.ts)が生きていれば、自分では取らず、依頼(requests/pull.<ID>)を置いて、応答(done.<ID>)を最大 90 秒待つ。
5
+ // 別の環境(シェル版の sf-log.sh)が、このプロジェクトのログを扱っていれば止める(.claim の AT が 30 分以内で環境が
6
+ // node 以外・.collector の STARTED が 12 時間以内で HEARTBEAT が 30 分以内)
7
+ // 3. しおり(.state)が別の組織・ユーザーのものなら、今から取り直す(LAST_FETCH = 30 分前・要約のしおり = 今の目録の最後)
8
+ // 4. 取得のロック(.fetch.lock。最大 90 秒)を持ち、しおり(LAST_FETCH・LAST_FETCH_ID)から古い順に取る(1 回 50 本・最大 4 回)。
9
+ // 一覧は全ユーザーの見出し(画面・ログに出さない)、本文は自分のログだけを保存する。取りたいログより新しいログがすべて自分のもの
10
+ // なら -n でまとめて、それ以外は -i で 1 本ずつ。本文は一時フォルダに書かせ、取りたい ID 以外は中を読まずに消す。
11
+ // 追いついたら、遅れて現れたログを拾い直す(今から 30 分前(LATE_FROM があれば早いほう)からしおりまで。200 本ずつ最大 5 回)
12
+ // 5. 保存: logs/apex/<日付>/<時刻>_<ID>_<操作>.log(PC のタイムゾーン)と、目録 logs/apex/.index
13
+ // 6. 要約のロック(.read.lock。最大 90 秒)を持って要約し(log-summarize.ts の writeSummary)、しおりを進める
14
+ // (--since・ロックが取れないときは進めない)
15
+ // ロックは「PID 環境 時刻」の印のフォルダ(シェル版と同じ形。環境は node。シェル版からは別の環境に見えるので、10 分で古いとみなされる)。
16
+ // 古い .state(LAST_READ・LAST_READ_IDS)からの移し替えは、要約(log-summarize.ts の writeSummary)が行う。
17
+ // sf の更新は待たない(シェル版の pull と同じ。待つのは取得役と自動の取り始め)
18
+ import { isReservedOrgAlias } from "./branches.js";
19
+ import { ID_RE, ISO_RE, indexMark, kvGet, kvSet, parseIndex } from "./log-select.js";
20
+ import { readOrgUser } from "./log-status.js";
21
+ import { parseSummaryArgs, writeSummary } from "./log-summarize.js";
22
+ import { getTargetOrg, orgLocalReleaseCheck } from "./org.js";
23
+ const APEX = "logs/apex";
24
+ const STATE_F = `${APEX}/.state`;
25
+ const STATUS_F = `${APEX}/.status`;
26
+ const INDEX_F = `${APEX}/.index`;
27
+ const COLLECTOR_F = `${APEX}/.collector`;
28
+ const CLAIM_F = `${APEX}/.claim`;
29
+ const LOCK_DIR = `${APEX}/.lock`;
30
+ const FETCH_LOCK = `${APEX}/.fetch.lock`;
31
+ const READ_LOCK = `${APEX}/.read.lock`;
32
+ const LOG_FILE = "sf-tools/logs/sf-log.log";
33
+ export const RUNTIME_SELF = "node";
34
+ const MIX_STALE = 1800;
35
+ const MAX_RUN = 43200;
36
+ const LATE_WINDOW = 1800;
37
+ const LATE_PAGE = 200;
38
+ const LATE_MAX_PAGES = 5;
39
+ const LATE_MAX_AGE = 86400;
40
+ const FIELDS = "Id, LogUserId, StartTime, Operation, Request, Status, LogLength, DurationMilliseconds";
41
+ const BODY_RE = /^[A-Za-z0-9]{15}([A-Za-z0-9]{3})?\.log$/;
42
+ // ---- 日時(lib/apexlog.js の parseTime・fmtZ・time local と同じ) ----
43
+ /** YYYY-MM-DDTHH:MM:SS[.sss](Z|±HHMM|±HH:MM) を UTC のミリ秒に。形が違えば null */
44
+ export function parseTime(s) {
45
+ const m = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,9}))?(Z|[+-]\d{2}:?\d{2})$/.exec(s);
46
+ if (!m)
47
+ return null;
48
+ const [, y, mo, d, h, mi, se, , tz] = m;
49
+ let ms = Date.UTC(+y, +mo - 1, +d, +h, +mi, +se);
50
+ const chk = new Date(ms);
51
+ if (chk.getUTCFullYear() !== +y || chk.getUTCMonth() !== +mo - 1 || chk.getUTCDate() !== +d) {
52
+ return null;
53
+ }
54
+ if (tz !== "Z") {
55
+ const t = tz.replace(":", "");
56
+ const sign = t[0] === "-" ? -1 : 1;
57
+ ms -= sign * (Number(t.slice(1, 3)) * 60 + Number(t.slice(3, 5))) * 60_000;
58
+ }
59
+ return ms;
60
+ }
61
+ /** UTC のミリ秒 → YYYY-MM-DDTHH:MM:SSZ(ミリ秒は切り捨て) */
62
+ export function fmtZ(ms) {
63
+ return new Date(Math.floor(ms / 1000) * 1000).toISOString().replace(/\.\d{3}Z$/, "Z");
64
+ }
65
+ /** PC のタイムゾーンの日付(YYYYMMDD)と時刻(HHMMSS)。保存するログのフォルダとファイル名 */
66
+ export function localParts(ms) {
67
+ const d = new Date(ms);
68
+ const p = (n) => String(n).padStart(2, "0");
69
+ return {
70
+ date: `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}`,
71
+ time: `${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`,
72
+ };
73
+ }
74
+ const cell = (v) => String(v ?? "")
75
+ .replace(/[\r\n\t]+/g, " ")
76
+ .replace(/\|/g, "|")
77
+ .trim();
78
+ /** sf data query --json の ApexLog の応答を検査して読む(lib/apexlog.js の list と同じ)。形が違えば null(中身は、どこにも出さない) */
79
+ export function parseLogList(json, userId) {
80
+ let o;
81
+ try {
82
+ o = JSON.parse(json);
83
+ }
84
+ catch {
85
+ try {
86
+ o = JSON.parse(json.slice(json.indexOf("{"), json.lastIndexOf("}") + 1));
87
+ }
88
+ catch {
89
+ return null;
90
+ }
91
+ }
92
+ if (o?.status !== 0 || !o.result || !Array.isArray(o.result.records))
93
+ return null;
94
+ const me = userId.slice(0, 15);
95
+ const rows = [];
96
+ for (const r of o.result.records) {
97
+ if (!r || typeof r !== "object")
98
+ return null;
99
+ if (typeof r.Id !== "string" || !ID_RE.test(r.Id))
100
+ return null;
101
+ if (typeof r.LogUserId !== "string" || !ID_RE.test(r.LogUserId))
102
+ return null;
103
+ const t = typeof r.StartTime === "string" ? parseTime(r.StartTime) : null;
104
+ if (t === null)
105
+ return null;
106
+ if (!Number.isInteger(r.LogLength) || r.LogLength < 0)
107
+ return null;
108
+ const dur = Number.isInteger(r.DurationMilliseconds) && r.DurationMilliseconds >= 0 ? r.DurationMilliseconds : 0;
109
+ rows.push({
110
+ id: r.Id,
111
+ mine: r.LogUserId.slice(0, 15) === me,
112
+ start: fmtZ(t),
113
+ len: r.LogLength,
114
+ dur,
115
+ op: cell(r.Operation),
116
+ status: cell(r.Status),
117
+ });
118
+ }
119
+ return rows;
120
+ }
121
+ /** 操作名をファイル名の飾りにする(英数字・_・- 以外を _ に。先頭と末尾の _ を除く。最大 30 文字) */
122
+ export function opSlug(op) {
123
+ return op
124
+ .replace(/[^A-Za-z0-9_-]/g, "_")
125
+ .replace(/^_+/, "")
126
+ .replace(/_+$/, "")
127
+ .slice(0, 30);
128
+ }
129
+ export function note(box, level, message) {
130
+ const d = box.clock.now();
131
+ const p = (n) => String(n).padStart(2, "0");
132
+ const at = `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
133
+ try {
134
+ box.files.makeDir("sf-tools/logs");
135
+ box.files.appendText(LOG_FILE, `[${at}] [${level}] ${message}\n`);
136
+ }
137
+ catch {
138
+ // 記録は、書けなくても続ける
139
+ }
140
+ }
141
+ export const read = (box, path) => (box.files.exists(path) ? box.files.readText(path) : "");
142
+ /** .state などを、短いロックの中で書き換える */
143
+ export async function stateSet(ctx, path, updates) {
144
+ if (!(await ctx.deps.lock.take(LOCK_DIR, 50))) {
145
+ ctx.box.output.err(`[WARNING] 手元の状態のロックを取れませんでした(${LOCK_DIR})。`);
146
+ return false;
147
+ }
148
+ try {
149
+ ctx.box.files.writeText(path, kvSet(read(ctx.box, path), updates));
150
+ return true;
151
+ }
152
+ finally {
153
+ ctx.deps.lock.drop(LOCK_DIR);
154
+ }
155
+ }
156
+ async function query(ctx, soql) {
157
+ const r = await ctx.box
158
+ .run("sf", ["data", "query", "--use-tooling-api", "--target-org", ctx.org, "--json", "--query", soql])
159
+ .catch(() => null);
160
+ if (r === null || r.code !== 0) {
161
+ try {
162
+ const n = JSON.parse(r?.stdout ?? "").name;
163
+ return typeof n === "string" && n !== "" ? n : "不明";
164
+ }
165
+ catch {
166
+ return "不明";
167
+ }
168
+ }
169
+ return parseLogList(r.stdout, ctx.userId) ?? "応答の形が正しくありません";
170
+ }
171
+ async function getLog(ctx, args, dir) {
172
+ const r = await ctx.box.run("sf", ["apex", "get", "log", ...args, "-d", dir, "--target-org", ctx.org]).catch(() => null);
173
+ return r !== null && r.code === 0;
174
+ }
175
+ /** 1 本を保存する(同じ名前がすでにあれば、成功として扱う)。目録に同じ ID がなければ足す */
176
+ function saveOne(box, src, row) {
177
+ try {
178
+ const { date, time } = localParts(parseTime(row.start) ?? 0);
179
+ const slug = opSlug(row.op);
180
+ const dir = `${APEX}/${date}`;
181
+ const path = `${dir}/${time}_${row.id}${slug !== "" ? `_${slug}` : ""}.log`;
182
+ box.files.makeDir(dir);
183
+ if (!box.files.exists(path))
184
+ box.files.writeText(path, box.files.readText(src));
185
+ if (!read(box, INDEX_F).includes(`\t${row.id}\t`)) {
186
+ box.files.appendText(INDEX_F, `${[path, row.id, row.start, row.op, row.status, row.len, row.dur].join("\t")}\n`);
187
+ }
188
+ return true;
189
+ }
190
+ catch {
191
+ return false;
192
+ }
193
+ }
194
+ /** 1 回の取得。done = 追いついた / more = まだ残りがある / fail = 失敗 */
195
+ export async function fetchRound(ctx) {
196
+ const { box, deps } = ctx;
197
+ const state = read(box, STATE_F);
198
+ let last = kvGet(state, "LAST_FETCH");
199
+ let lastId = kvGet(state, "LAST_FETCH_ID");
200
+ if (!ISO_RE.test(last)) {
201
+ last = fmtZ(box.clock.now().getTime() - 1800_000);
202
+ lastId = "";
203
+ }
204
+ if (!ID_RE.test(lastId))
205
+ lastId = "";
206
+ const where = lastId !== "" ? `StartTime > ${last} OR (StartTime = ${last} AND Id > '${lastId}')` : `StartTime >= ${last}`;
207
+ const rows = await query(ctx, `SELECT ${FIELDS} FROM ApexLog WHERE ${where} ORDER BY StartTime ASC, Id ASC LIMIT 51`);
208
+ if (typeof rows === "string") {
209
+ note(box, "INFO", `ApexLog の一覧: 失敗(${rows})`);
210
+ return "fail";
211
+ }
212
+ const more = rows.length > 50;
213
+ const list = rows.slice(0, 50);
214
+ const first = list.findIndex((r) => r.mine);
215
+ const mineCount = list.filter((r) => r.mine).length;
216
+ const othersAfter = first >= 0 && list.slice(first).some((r) => !r.mine);
217
+ note(box, "INFO", `ApexLog の一覧: ${list.length} 本(自分のログ ${mineCount} 本)${more ? "・残りあり" : ""}`);
218
+ if (list.length === 0)
219
+ return "done";
220
+ const lastRow = list[list.length - 1];
221
+ if (first < 0) {
222
+ if (!(await stateSet(ctx, STATE_F, { LAST_FETCH: lastRow.start, LAST_FETCH_ID: lastRow.id })))
223
+ return "fail";
224
+ return more ? "more" : "done";
225
+ }
226
+ // 本文は、毎回新しい一時フォルダに書かせる(他の人の本文を残さない)
227
+ const tmp = deps.makeTempDir();
228
+ try {
229
+ if (!more && !othersAfter && !(await getLog(ctx, ["-n", String(list.length - first)], tmp)))
230
+ return "fail";
231
+ if (box.files.listDir(tmp).some((n) => n !== "one" && !BODY_RE.test(n))) {
232
+ note(box, "INFO", "本文の取得: 想定しない名前のファイルがあったため、この回を失敗にします");
233
+ return "fail";
234
+ }
235
+ for (const row of list) {
236
+ if (row.mine) {
237
+ let src = `${tmp}/${row.id}.log`;
238
+ if (!box.files.exists(src)) {
239
+ // -n で押し出された・1 本ずつ取る場合(-i は ID を指定するので、他の人のログは入らない)
240
+ const one = `${tmp}/one`;
241
+ deps.removeDir(one);
242
+ box.files.makeDir(one);
243
+ if (!(await getLog(ctx, ["-i", row.id], one)))
244
+ return "fail";
245
+ src = `${one}/${row.id}.log`;
246
+ if (!box.files.exists(src)) {
247
+ note(box, "INFO", `本文の取得: ${row.id} のファイルがありません`);
248
+ return "fail";
249
+ }
250
+ }
251
+ if (!saveOne(box, src, row))
252
+ return "fail";
253
+ }
254
+ if (!(await stateSet(ctx, STATE_F, { LAST_FETCH: row.start, LAST_FETCH_ID: row.id })))
255
+ return "fail";
256
+ }
257
+ }
258
+ finally {
259
+ deps.removeDir(tmp);
260
+ }
261
+ return more ? "more" : "done";
262
+ }
263
+ /**
264
+ * 遅れて現れたログの拾い直し(doc/sf-log-design.md 8.3)。通常の取得が追いついた回に 1 回。しおりは動かさない。
265
+ * 戻り値: 知らせること(空なら、なし)。失敗しても、その回の取得は成功として扱う
266
+ */
267
+ export async function lateRecheck(ctx) {
268
+ const { box, deps } = ctx;
269
+ const state = read(box, STATE_F);
270
+ const last = kvGet(state, "LAST_FETCH");
271
+ if (!ISO_RE.test(last))
272
+ return "";
273
+ const nowMs = box.clock.now().getTime();
274
+ let lower = fmtZ(nowMs - LATE_WINDOW * 1000);
275
+ let lf = kvGet(state, "LATE_FROM");
276
+ let warn = "";
277
+ if (lf !== "" && !ISO_RE.test(lf)) {
278
+ await stateSet(ctx, STATE_F, { LATE_FROM: "" });
279
+ lf = "";
280
+ }
281
+ if (lf !== "" && parseTime(lf) < nowMs - LATE_MAX_AGE * 1000) {
282
+ await stateSet(ctx, STATE_F, { LATE_FROM: "" });
283
+ warn = `遅れて現れたログの拾い直しの失敗が 24 時間続いたため、${lf}(UTC)からの分の拾い直しをやめました`;
284
+ note(box, "WARNING", `拾い直し: ${warn}`);
285
+ lf = "";
286
+ }
287
+ if (lf === "" && last < lower)
288
+ return warn; // しおりが 30 分より古い(範囲が空)
289
+ if (lf !== "" && lf < lower)
290
+ lower = lf;
291
+ if (lower > last) {
292
+ await stateSet(ctx, STATE_F, { LATE_FROM: "" });
293
+ return warn;
294
+ }
295
+ let before = null;
296
+ let seen = 0;
297
+ let got = 0;
298
+ let failed = false;
299
+ let full = false;
300
+ const join = (a, b) => (a !== "" ? `${a}。${b}` : b);
301
+ const tmp = deps.makeTempDir();
302
+ try {
303
+ for (let page = 1; page <= LATE_MAX_PAGES && !failed; page++) {
304
+ let where = `LogUserId = '${ctx.userId}' AND StartTime >= ${lower} AND StartTime <= ${last}`;
305
+ if (before)
306
+ where += ` AND (StartTime < ${before.start} OR (StartTime = ${before.start} AND Id < '${before.id}'))`;
307
+ const rows = await query(ctx, `SELECT ${FIELDS} FROM ApexLog WHERE ${where} ORDER BY StartTime DESC, Id DESC LIMIT ${LATE_PAGE}`);
308
+ if (typeof rows === "string") {
309
+ note(box, "WARNING", `拾い直し: 一覧の失敗(${rows})`);
310
+ failed = true;
311
+ break;
312
+ }
313
+ for (const row of rows) {
314
+ before = row;
315
+ if (!row.mine)
316
+ continue; // 念のため(検索は自分のログだけ)
317
+ seen++;
318
+ if (read(box, INDEX_F).includes(`\t${row.id}\t`))
319
+ continue;
320
+ const one = `${tmp}/one`;
321
+ deps.removeDir(one);
322
+ box.files.makeDir(one);
323
+ const src = `${one}/${row.id}.log`;
324
+ if (!(await getLog(ctx, ["-i", row.id], one)) || !box.files.exists(src)) {
325
+ note(box, "WARNING", `拾い直し: ${row.id} を取れませんでした`);
326
+ failed = true;
327
+ break;
328
+ }
329
+ if (!saveOne(box, src, row)) {
330
+ failed = true;
331
+ break;
332
+ }
333
+ got++;
334
+ }
335
+ if (rows.length < LATE_PAGE)
336
+ break;
337
+ if (page === LATE_MAX_PAGES)
338
+ full = true;
339
+ }
340
+ }
341
+ finally {
342
+ deps.removeDir(tmp);
343
+ }
344
+ note(box, "INFO", `拾い直し: 自分のログ ${seen} 本を見て、${got} 本を拾い直しました(${lower}〜${last}。UTC)`);
345
+ if (failed) {
346
+ // その回の下限を残す(範囲の下限は毎回進むため、残さないと、失敗したログが次の回には範囲の外に出ることがある)
347
+ await stateSet(ctx, STATE_F, { LATE_FROM: lower });
348
+ warn = join(warn, `遅れて現れたログの拾い直しに失敗しました(次の回に、${lower}(UTC)からやり直します)`);
349
+ note(box, "WARNING", `拾い直し: ${warn}`);
350
+ return warn;
351
+ }
352
+ await stateSet(ctx, STATE_F, { LATE_FROM: "" });
353
+ if (full) {
354
+ warn = join(warn, `拾い直しの範囲に自分のログが ${LATE_PAGE * LATE_MAX_PAGES} 本を超えてあったため、${lower}〜${before?.start ?? ""}(UTC)に始まったログの一部は、拾い直していないかもしれません`);
355
+ note(box, "WARNING", `拾い直し: ${warn}`);
356
+ }
357
+ return warn;
358
+ }
359
+ /** 別の環境(シェル版の sf-log.sh など)や別の取得役が、このプロジェクトのログを扱っているか。扱っていれば、その説明 */
360
+ export function otherHandler(box) {
361
+ const now = Math.floor(box.clock.now().getTime() / 1000);
362
+ const recent = (at, sec) => !/^[0-9]+$/.test(at) || Number(at) > now || now - Number(at) <= sec;
363
+ const claim = read(box, CLAIM_F);
364
+ if (claim !== "") {
365
+ const rt = kvGet(claim, "RUNTIME");
366
+ if (rt !== RUNTIME_SELF && recent(kvGet(claim, "AT"), MIX_STALE))
367
+ return `別の環境(${rt || "不明"})が、このプロジェクトのログを扱っています`;
368
+ }
369
+ const col = read(box, COLLECTOR_F);
370
+ if (col === "")
371
+ return null;
372
+ const started = kvGet(col, "STARTED");
373
+ if (!/^[0-9]+$/.test(started) || (Number(started) <= now && now - Number(started) >= MAX_RUN))
374
+ return null;
375
+ if (recent(kvGet(col, "HEARTBEAT"), MIX_STALE))
376
+ return `取得役(${kvGet(col, "RUNTIME") || "シェル版"})が動いています`;
377
+ return null;
378
+ }
379
+ const REQ_DIR = `${APEX}/requests`;
380
+ const PULL_WAIT = 90;
381
+ /** 生きている取得役(node)の PID と組織。いなければ null */
382
+ function liveNodeCollector(box, deps) {
383
+ const col = read(box, COLLECTOR_F);
384
+ const pid = kvGet(col, "PID");
385
+ if (kvGet(col, "RUNTIME") !== RUNTIME_SELF || !/^[0-9]+$/.test(pid) || !deps.pidAlive?.(Number(pid)))
386
+ return null;
387
+ return { pid, org: kvGet(col, "ORG") };
388
+ }
389
+ /** 取得役に取得を頼み、自分の ID の応答を最大 90 秒待つ(依頼は ID つきのファイル)。ok / error / timeout */
390
+ export async function requestCollector(box, deps, pid) {
391
+ const at = Math.floor(box.clock.now().getTime() / 1000);
392
+ const id = `${at}_${Math.floor(Math.random() * 1_000_000)}_${pid}`;
393
+ box.files.makeDir(REQ_DIR);
394
+ box.files.writeText(`${REQ_DIR}/pull.${id}`, `AT=${at}\n`);
395
+ for (let i = 0; i < PULL_WAIT; i++) {
396
+ const done = `${REQ_DIR}/done.${id}`;
397
+ if (box.files.exists(done)) {
398
+ const res = kvGet(read(box, done), "RESULT");
399
+ box.files.removeFile(done);
400
+ return res === "ok" ? "ok" : "error";
401
+ }
402
+ if (!deps.pidAlive?.(Number(pid)))
403
+ break;
404
+ await box.clock.sleep(1000);
405
+ }
406
+ box.files.removeFile(`${REQ_DIR}/pull.${id}`);
407
+ return "timeout";
408
+ }
409
+ class Stop extends Error {
410
+ code;
411
+ constructor(code, message) {
412
+ super(message);
413
+ this.code = code;
414
+ }
415
+ }
416
+ async function pull(args, box, deps) {
417
+ let orgArg = "";
418
+ const rest = [];
419
+ for (let i = 0; i < args.length; i++) {
420
+ const a = args[i];
421
+ if (a === "-o") {
422
+ const v = args[i + 1] ?? "";
423
+ if (v === "" || v.startsWith("-"))
424
+ throw new Stop(1, "-o には、組織のエイリアスを指定してください。");
425
+ orgArg = v;
426
+ i++;
427
+ }
428
+ else
429
+ rest.push(a);
430
+ }
431
+ const parsed = parseSummaryArgs(rest);
432
+ if (typeof parsed === "string")
433
+ throw new Stop(1, parsed);
434
+ const org = await getTargetOrg(box, orgArg);
435
+ if (org === null)
436
+ throw new Stop(1, "接続先の組織エイリアスを特定できません。");
437
+ if (isReservedOrgAlias(org))
438
+ throw new Stop(1, `${org} は共有環境(予約名)のため、ログを取りません。`);
439
+ const kind = await orgLocalReleaseCheck(box, org);
440
+ if (kind === 1)
441
+ throw new Stop(1, `${org} は本番組織のため、ログを取りません。`);
442
+ if (kind === 2)
443
+ throw new Stop(1, `${org} の組織の種類を確認できないため、ログを取りません。`);
444
+ const user = await readOrgUser(box, org);
445
+ if (typeof user === "string")
446
+ throw new Stop(1, `ユーザーの情報を取得できません(${user})。`);
447
+ const collector = liveNodeCollector(box, deps);
448
+ const other = collector === null ? otherHandler(box) : null;
449
+ if (other !== null)
450
+ throw new Stop(1, `${other}。そちらで pull してください(sft log pull)。`);
451
+ const ctx = { box, deps, org, userId: user.userId };
452
+ box.files.makeDir(APEX);
453
+ // 取得役の組織が違うなら、しおりを書き換える前に止める(止めたあとに、しおりだけ別の組織になるのを防ぐ)
454
+ if (collector !== null && collector.org !== org)
455
+ throw new Stop(1, `取得役が、別の組織(${collector.org})で動いています(PID ${collector.pid})。`);
456
+ // しおりが別の組織・ユーザーのものなら、今から取り直す(別の組織の時刻・ID を使わない)
457
+ const state = read(box, STATE_F);
458
+ if (kvGet(state, "ORG") !== org || kvGet(state, "USER_ID") !== user.userId) {
459
+ const mark = indexMark(parseIndex(read(box, INDEX_F)));
460
+ const ok = await stateSet(ctx, STATE_F, {
461
+ ORG: org,
462
+ USER_ID: user.userId,
463
+ LAST_FETCH: fmtZ(box.clock.now().getTime() - 1800_000),
464
+ LAST_FETCH_ID: "",
465
+ LATE_FROM: "",
466
+ LAST_READ_LINE: String(mark.line),
467
+ LAST_READ_ID: mark.id,
468
+ LAST_READ: "",
469
+ LAST_READ_IDS: "",
470
+ });
471
+ if (!ok)
472
+ throw new Stop(1, "手元の状態を書けません。");
473
+ }
474
+ const notes = [];
475
+ if (collector !== null) {
476
+ // 取得役が生きている → 自分では取らず、取得役に頼む(組織から取って、しおりを書くのは取得役だけ)
477
+ const res = await requestCollector(box, deps, collector.pid);
478
+ const status = read(box, STATUS_F);
479
+ if (res === "ok") {
480
+ notes.push(`取得役: 動作中(最後の取得 ${kvGet(status, "LAST_FETCH")})`);
481
+ const late = kvGet(status, "LATE_WARNING");
482
+ if (late !== "")
483
+ notes.push(late);
484
+ }
485
+ else if (res === "error") {
486
+ notes.push(`取得役: 直前の取得に失敗しています(${LOG_FILE} を参照)。手元にある分で要約しました`);
487
+ }
488
+ else {
489
+ box.output.err(`[WARNING] 取得役の取り込みが、${PULL_WAIT} 秒で終わりませんでした。手元にある分で要約します。`);
490
+ notes.push(`取り込みが終わっていません(残り約 ${kvGet(status, "BACKLOG")} 本)。手元にある分で要約しました。少し待って、もう一度 pull してください`);
491
+ }
492
+ }
493
+ else {
494
+ await fetchDirect(ctx, notes);
495
+ }
496
+ return summarize(box, deps, parsed, notes);
497
+ }
498
+ /** 取得役がいない: 自分で取る(取得のロックを持つ。最大 90 秒待つ) */
499
+ async function fetchDirect(ctx, notes) {
500
+ const { deps } = ctx;
501
+ if (!(await deps.lock.take(FETCH_LOCK, 450)))
502
+ throw new Stop(1, `取得のロックを取れませんでした(${FETCH_LOCK}。ほかの取得が終わりません)。`);
503
+ let result = "done";
504
+ try {
505
+ for (let round = 1; round <= 4; round++) {
506
+ result = await fetchRound(ctx);
507
+ if (result !== "more")
508
+ break;
509
+ }
510
+ if (result === "done") {
511
+ const late = await lateRecheck(ctx); // 追いついたときだけ(200 本の上限で止まったら、次の回に回す)
512
+ if (late !== "")
513
+ notes.push(late);
514
+ }
515
+ }
516
+ finally {
517
+ deps.lock.drop(FETCH_LOCK);
518
+ }
519
+ if (result === "fail")
520
+ throw new Stop(1, `ログを取得できませんでした(${LOG_FILE} を参照)。`);
521
+ if (result === "more")
522
+ notes.push("取り込みの残りがあります(200 本を超えました)。もう一度 sft log pull を実行すると、続きを取ります。");
523
+ notes.push("取得役: 動いていません(この pull が、組織から直接取りました)");
524
+ }
525
+ async function summarize(box, deps, parsed, notes) {
526
+ const now = read(box, STATE_F);
527
+ if (kvGet(now, "TRACE_FLAG_ID") === "") {
528
+ const status = read(box, STATUS_F);
529
+ const reason = kvGet(status, "STATE") === "stopped" ? kvGet(status, "REASON") : "";
530
+ notes.push(`sf-log の TraceFlag がありません(新しいログは出ません${reason !== "" ? `。理由: ${reason}` : ""})。人に sft の起動か sft log start を頼んでください`);
531
+ }
532
+ const exp = kvGet(read(box, STATUS_F), "EXPIRES");
533
+ if (exp !== "")
534
+ notes.push(`TraceFlag の期限: ${exp}(UTC)`);
535
+ // 要約のロックを持ってから、しおりを読む(同時に動く pull が、先にしおりを進めることがあるため)
536
+ const held = await deps.lock.take(READ_LOCK, 450);
537
+ if (!held) {
538
+ box.output.err(`[WARNING] 要約のロックを取れませんでした(${READ_LOCK})。しおりを読まず・進めずに要約します。`);
539
+ notes.push(`要約のロックを取れませんでした(ほかの pull が動いています)。しおりを進めずに、直近 ${parsed.since ?? 30} 分に始まったログで要約しました`);
540
+ }
541
+ try {
542
+ return await writeSummary(box, deps, {
543
+ max: parsed.max,
544
+ since: held ? parsed.since : (parsed.since ?? 30),
545
+ notes,
546
+ advance: held,
547
+ writeState: (u) => stateSet({ box, deps }, STATE_F, u),
548
+ });
549
+ }
550
+ finally {
551
+ if (held)
552
+ deps.lock.drop(READ_LOCK);
553
+ }
554
+ }
555
+ export async function runLogPull(args, box, deps) {
556
+ try {
557
+ return await pull(args, box, deps);
558
+ }
559
+ catch (e) {
560
+ if (!(e instanceof Stop))
561
+ throw e;
562
+ box.output.err(`[ERROR] ${e.message}`);
563
+ return e.code;
564
+ }
565
+ }