-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmock-server.js
More file actions
962 lines (863 loc) · 31.6 KB
/
mock-server.js
File metadata and controls
962 lines (863 loc) · 31.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
import http from "node:http";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { URL } from "node:url";
const args = process.argv.slice(2);
const argMap = new Map();
for (let index = 0; index < args.length; index += 1) {
const item = args[index];
if (item.startsWith("--")) {
const next = args[index + 1];
if (next && !next.startsWith("--")) {
argMap.set(item, next);
index += 1;
} else {
argMap.set(item, "true");
}
}
}
const port = Number(argMap.get("--port") || process.env.PORT || 8787);
const host = argMap.get("--host") || process.env.HOST || "127.0.0.1";
const workspaceDir = path.dirname(fileURLToPath(import.meta.url));
const bootstrapPath = path.join(workspaceDir, "mock-bootstrap.json");
const statePath = path.join(workspaceDir, "mock-server-state.json");
const apiBase = "/api/compute-tide";
function readJson(filePath) {
return JSON.parse(fs.readFileSync(filePath, "utf8"));
}
function writeJson(filePath, payload) {
fs.writeFileSync(filePath, `${JSON.stringify(payload, null, 2)}\n`, "utf8");
}
function cloneData(value) {
return JSON.parse(JSON.stringify(value));
}
function loadInitialSnapshot() {
const bootstrap = readJson(bootstrapPath);
const snapshot = bootstrap.snapshot || bootstrap.data || bootstrap;
return cloneData(snapshot);
}
function loadState() {
if (fs.existsSync(statePath)) {
return readJson(statePath);
}
const snapshot = loadInitialSnapshot();
writeJson(statePath, snapshot);
return snapshot;
}
let store = loadState();
function saveState() {
writeJson(statePath, store);
}
function resetState() {
store = loadInitialSnapshot();
saveState();
return store;
}
function sendJson(response, statusCode, payload) {
response.writeHead(statusCode, {
"Content-Type": "application/json; charset=utf-8",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET,POST,PUT,OPTIONS",
"Access-Control-Allow-Headers": "Content-Type",
"Cache-Control": "no-store",
});
response.end(JSON.stringify(payload, null, 2));
}
function sendOk(response, data, message = "success") {
sendJson(response, 200, {
code: "0",
message,
data,
});
}
function sendText(response, statusCode, payload, contentType = "text/plain; charset=utf-8") {
response.writeHead(statusCode, {
"Content-Type": contentType,
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET,POST,PUT,OPTIONS",
"Access-Control-Allow-Headers": "Content-Type",
"Cache-Control": "no-store",
});
response.end(payload);
}
function parseBody(request) {
return new Promise((resolve, reject) => {
const chunks = [];
request.on("data", (chunk) => chunks.push(chunk));
request.on("end", () => {
const text = Buffer.concat(chunks).toString("utf8");
if (!text) {
resolve({});
return;
}
try {
resolve(JSON.parse(text));
} catch (error) {
reject(new Error("Invalid JSON request body"));
}
});
request.on("error", reject);
});
}
function getSnapshotEnvelope(extra = {}) {
return {
...extra,
snapshot: cloneData(store),
};
}
function ensureFormalCollections() {
if (!Array.isArray(store.messages)) {
store.messages = [
{
id: 1,
title: "申请提交成功",
content: "本地 mock server 已启用正式 V1 API。",
bizType: "SYSTEM",
bizId: "mock-server",
recipients: ["ops001"],
isRead: false,
createdAt: formatDateTime(new Date()),
},
];
}
if (!Array.isArray(store.migrations)) {
store.migrations = [];
}
if (!Array.isArray(store.adminUsers)) {
store.adminUsers = [
{ id: 1, username: "zhang", displayName: "张工", role: "普通申请人", status: "启用" },
{ id: 2, username: "liu", displayName: "刘工", role: "审批人", status: "启用" },
{ id: 3, username: "ops001", displayName: "平台运维", role: "运维人员", status: "启用" },
];
}
if (!Array.isArray(store.adminConfigs)) {
store.adminConfigs = [
{ key: "UNUSED_SETTLE_DELAY_MINUTES", value: "30", description: "完全未使用判定延迟分钟数" },
{ key: "TASK_SYNC_INTERVAL_MINUTES", value: "5", description: "任务同步周期分钟数" },
{ key: "APPLY_TIMEOUT_SCAN_INTERVAL", value: "1", description: "审批超时扫描周期分钟数" },
];
}
if (!store.approvalFlows || typeof store.approvalFlows !== "object") {
store.approvalFlows = {};
}
store.pools.forEach((pool) => {
if (!store.approvalFlows[pool.id]) {
store.approvalFlows[pool.id] = {
poolCode: pool.id,
poolName: pool.name,
nodes: [
{ seq: 1, name: "资源负责人", approvers: "liu, chen" },
{ seq: 2, name: "平台运维", approvers: "ops001" },
],
};
}
});
}
function addFormalMessage(title, content, bizType, bizId, recipients = []) {
ensureFormalCollections();
const maxId = store.messages.reduce((max, item) => Math.max(max, Number(item.id || 0)), 0);
store.messages.unshift({
id: maxId + 1,
title,
content,
bizType,
bizId,
recipients,
isRead: false,
createdAt: formatDateTime(new Date()),
});
}
function formalPoolStatus(status) {
return status === "停用" || status === "INACTIVE" ? "停用" : "启用";
}
function toFormalPool(pool) {
return {
poolCode: pool.id,
poolName: pool.name,
status: formalPoolStatus(pool.status),
nodeCount: Number(pool.nodes || pool.nodeCount || 0),
totalGpu: Number(pool.totalGpu || 0),
usedGpu: Number(pool.usedGpu || 0),
reservedGpu: Number(pool.reservedToday || 0),
pendingGpu: store.reservations
.filter((item) => item.pool === pool.id)
.filter((item) => item.status === "pending" || item.status === "approving")
.reduce((sum, item) => sum + Number(item.gpu || 0), 0),
remark: pool.remark || pool.type || "",
};
}
function toFormalNode(node) {
return {
nodeName: node.name || node.id,
poolCode: node.pool,
gpuCount: Number(node.totalGpu || node.gpuCount || 8),
status: "启用",
remark: node.runningTasks > 0 ? "存在运行任务" : "可迁移",
};
}
function toFormalApplicationStatus(reservation) {
if (reservation.status === "pending") return "待审批";
if (reservation.status === "approving") return "审批中";
if (reservation.status === "rejected") return "已终止";
if (reservation.status === "cancelled") return "已取消";
if (reservation.fulfillment === "已结束" || reservation.fulfillment === "已完成") return "已结束";
return "生效中";
}
function toFormalComplianceResult(reservation) {
if (reservation.fulfillment === "跨机风险") return "超额使用";
if (reservation.fulfillment === "资源不足") return "超额使用";
if (reservation.id === "未绑定") return "无申请ID";
return "合规";
}
function toFormalApplication(reservation) {
return {
applyId: reservation.id,
applicant: reservation.applicant || "unknown",
poolCode: reservation.pool,
startTime: reservation.start,
endTime: reservation.end,
gpuCount: Number(reservation.gpu || 0),
topologyType: Number(reservation.gpu || 0) > 8 ? "允许跨节点" : "必须单节点",
purpose: reservation.project || "未命名申请",
remark: reservation.remark || "",
status: toFormalApplicationStatus(reservation),
terminateReason: reservation.status === "rejected" ? "审批拒绝" : undefined,
complianceResult: reservation.status === "approved" ? toFormalComplianceResult(reservation) : undefined,
currentApprovalNode: reservation.status === "approving" ? "平台运维" : reservation.status === "pending" ? "资源负责人" : "全部通过",
createdAt: reservation.createdAt || reservation.start,
updatedAt: reservation.updatedAt || reservation.end,
};
}
function toFormalTask(task, index) {
return {
taskId: task.taskId || `task-${String(index + 1).padStart(4, "0")}`,
taskName: task.name,
applicant: task.applicant || task.project || "unknown",
applyId: task.reservationId === "未绑定" ? undefined : task.reservationId,
poolCode: task.pool,
gpuCount: Number(task.gpu || 0),
startTime: task.start || "",
endTime: task.end || undefined,
status: task.status || "UNKNOWN",
};
}
function getFormalApprovalTodos() {
return store.reservations
.filter((item) => item.status === "pending" || item.status === "approving")
.map((item) => ({
applyId: item.id,
nodeName: item.status === "approving" ? "平台运维" : "资源负责人",
applicant: item.applicant || "unknown",
poolCode: item.pool,
submittedAt: item.createdAt || item.start,
}));
}
function getFormalCompliance() {
const invalidTasks = store.tasks
.filter((task) => task.reservationId === "未绑定")
.map((task) => ({
applyId: "未绑定",
applicant: task.applicant || "unknown",
poolCode: task.pool,
approvedGpuCount: 0,
peakGpuCount: Number(task.gpu || 0),
usedGpuHours: Number(task.gpu || 0) * 0.8,
complianceRate: 0,
result: "无申请ID",
anomalyTypes: ["无申请ID"],
}));
const summaries = store.reservations.map((item) => {
const relatedTasks = store.tasks.filter((task) => task.reservationId === item.id);
const peak = relatedTasks.reduce((sum, task) => sum + Number(task.gpu || 0), 0) || Number(item.gpu || 0);
const result = toFormalComplianceResult(item);
return {
applyId: item.id,
applicant: item.applicant || "unknown",
poolCode: item.pool,
approvedGpuCount: Number(item.gpu || 0),
peakGpuCount: peak,
usedGpuHours: Number((peak * 5.15).toFixed(2)),
complianceRate: item.gpu ? Number((peak / Number(item.gpu)).toFixed(2)) : 0,
result,
anomalyTypes: result === "合规" ? [] : [result],
};
});
return [...summaries, ...invalidTasks];
}
function getFormalBootstrap() {
ensureFormalCollections();
return {
resourcePools: store.pools.map(toFormalPool),
nodes: store.nodes.map(toFormalNode),
applications: store.reservations.map(toFormalApplication),
approvalTodos: getFormalApprovalTodos(),
tasks: store.tasks.map(toFormalTask),
compliance: getFormalCompliance(),
migrations: cloneData(store.migrations),
messages: cloneData(store.messages),
};
}
function nextApplyId() {
const stamp = new Date().toISOString().replace(/\D/g, "").slice(0, 14);
const sequence = String(store.reservations.length + 1).padStart(4, "0");
return `RID${stamp}${sequence}`;
}
function nextReservationId() {
const today = new Date().toISOString().slice(0, 10).replace(/-/g, "");
const maxSeq = store.reservations.reduce((max, item) => {
const match = /(\d{3,})$/.exec(item.id || "");
return Math.max(max, match ? Number(match[1]) : 0);
}, 0);
return `RSV-${today}-${String(maxSeq + 1).padStart(3, "0")}`;
}
function formatDateTime(value) {
const date = new Date(value);
if (Number.isNaN(date.getTime())) return value;
const yyyy = date.getFullYear();
const mm = String(date.getMonth() + 1).padStart(2, "0");
const dd = String(date.getDate()).padStart(2, "0");
const hh = String(date.getHours()).padStart(2, "0");
const mi = String(date.getMinutes()).padStart(2, "0");
return `${yyyy}-${mm}-${dd} ${hh}:${mi}`;
}
function detectScheduleStatus(action) {
const map = {
approve: "approved",
running: "running",
ended: "ended",
conflict: "conflict",
reject: "conflict",
};
return map[action] || "pending";
}
function detectReservationStatus(action) {
const map = {
approve: { status: "approved", fulfillment: "待启动" },
running: { status: "approved", fulfillment: "运行中" },
ended: { status: "approved", fulfillment: "已完成" },
conflict: { status: "pending", fulfillment: "跨机风险" },
reject: { status: "rejected", fulfillment: "资源不足" },
};
return map[action] || { status: "pending", fulfillment: "待启动" };
}
function ensureTaskForReservation(reservation) {
let task = store.tasks.find((item) => item.reservationId === reservation.id);
if (task) return task;
task = {
name: `job-${reservation.id.toLowerCase()}`,
project: reservation.project,
reservationId: reservation.id,
pool: reservation.pool,
gpu: reservation.gpu,
status: "待启动",
start: reservation.start.slice(11, 16),
};
store.tasks.unshift(task);
return task;
}
function recomputeReservedToday() {
const selectedDate = "2026-04-28";
const dayStart = new Date(`${selectedDate}T00:00:00`);
const dayEnd = new Date(`${selectedDate}T23:59:59`);
store.pools.forEach((pool) => {
pool.reservedToday = store.scheduleReservations
.filter((booking) => booking.pool === pool.id)
.filter((booking) => {
const start = new Date(booking.start);
const end = new Date(booking.end);
return start <= dayEnd && end >= dayStart;
})
.reduce((sum, booking) => sum + Number(booking.gpuCount || 0), 0);
});
}
function createReservation(body) {
const reservationId = nextReservationId();
const reservation = {
id: reservationId,
project: body.project,
applicant: body.applicant,
pool: body.poolId,
gpu: Number(body.gpuCount || 0),
start: formatDateTime(body.startAt),
end: formatDateTime(body.endAt),
status: "pending",
fulfillment: "待启动",
};
const pool = store.pools.find((item) => item.id === reservation.pool);
const fallbackStart = 1;
const booking = {
reservationId,
pool: reservation.pool,
start: body.startAt,
end: body.endAt,
gpuStart: fallbackStart,
gpuCount: Number(body.gpuCount || 0),
statusKey: "pending",
};
if (pool && booking.gpuCount > pool.totalGpu) {
booking.statusKey = "conflict";
reservation.fulfillment = "跨机风险";
}
store.reservations.unshift(reservation);
store.scheduleReservations.push(booking);
recomputeReservedToday();
saveState();
return {
reservationId,
snapshot: cloneData(store),
};
}
function createFormalApplication(body) {
const applyId = nextApplyId();
const reservation = {
id: applyId,
project: body.purpose || "未命名申请",
applicant: body.applicant || "zhang",
pool: body.poolCode,
gpu: Number(body.gpuCount || 0),
start: formatDateTime(body.startTime),
end: formatDateTime(body.endTime),
status: "pending",
fulfillment: "待启动",
remark: body.remark || "",
createdAt: formatDateTime(new Date()),
updatedAt: formatDateTime(new Date()),
};
store.reservations.unshift(reservation);
store.scheduleReservations.push({
reservationId: applyId,
pool: reservation.pool,
start: body.startTime,
end: body.endTime,
gpuStart: 1,
gpuCount: reservation.gpu,
statusKey: "pending",
});
recomputeReservedToday();
addFormalMessage("申请提交成功", `${applyId} 已提交,等待审批。`, "APPLICATION", applyId, [reservation.applicant]);
addFormalMessage("待审批提醒", `${applyId} 等待资源负责人审批。`, "APPROVAL", applyId, ["liu", "chen"]);
saveState();
return toFormalApplication(reservation);
}
function findReservationByApplyId(applyId) {
return store.reservations.find((item) => item.id === applyId);
}
function cancelFormalApplication(applyId) {
const reservation = findReservationByApplyId(applyId);
if (!reservation) throw new Error("Application not found");
if (reservation.status !== "pending") {
const error = new Error("当前状态不允许取消");
error.code = "APPLY_STATUS_INVALID";
throw error;
}
reservation.status = "cancelled";
reservation.updatedAt = formatDateTime(new Date());
addFormalMessage("申请已取消", `${applyId} 已取消并释放占用容量。`, "APPLICATION", applyId, [reservation.applicant]);
saveState();
return toFormalApplication(reservation);
}
function assertFormalApprovalCapacity(reservation) {
const pool = store.pools.find((item) => item.id === reservation.pool);
if (!pool) return;
const activeGpu = store.reservations
.filter((item) => item.id !== reservation.id)
.filter((item) => item.pool === reservation.pool)
.filter((item) => item.status === "approving" || item.status === "approved")
.reduce((sum, item) => sum + Number(item.gpu || 0), 0);
const availableGpu = Number(pool.totalGpu || 0) - activeGpu;
if (Number(reservation.gpu || 0) > availableGpu) {
const error = new Error("已无剩余容量");
error.code = "NO_REMAINING_CAPACITY";
error.statusCode = 409;
throw error;
}
}
function approveFormalApplication(applyId) {
const reservation = findReservationByApplyId(applyId);
if (!reservation) throw new Error("Application not found");
assertFormalApprovalCapacity(reservation);
if (reservation.status === "pending") {
reservation.status = "approving";
addFormalMessage("待审批提醒", `${applyId} 等待平台运维审批。`, "APPROVAL", applyId, ["ops001"]);
} else {
reservation.status = "approved";
reservation.fulfillment = "待启动";
addFormalMessage("申请审批通过", `${applyId} 已审批通过。`, "APPLICATION", applyId, [reservation.applicant]);
}
reservation.updatedAt = formatDateTime(new Date());
saveState();
return toFormalApplication(reservation);
}
function rejectFormalApplication(applyId) {
const reservation = findReservationByApplyId(applyId);
if (!reservation) throw new Error("Application not found");
reservation.status = "rejected";
reservation.fulfillment = "资源不足";
reservation.updatedAt = formatDateTime(new Date());
addFormalMessage("申请审批拒绝", `${applyId} 已被拒绝。`, "APPLICATION", applyId, [reservation.applicant]);
saveState();
return toFormalApplication(reservation);
}
function createFormalMigration(body) {
ensureFormalCollections();
const migrationNo = `MIG${new Date().toISOString().replace(/\D/g, "").slice(0, 14)}`;
const requestPayload = {
sourcePoolCode: body.sourcePoolCode,
targetPoolCode: body.targetPoolCode,
nodeList: body.nodeList || [],
remark: body.remark || "",
};
const responsePayload = {
externalResult: "SUCCESS",
message: "mock 外部平台迁移完成",
migratedNodes: requestPayload.nodeList,
completedAt: formatDateTime(new Date()),
};
const record = {
migrationNo,
sourcePoolCode: requestPayload.sourcePoolCode,
targetPoolCode: requestPayload.targetPoolCode,
nodeList: requestPayload.nodeList,
operator: body.operator || "ops001",
result: "SUCCESS",
requestPayload,
responsePayload,
riskSummary: body.riskSummary || "",
createdAt: formatDateTime(new Date()),
};
store.migrations.unshift(record);
store.nodes.forEach((node) => {
if (record.nodeList.includes(node.name) || record.nodeList.includes(node.id)) {
node.pool = record.targetPoolCode;
}
});
addFormalMessage("节点迁移完成", `${record.nodeList.join("、")} 已迁移。`, "MIGRATION", migrationNo, ["ops001"]);
saveState();
return record;
}
function updateReservationLifecycle(reservationId, action) {
const reservation = store.reservations.find((item) => item.id === reservationId);
if (!reservation) {
throw new Error("Reservation not found");
}
const next = detectReservationStatus(action);
reservation.status = next.status;
reservation.fulfillment = next.fulfillment;
const schedule = store.scheduleReservations.find((item) => item.reservationId === reservationId);
if (schedule) {
schedule.statusKey = detectScheduleStatus(action);
}
if (action === "running" || action === "ended" || action === "conflict") {
const task = ensureTaskForReservation(reservation);
task.pool = reservation.pool;
task.gpu = reservation.gpu;
task.status =
action === "running" ? "运行中" : action === "ended" ? "已完成" : "异常";
}
saveState();
return {
reservationId,
snapshot: cloneData(store),
};
}
function migrateNode(nodeId, targetPool) {
const node = store.nodes.find((item) => item.id === nodeId);
const pool = store.pools.find((item) => item.id === targetPool);
if (!node || !pool) {
throw new Error("Node or target pool not found");
}
node.pool = pool.id;
node.taints = pool.taint;
saveState();
return {
snapshot: cloneData(store),
};
}
async function handleApi(request, response, pathname) {
if (request.method === "OPTIONS") {
response.writeHead(204, {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET,POST,OPTIONS",
"Access-Control-Allow-Headers": "Content-Type",
});
response.end();
return;
}
if (request.method === "GET" && pathname === "/api/auth/me") {
sendOk(response, { username: "ops001", displayName: "平台运维", role: "OPS" });
return;
}
if (request.method === "GET" && pathname === "/api/bootstrap") {
sendOk(response, getFormalBootstrap());
return;
}
if (request.method === "GET" && pathname === "/api/monitor/usage") {
sendOk(response, { tasks: getFormalBootstrap().tasks, resourcePools: getFormalBootstrap().resourcePools });
return;
}
if (request.method === "GET" && pathname === "/api/monitor/reservation") {
sendOk(response, { applications: getFormalBootstrap().applications, resourcePools: getFormalBootstrap().resourcePools });
return;
}
if (request.method === "GET" && pathname === "/api/applications") {
sendOk(response, getFormalBootstrap().applications);
return;
}
if (request.method === "POST" && pathname === "/api/applications") {
const body = await parseBody(request);
sendOk(response, createFormalApplication(body));
return;
}
const formalApplicationMatch = pathname.match(/^\/api\/applications\/([^/]+)$/);
if (request.method === "GET" && formalApplicationMatch) {
const item = findReservationByApplyId(decodeURIComponent(formalApplicationMatch[1]));
sendOk(response, item ? toFormalApplication(item) : null);
return;
}
const formalCancelMatch = pathname.match(/^\/api\/applications\/([^/]+)\/cancel$/);
if (request.method === "POST" && formalCancelMatch) {
sendOk(response, cancelFormalApplication(decodeURIComponent(formalCancelMatch[1])));
return;
}
const formalChangeMatch = pathname.match(/^\/api\/applications\/([^/]+)\/change$/);
if (request.method === "POST" && formalChangeMatch) {
cancelFormalApplication(decodeURIComponent(formalChangeMatch[1]));
const body = await parseBody(request);
sendOk(response, createFormalApplication(body));
return;
}
if (request.method === "GET" && pathname === "/api/approvals/todos") {
sendOk(response, getFormalApprovalTodos());
return;
}
const formalApprovalDetailMatch = pathname.match(/^\/api\/approvals\/([^/]+)$/);
if (request.method === "GET" && formalApprovalDetailMatch) {
const item = findReservationByApplyId(decodeURIComponent(formalApprovalDetailMatch[1]));
sendOk(response, item ? toFormalApplication(item) : null);
return;
}
const formalApproveMatch = pathname.match(/^\/api\/approvals\/([^/]+)\/approve$/);
if (request.method === "POST" && formalApproveMatch) {
sendOk(response, approveFormalApplication(decodeURIComponent(formalApproveMatch[1])));
return;
}
const formalRejectMatch = pathname.match(/^\/api\/approvals\/([^/]+)\/reject$/);
if (request.method === "POST" && formalRejectMatch) {
sendOk(response, rejectFormalApplication(decodeURIComponent(formalRejectMatch[1])));
return;
}
if (request.method === "GET" && pathname === "/api/compliance") {
sendOk(response, getFormalCompliance());
return;
}
const formalComplianceMatch = pathname.match(/^\/api\/compliance\/([^/]+)$/);
if (request.method === "GET" && formalComplianceMatch) {
const applyId = decodeURIComponent(formalComplianceMatch[1]);
sendOk(response, getFormalCompliance().find((item) => item.applyId === applyId) || null);
return;
}
if (request.method === "GET" && pathname === "/api/anomalies") {
sendOk(response, getFormalCompliance().filter((item) => item.result !== "合规"));
return;
}
if (request.method === "GET" && pathname === "/api/messages") {
ensureFormalCollections();
sendOk(response, store.messages);
return;
}
if (request.method === "POST" && pathname === "/api/messages/read-all") {
ensureFormalCollections();
store.messages.forEach((message) => {
message.isRead = true;
});
saveState();
sendOk(response, { ok: true });
return;
}
const formalMessageReadMatch = pathname.match(/^\/api\/messages\/(\d+)\/read$/);
if (request.method === "POST" && formalMessageReadMatch) {
ensureFormalCollections();
const id = Number(formalMessageReadMatch[1]);
const message = store.messages.find((item) => Number(item.id) === id);
if (message) message.isRead = true;
saveState();
sendOk(response, { ok: true });
return;
}
if (request.method === "GET" && pathname === "/api/migrations") {
ensureFormalCollections();
sendOk(response, store.migrations);
return;
}
if (request.method === "POST" && pathname === "/api/migrations") {
const body = await parseBody(request);
sendOk(response, createFormalMigration(body));
return;
}
const formalMigrationMatch = pathname.match(/^\/api\/migrations\/([^/]+)$/);
if (request.method === "GET" && formalMigrationMatch) {
ensureFormalCollections();
const migrationNo = decodeURIComponent(formalMigrationMatch[1]);
sendOk(response, store.migrations.find((item) => item.migrationNo === migrationNo) || null);
return;
}
if (request.method === "GET" && pathname === "/api/admin/pools") {
ensureFormalCollections();
sendOk(response, getFormalBootstrap().resourcePools);
return;
}
const formalAdminPoolMatch = pathname.match(/^\/api\/admin\/pools\/([^/]+)$/);
if (request.method === "PUT" && formalAdminPoolMatch) {
const poolCode = decodeURIComponent(formalAdminPoolMatch[1]);
const body = await parseBody(request);
const pool = store.pools.find((item) => item.id === poolCode);
if (!pool) throw new Error("Pool not found");
pool.name = body.poolName ?? pool.name;
pool.status = body.status ?? pool.status;
pool.remark = body.remark ?? pool.remark;
saveState();
sendOk(response, toFormalPool(pool));
return;
}
if (request.method === "GET" && pathname === "/api/admin/nodes") {
ensureFormalCollections();
sendOk(response, getFormalBootstrap().nodes);
return;
}
const formalAdminNodeMatch = pathname.match(/^\/api\/admin\/nodes\/([^/]+)$/);
if (request.method === "PUT" && formalAdminNodeMatch) {
const nodeName = decodeURIComponent(formalAdminNodeMatch[1]);
const body = await parseBody(request);
const node = store.nodes.find((item) => item.name === nodeName || item.id === nodeName);
if (!node) throw new Error("Node not found");
node.status = body.status ?? node.status;
node.remark = body.remark ?? node.remark;
saveState();
sendOk(response, toFormalNode(node));
return;
}
if (request.method === "GET" && pathname === "/api/admin/configs") {
ensureFormalCollections();
sendOk(response, store.adminConfigs);
return;
}
const formalAdminConfigMatch = pathname.match(/^\/api\/admin\/configs\/([^/]+)$/);
if (request.method === "PUT" && formalAdminConfigMatch) {
ensureFormalCollections();
const key = decodeURIComponent(formalAdminConfigMatch[1]);
const body = await parseBody(request);
const index = store.adminConfigs.findIndex((item) => item.key === key);
const item = { key, value: String(body.value ?? ""), description: body.description ?? "" };
if (index >= 0) store.adminConfigs[index] = item;
else store.adminConfigs.push(item);
saveState();
sendOk(response, item);
return;
}
if (request.method === "GET" && pathname === "/api/admin/users") {
ensureFormalCollections();
sendOk(response, store.adminUsers);
return;
}
if (request.method === "POST" && pathname === "/api/admin/users") {
ensureFormalCollections();
const body = await parseBody(request);
const maxId = store.adminUsers.reduce((max, item) => Math.max(max, Number(item.id || 0)), 0);
const user = { id: maxId + 1, ...body };
store.adminUsers.unshift(user);
saveState();
sendOk(response, user);
return;
}
const formalAdminUserMatch = pathname.match(/^\/api\/admin\/users\/(\d+)$/);
if (request.method === "PUT" && formalAdminUserMatch) {
ensureFormalCollections();
const id = Number(formalAdminUserMatch[1]);
const body = await parseBody(request);
const index = store.adminUsers.findIndex((item) => Number(item.id) === id);
if (index < 0) throw new Error("User not found");
store.adminUsers[index] = { ...store.adminUsers[index], ...body, id };
saveState();
sendOk(response, store.adminUsers[index]);
return;
}
const formalAdminResetMatch = pathname.match(/^\/api\/admin\/users\/(\d+)\/reset-password$/);
if (request.method === "POST" && formalAdminResetMatch) {
ensureFormalCollections();
sendOk(response, { ok: true, password: "Reset@123" });
return;
}
const formalAdminFlowMatch = pathname.match(/^\/api\/admin\/approval-flows\/([^/]+)$/);
if (request.method === "GET" && formalAdminFlowMatch) {
ensureFormalCollections();
const poolCode = decodeURIComponent(formalAdminFlowMatch[1]);
sendOk(response, store.approvalFlows[poolCode] || null);
return;
}
if (request.method === "PUT" && formalAdminFlowMatch) {
ensureFormalCollections();
const poolCode = decodeURIComponent(formalAdminFlowMatch[1]);
const body = await parseBody(request);
store.approvalFlows[poolCode] = { ...body, poolCode };
saveState();
sendOk(response, store.approvalFlows[poolCode]);
return;
}
if (request.method === "GET" && pathname === `${apiBase}/bootstrap`) {
sendJson(response, 200, getSnapshotEnvelope());
return;
}
if (request.method === "POST" && pathname === `${apiBase}/reservations`) {
const body = await parseBody(request);
sendJson(response, 200, createReservation(body));
return;
}
const lifecycleMatch = pathname.match(/^\/api\/compute-tide\/reservations\/([^/]+)\/lifecycle$/);
if (request.method === "POST" && lifecycleMatch) {
const reservationId = decodeURIComponent(lifecycleMatch[1]);
const body = await parseBody(request);
sendJson(response, 200, updateReservationLifecycle(reservationId, body.action));
return;
}
const migrateMatch = pathname.match(/^\/api\/compute-tide\/nodes\/([^/]+)\/migrate$/);
if (request.method === "POST" && migrateMatch) {
const nodeId = decodeURIComponent(migrateMatch[1]);
const body = await parseBody(request);
sendJson(response, 200, migrateNode(nodeId, body.targetPool));
return;
}
if (request.method === "POST" && pathname === `${apiBase}/reset`) {
sendJson(response, 200, { snapshot: cloneData(resetState()) });
return;
}
if (request.method === "GET" && pathname === "/health") {
sendJson(response, 200, {
ok: true,
mode: "local-mock",
apiBase,
reservationCount: store.reservations.length,
});
return;
}
sendJson(response, 404, {
message: `No route for ${request.method} ${pathname}`,
});
}
const server = http.createServer(async (request, response) => {
try {
const url = new URL(request.url, `http://${request.headers.host}`);
await handleApi(request, response, url.pathname);
} catch (error) {
sendJson(response, error.statusCode || 500, {
code: error.code || "INTERNAL_ERROR",
message: error.message || "Internal server error",
});
}
});
server.listen(port, host, () => {
const target = `http://${host}:${port}${apiBase}`;
console.log(`[mock-server] listening on http://${host}:${port}`);
console.log(`[mock-server] api base ${target}`);
console.log(`[mock-server] state file ${statePath}`);
});