@hit-sudomaker/ccw 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,99 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { json, object } from './model.js';
3
+ import { step } from './work.js';
4
+ /**
5
+ * 计算区分 undefined 与 null 的 JSON 摘要
6
+ *
7
+ * @param value - 可序列化配置值,undefined 表示缺失
8
+ * @returns SHA-256 十六进制摘要,保留键顺序
9
+ * @throws TypeError - 循环引用或 bigint 等不可序列化内容;访问器及 toJSON 异常原样传播
10
+ */
11
+ export const jsonFingerprint = (value) => createHash('sha256').update(JSON.stringify({ value })).digest('hex');
12
+ /**
13
+ * 冻结字段并准备原子 JSON 编辑
14
+ *
15
+ * @param options - 文件、原值摘要、目标字段及可公开的变更说明和效果
16
+ * @returns 不公开字段值的延迟编辑步骤
17
+ * @throws 无法克隆目标值或计算摘要时同步抛出
18
+ * @remarks 路径和值均复制,undefined 表示删除;写入前及原子回调内都复核原值
19
+ */
20
+ export function frozenJsonWork(ctx, options) {
21
+ const { file, changes, effects } = options;
22
+ const fields = options.fields.map(field => {
23
+ const value = structuredClone(field.value);
24
+ return { path: [...field.path], before: field.before, after: jsonFingerprint(value), value };
25
+ });
26
+ return step(changes, async (fact) => {
27
+ const result = assessFrozenJson(await json(ctx.machine, file), fields, fact);
28
+ return result.state === 'complete' ? { ...result, effects } : result;
29
+ }, async () => {
30
+ await ctx.effects.editJson(file, document => applyFrozenJson(document, fields));
31
+ return { receipt: { kind: 'returned', failure: null } };
32
+ });
33
+ }
34
+ /**
35
+ * 比较字段与冻结值,判断完成、可写或漂移
36
+ *
37
+ * @param document - 当前配置快照
38
+ * @param fields - 每个字段的路径和修改前后摘要
39
+ * @param fact - 已派发与已确认的执行历史
40
+ * @param problem - 目标不符时使用的问题码
41
+ * @returns 只读核验结果
42
+ * @throws Error - 路径经过非对象时为 invalid-settings;读取或摘要异常原样传播
43
+ * @remarks 已确认的写入不能因目标回退而重新派发
44
+ */
45
+ export function assessFrozenJson(document, fields, fact, problem = 'target-changed') {
46
+ const current = fields.map(field => jsonFingerprint(jsonField(document, field.path)));
47
+ if (fields.every((field, index) => current[index] === field.after))
48
+ return { state: 'complete' };
49
+ if (!fact.confirmed &&
50
+ !(fact.receipt?.kind === 'returned' && fact.receipt.failure === null) &&
51
+ fields.every((field, index) => current[index] === field.before))
52
+ return { state: 'ready' };
53
+ return { state: 'blocked', problem };
54
+ }
55
+ /**
56
+ * 核对冻结摘要后原地修改指定 JSON 字段
57
+ *
58
+ * @param document - 原子编辑回调内的可变配置对象
59
+ * @param fields - 字段路径、原值摘要及目标值;undefined 表示删除
60
+ * @param problem - 当前值与冻结摘要不符时抛出的问题码
61
+ * @throws Error - 原值漂移、路径经过非对象值或字段路径为空;属性访问或摘要计算异常原样传播
62
+ * @remarks 所有摘要先核对再赋值;文件持久化及原子性由调用方负责
63
+ */
64
+ export function applyFrozenJson(document, fields, problem = 'target-changed') {
65
+ for (const field of fields)
66
+ if (jsonFingerprint(jsonField(document, field.path)) !== field.before)
67
+ throw new Error(problem);
68
+ for (const field of fields) {
69
+ let parent = document;
70
+ for (const part of field.path.slice(0, -1)) {
71
+ const child = object(Object.hasOwn(parent, part) ? parent[part] : undefined);
72
+ Object.defineProperty(parent, part, { value: child, writable: true, enumerable: true, configurable: true });
73
+ parent = child;
74
+ }
75
+ const key = field.path.at(-1);
76
+ if (key === undefined)
77
+ throw new Error('operation-record-invalid');
78
+ if (field.value === undefined)
79
+ delete parent[key];
80
+ else
81
+ Object.defineProperty(parent, key, { value: field.value, writable: true, enumerable: true, configurable: true });
82
+ }
83
+ }
84
+ /**
85
+ * 沿自有属性路径读取 JSON 字段
86
+ *
87
+ * @param document - 待读取的 JSON 对象
88
+ * @param parts - 字段路径;空路径返回整个对象
89
+ * @returns 字段值;路径缺失时返回 undefined
90
+ * @throws Error - 已存在的中间值不是对象时抛出 invalid-settings
91
+ */
92
+ export function jsonField(document, parts) {
93
+ let current = document;
94
+ for (const part of parts) {
95
+ const parent = object(current);
96
+ current = Object.hasOwn(parent, part) ? parent[part] : undefined;
97
+ }
98
+ return current;
99
+ }
@@ -0,0 +1,71 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { createConnection, createServer } from 'node:net';
3
+ import os from 'node:os';
4
+ import { errorCode } from './machine.js';
5
+ const HOST = '127.0.0.1';
6
+ const DYNAMIC_PORT_MIN = 49_152;
7
+ const DYNAMIC_PORT_COUNT = 16_384;
8
+ const PORT_HASH_HEX_LENGTH = 8;
9
+ const OWNER_PROBE_TIMEOUT_MS = 500;
10
+ /**
11
+ * 为当前系统用户获取基于回环监听端口的单实例租约
12
+ *
13
+ * @returns 用于关闭监听并释放租约的 release 方法
14
+ * @throws Error - 用户身份读取失败时 Promise 拒绝;端口已响应同一用户的租约标识时以 instance-already-running 拒绝
15
+ * 无法确认占用者或监听失败时以 instance-lock-unavailable 拒绝
16
+ * @remarks 监听不阻止进程退出;进程终止时内核释放端口
17
+ */
18
+ export async function acquireInstance() {
19
+ // 用系统用户信息固定身份,避免 HOME、USERPROFILE 或 Claude 配置根变化产生第二个实例身份
20
+ const user = os.userInfo();
21
+ const identity = createHash('sha256')
22
+ .update(JSON.stringify([process.platform, user.uid, user.username, user.homedir]))
23
+ .digest('hex');
24
+ const port = DYNAMIC_PORT_MIN + (Number.parseInt(identity.slice(0, PORT_HASH_HEX_LENGTH), 16) % DYNAMIC_PORT_COUNT);
25
+ const signature = `ccw-instance:${identity}\n`;
26
+ const server = createServer(socket => {
27
+ socket.on('error', () => socket.destroy());
28
+ socket.end(signature, () => socket.destroy());
29
+ });
30
+ try {
31
+ await new Promise((resolve, reject) => {
32
+ server.once('error', reject);
33
+ server.listen({ host: HOST, port, exclusive: true }, resolve);
34
+ });
35
+ }
36
+ catch (error) {
37
+ const owned = errorCode(error) === 'EADDRINUSE' && (await isOwner(port, signature));
38
+ throw new Error(owned ? 'instance-already-running' : 'instance-lock-unavailable', { cause: error });
39
+ }
40
+ server.unref();
41
+ return {
42
+ /** 关闭监听并释放租约;关闭失败或重复释放时 Promise 拒绝 */
43
+ release: () => new Promise((resolve, reject) => {
44
+ server.close(error => {
45
+ if (error)
46
+ reject(error);
47
+ else
48
+ resolve();
49
+ });
50
+ }),
51
+ };
52
+ }
53
+ function isOwner(port, signature) {
54
+ return new Promise(resolve => {
55
+ const socket = createConnection({ host: HOST, port });
56
+ let response = '';
57
+ const finish = (matches) => {
58
+ socket.destroy();
59
+ resolve(matches);
60
+ };
61
+ socket.setEncoding('utf8');
62
+ socket.setTimeout(OWNER_PROBE_TIMEOUT_MS, () => finish(false));
63
+ socket.on('error', () => finish(false));
64
+ socket.on('end', () => finish(response === signature));
65
+ socket.on('data', (chunk) => {
66
+ response += chunk;
67
+ if (response.length >= signature.length)
68
+ finish(response === signature);
69
+ });
70
+ });
71
+ }