@cfasim-ui/server 0.0.0-stage → 0.9.3
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/LICENSE +201 -0
- package/package.json +32 -3
- package/src/api.ts +110 -0
- package/src/index.ts +18 -0
- package/src/types.ts +85 -0
- package/src/useRun.ts +298 -0
- package/src/useServerModel.ts +160 -0
- package/src/vitePlugin.js +253 -0
- package/README.md +0 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "{}"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright {yyyy} {name of copyright owner}
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/package.json
CHANGED
|
@@ -1,6 +1,35 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cfasim-ui/server",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
3
|
+
"version": "0.9.3",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "Local task-server integration for cfasim-ui: run long jobs with streamed progress and saved runs",
|
|
6
|
+
"license": "Apache-2.0",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "https://github.com/CDCgov/cfa-simulator.git",
|
|
10
|
+
"directory": "cfasim-ui/server"
|
|
11
|
+
},
|
|
12
|
+
"publishConfig": {
|
|
13
|
+
"access": "public"
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"src",
|
|
17
|
+
"!src/*.test.ts",
|
|
18
|
+
"!src/testUtils.ts"
|
|
19
|
+
],
|
|
20
|
+
"exports": {
|
|
21
|
+
".": "./src/index.ts",
|
|
22
|
+
"./vite": "./src/vitePlugin.js"
|
|
23
|
+
},
|
|
24
|
+
"dependencies": {
|
|
25
|
+
"@cfasim-ui/shared": "0.9.3"
|
|
26
|
+
},
|
|
27
|
+
"peerDependencies": {
|
|
28
|
+
"vue": "^3.5.0"
|
|
29
|
+
},
|
|
30
|
+
"devDependencies": {
|
|
31
|
+
"@types/node": "26.1.1",
|
|
32
|
+
"vitest": "4.1.10",
|
|
33
|
+
"vue": "3.5.40"
|
|
34
|
+
}
|
|
6
35
|
}
|
package/src/api.ts
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import type { ModelOutput } from "@cfasim-ui/shared";
|
|
2
|
+
import { decodeModelOutputs } from "@cfasim-ui/shared";
|
|
3
|
+
import type { RunFile, RunSummary, TaskInfo } from "./types.js";
|
|
4
|
+
|
|
5
|
+
const DEFAULT_BASE_URL = "/api";
|
|
6
|
+
|
|
7
|
+
interface StartedRun {
|
|
8
|
+
run_id: string;
|
|
9
|
+
name: string | null;
|
|
10
|
+
inputs_hash: string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export class ServerError extends Error {
|
|
14
|
+
constructor(
|
|
15
|
+
message: string,
|
|
16
|
+
readonly status: number,
|
|
17
|
+
readonly url: string,
|
|
18
|
+
) {
|
|
19
|
+
super(message);
|
|
20
|
+
this.name = "ServerError";
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export const errorMessage = (e: unknown) =>
|
|
25
|
+
e instanceof Error ? e.message : String(e);
|
|
26
|
+
|
|
27
|
+
async function request(url: string, init?: RequestInit): Promise<Response> {
|
|
28
|
+
const res = await fetch(url, init);
|
|
29
|
+
if (!res.ok) {
|
|
30
|
+
let detail = `${res.status} ${res.statusText}`;
|
|
31
|
+
try {
|
|
32
|
+
const body = (await res.json()) as { error?: string };
|
|
33
|
+
if (body?.error) detail = body.error;
|
|
34
|
+
} catch {
|
|
35
|
+
// not JSON: keep the status line
|
|
36
|
+
}
|
|
37
|
+
throw new ServerError(detail, res.status, url);
|
|
38
|
+
}
|
|
39
|
+
return res;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function createApi(baseUrl: string = DEFAULT_BASE_URL) {
|
|
43
|
+
const base = baseUrl.replace(/\/$/, "");
|
|
44
|
+
const url = (path: string) => `${base}${path}`;
|
|
45
|
+
const runUrl = (runId: string, suffix = "") =>
|
|
46
|
+
url(`/runs/${encodeURIComponent(runId)}${suffix}`);
|
|
47
|
+
return {
|
|
48
|
+
baseUrl: base,
|
|
49
|
+
eventsUrl: (runId: string) => runUrl(runId, "/events"),
|
|
50
|
+
fileUrl: (runId: string, path: string) =>
|
|
51
|
+
runUrl(
|
|
52
|
+
runId,
|
|
53
|
+
`/files/${path.split("/").map(encodeURIComponent).join("/")}`,
|
|
54
|
+
),
|
|
55
|
+
async listTasks(): Promise<TaskInfo[]> {
|
|
56
|
+
const res = await request(url("/tasks"));
|
|
57
|
+
return ((await res.json()) as { tasks: TaskInfo[] }).tasks;
|
|
58
|
+
},
|
|
59
|
+
async listRuns(task?: string, limit?: number): Promise<RunSummary[]> {
|
|
60
|
+
const params = new URLSearchParams();
|
|
61
|
+
if (task) params.set("task", task);
|
|
62
|
+
if (limit !== undefined) params.set("limit", String(limit));
|
|
63
|
+
const query = params.toString();
|
|
64
|
+
const res = await request(url(`/runs${query ? `?${query}` : ""}`));
|
|
65
|
+
return ((await res.json()) as { runs: RunSummary[] }).runs;
|
|
66
|
+
},
|
|
67
|
+
async getRun(runId: string): Promise<RunSummary> {
|
|
68
|
+
const res = await request(runUrl(runId));
|
|
69
|
+
return (await res.json()) as RunSummary;
|
|
70
|
+
},
|
|
71
|
+
async startRun(
|
|
72
|
+
task: string,
|
|
73
|
+
inputs: Record<string, unknown>,
|
|
74
|
+
name?: string,
|
|
75
|
+
): Promise<StartedRun> {
|
|
76
|
+
const res = await request(url(`/tasks/${encodeURIComponent(task)}/run`), {
|
|
77
|
+
method: "POST",
|
|
78
|
+
headers: { "content-type": "application/json" },
|
|
79
|
+
body: JSON.stringify(name ? { inputs, name } : { inputs }),
|
|
80
|
+
});
|
|
81
|
+
return (await res.json()) as StartedRun;
|
|
82
|
+
},
|
|
83
|
+
async cancelRun(runId: string): Promise<void> {
|
|
84
|
+
await request(runUrl(runId, "/cancel"), {
|
|
85
|
+
method: "POST",
|
|
86
|
+
});
|
|
87
|
+
},
|
|
88
|
+
async fetchInputs(runId: string): Promise<Record<string, unknown>> {
|
|
89
|
+
const res = await request(runUrl(runId, "/inputs"));
|
|
90
|
+
return (await res.json()) as Record<string, unknown>;
|
|
91
|
+
},
|
|
92
|
+
async fetchLog(runId: string): Promise<string> {
|
|
93
|
+
const res = await request(runUrl(runId, "/log"));
|
|
94
|
+
return res.text();
|
|
95
|
+
},
|
|
96
|
+
async fetchFiles(runId: string): Promise<RunFile[]> {
|
|
97
|
+
const res = await request(runUrl(runId, "/files"));
|
|
98
|
+
return ((await res.json()) as { files: RunFile[] }).files;
|
|
99
|
+
},
|
|
100
|
+
async fetchOutputs(
|
|
101
|
+
runId: string,
|
|
102
|
+
signal?: AbortSignal,
|
|
103
|
+
): Promise<Record<string, ModelOutput>> {
|
|
104
|
+
const res = await request(runUrl(runId, "/outputs"), { signal });
|
|
105
|
+
return decodeModelOutputs(await res.arrayBuffer());
|
|
106
|
+
},
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export type ServerApi = ReturnType<typeof createApi>;
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export { useServerModel } from "./useServerModel.js";
|
|
2
|
+
export type { ServerModel } from "./useServerModel.js";
|
|
3
|
+
export { useRun } from "./useRun.js";
|
|
4
|
+
export { createApi, ServerError } from "./api.js";
|
|
5
|
+
export type { ServerApi } from "./api.js";
|
|
6
|
+
export type {
|
|
7
|
+
LogLine,
|
|
8
|
+
RunError,
|
|
9
|
+
RunFile,
|
|
10
|
+
RunHandle,
|
|
11
|
+
RunProgress,
|
|
12
|
+
RunStatus,
|
|
13
|
+
RunSummary,
|
|
14
|
+
ServerOptions,
|
|
15
|
+
TaskInfo,
|
|
16
|
+
TaskParam,
|
|
17
|
+
} from "./types.js";
|
|
18
|
+
export { TERMINAL_STATUSES } from "./types.js";
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import type { ModelOutput } from "@cfasim-ui/shared";
|
|
2
|
+
import type { ComputedRef, Ref } from "vue";
|
|
3
|
+
|
|
4
|
+
export type RunStatus = "queued" | "running" | "done" | "error" | "cancelled";
|
|
5
|
+
|
|
6
|
+
export const TERMINAL_STATUSES: ReadonlySet<RunStatus> = new Set([
|
|
7
|
+
"done",
|
|
8
|
+
"error",
|
|
9
|
+
"cancelled",
|
|
10
|
+
]);
|
|
11
|
+
|
|
12
|
+
export interface RunProgress {
|
|
13
|
+
fraction: number;
|
|
14
|
+
message: string | null;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface RunError {
|
|
18
|
+
message: string;
|
|
19
|
+
traceback: string | null;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** One run as listed by `GET /api/runs` (the run's `status.json`). */
|
|
23
|
+
export interface RunSummary {
|
|
24
|
+
run_id: string;
|
|
25
|
+
/** Optional label given when the run was started; also prefixes `run_id`. */
|
|
26
|
+
name: string | null;
|
|
27
|
+
task: string;
|
|
28
|
+
inputs_hash: string;
|
|
29
|
+
status: RunStatus;
|
|
30
|
+
created_at: string;
|
|
31
|
+
started_at: string | null;
|
|
32
|
+
finished_at: string | null;
|
|
33
|
+
progress: RunProgress | null;
|
|
34
|
+
outputs: { revision: number; partial: boolean; names: string[] } | null;
|
|
35
|
+
error: RunError | null;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface TaskParam {
|
|
39
|
+
name: string;
|
|
40
|
+
required: boolean;
|
|
41
|
+
default: unknown;
|
|
42
|
+
annotation: string | null;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface TaskInfo {
|
|
46
|
+
name: string;
|
|
47
|
+
doc: string | null;
|
|
48
|
+
params: TaskParam[];
|
|
49
|
+
accepts_extra: boolean;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** A file the task wrote into its run directory. */
|
|
53
|
+
export interface RunFile {
|
|
54
|
+
path: string;
|
|
55
|
+
size: number;
|
|
56
|
+
modified: string;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export interface LogLine {
|
|
60
|
+
stream: "stdout" | "stderr" | "task";
|
|
61
|
+
line: string;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export interface ServerOptions {
|
|
65
|
+
/** Prefix of the server's REST routes (default `"/api"`, the Vite proxy path). */
|
|
66
|
+
baseUrl?: string;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export interface RunHandle {
|
|
70
|
+
id: Readonly<Ref<string | undefined>>;
|
|
71
|
+
status: Ref<RunStatus | undefined>;
|
|
72
|
+
progress: Ref<RunProgress | undefined>;
|
|
73
|
+
log: Ref<LogLine[]>;
|
|
74
|
+
outputs: Ref<Record<string, ModelOutput> | undefined>;
|
|
75
|
+
/** Revision of `outputs`; increments every time the task emits. */
|
|
76
|
+
revision: Ref<number>;
|
|
77
|
+
inputs: Ref<Record<string, unknown> | undefined>;
|
|
78
|
+
files: Ref<RunFile[]>;
|
|
79
|
+
error: Ref<string | undefined>;
|
|
80
|
+
/** `true` while the run is queued or running. */
|
|
81
|
+
active: ComputedRef<boolean>;
|
|
82
|
+
/** URL of a file the task wrote, for download links; `""` with no run. */
|
|
83
|
+
fileUrl: (path: string) => string;
|
|
84
|
+
refreshFiles: () => Promise<void>;
|
|
85
|
+
}
|
package/src/useRun.ts
ADDED
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
import { computed, onScopeDispose, ref, shallowRef, toValue, watch } from "vue";
|
|
2
|
+
import type { MaybeRefOrGetter } from "vue";
|
|
3
|
+
import type { ModelOutput } from "@cfasim-ui/shared";
|
|
4
|
+
import { createApi, errorMessage } from "./api.js";
|
|
5
|
+
import type { ServerApi } from "./api.js";
|
|
6
|
+
import type {
|
|
7
|
+
LogLine,
|
|
8
|
+
RunFile,
|
|
9
|
+
RunHandle,
|
|
10
|
+
RunProgress,
|
|
11
|
+
RunStatus,
|
|
12
|
+
ServerOptions,
|
|
13
|
+
} from "./types.js";
|
|
14
|
+
import { TERMINAL_STATUSES } from "./types.js";
|
|
15
|
+
|
|
16
|
+
const MAX_LOG_LINES = 5000;
|
|
17
|
+
|
|
18
|
+
const CONNECTION_LOST = "Connection to the server lost, retrying";
|
|
19
|
+
|
|
20
|
+
// log.txt prefixes every non-stdout line with its stream, e.g. "[stderr] ".
|
|
21
|
+
function parseSavedLog(text: string): LogLine[] {
|
|
22
|
+
const lines = text.split("\n");
|
|
23
|
+
if (lines[lines.length - 1] === "") lines.pop();
|
|
24
|
+
return lines.map((line) => {
|
|
25
|
+
const m = /^\[(stderr|task)\] (.*)$/s.exec(line);
|
|
26
|
+
return m
|
|
27
|
+
? { stream: m[1] as LogLine["stream"], line: m[2] }
|
|
28
|
+
: { stream: "stdout", line };
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
interface LogEvent {
|
|
33
|
+
stream: LogLine["stream"];
|
|
34
|
+
line: string;
|
|
35
|
+
overwrite: boolean;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Follow one run: its status, progress, log, and outputs, live over
|
|
40
|
+
* Server-Sent Events. Pass a ref to switch runs; pass `undefined` to detach.
|
|
41
|
+
* Two handles on two run ids give side-by-side comparison.
|
|
42
|
+
*/
|
|
43
|
+
export function useRun(
|
|
44
|
+
runId: MaybeRefOrGetter<string | undefined>,
|
|
45
|
+
options: ServerOptions | { api: ServerApi } = {},
|
|
46
|
+
): RunHandle {
|
|
47
|
+
const api = "api" in options ? options.api : createApi(options.baseUrl);
|
|
48
|
+
|
|
49
|
+
const id = ref<string>();
|
|
50
|
+
const status = ref<RunStatus>();
|
|
51
|
+
const progress = ref<RunProgress>();
|
|
52
|
+
const log = ref<LogLine[]>([]);
|
|
53
|
+
const outputs = shallowRef<Record<string, ModelOutput>>();
|
|
54
|
+
const revision = ref(0);
|
|
55
|
+
const inputs = ref<Record<string, unknown>>();
|
|
56
|
+
const files = ref<RunFile[]>([]);
|
|
57
|
+
const error = ref<string>();
|
|
58
|
+
const active = computed(
|
|
59
|
+
() => status.value === "queued" || status.value === "running",
|
|
60
|
+
);
|
|
61
|
+
|
|
62
|
+
let source: EventSource | undefined;
|
|
63
|
+
// The in-flight `/outputs` fetch; at most one at a time.
|
|
64
|
+
let controller: AbortController | undefined;
|
|
65
|
+
// Highest outputs revision announced by the server.
|
|
66
|
+
let wantedRevision = 0;
|
|
67
|
+
let fetchScheduled = false;
|
|
68
|
+
let outputsError: string | undefined;
|
|
69
|
+
// The stream ended before `seed` knew the status (an old, finished run).
|
|
70
|
+
let streamEnded = false;
|
|
71
|
+
// Index into `log` of the last overwrite line per stream, so progress-bar
|
|
72
|
+
// updates replace rather than append.
|
|
73
|
+
let overwriteIndex: Partial<Record<LogLine["stream"], number>> = {};
|
|
74
|
+
|
|
75
|
+
function reset() {
|
|
76
|
+
status.value = undefined;
|
|
77
|
+
progress.value = undefined;
|
|
78
|
+
log.value = [];
|
|
79
|
+
outputs.value = undefined;
|
|
80
|
+
revision.value = 0;
|
|
81
|
+
inputs.value = undefined;
|
|
82
|
+
files.value = [];
|
|
83
|
+
error.value = undefined;
|
|
84
|
+
wantedRevision = 0;
|
|
85
|
+
fetchScheduled = false;
|
|
86
|
+
outputsError = undefined;
|
|
87
|
+
streamEnded = false;
|
|
88
|
+
overwriteIndex = {};
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function closeSource() {
|
|
92
|
+
source?.close();
|
|
93
|
+
source = undefined;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function teardown() {
|
|
97
|
+
closeSource();
|
|
98
|
+
controller?.abort();
|
|
99
|
+
controller = undefined;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function finish(next: RunStatus) {
|
|
103
|
+
status.value = next;
|
|
104
|
+
closeSource();
|
|
105
|
+
if (error.value === CONNECTION_LOST) error.value = undefined;
|
|
106
|
+
// Picks up a revision whose fetch failed or is still pending.
|
|
107
|
+
scheduleOutputs();
|
|
108
|
+
void refreshFiles();
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// Loads the saved log when the event stream had none to replay.
|
|
112
|
+
async function loadSavedLog() {
|
|
113
|
+
const current = id.value;
|
|
114
|
+
if (!current || log.value.length) return;
|
|
115
|
+
try {
|
|
116
|
+
const text = await api.fetchLog(current);
|
|
117
|
+
if (id.value !== current || log.value.length) return;
|
|
118
|
+
log.value = parseSavedLog(text).slice(-MAX_LOG_LINES);
|
|
119
|
+
} catch {
|
|
120
|
+
// no log file yet; nothing to show
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
async function refreshFiles() {
|
|
125
|
+
const current = id.value;
|
|
126
|
+
if (!current) return;
|
|
127
|
+
try {
|
|
128
|
+
const list = await api.fetchFiles(current);
|
|
129
|
+
if (id.value === current) files.value = list;
|
|
130
|
+
} catch {
|
|
131
|
+
// the run may be gone; keep the previous list
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function requestOutputs(nextRevision: number) {
|
|
136
|
+
if (nextRevision > wantedRevision) wantedRevision = nextRevision;
|
|
137
|
+
scheduleOutputs();
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function scheduleOutputs() {
|
|
141
|
+
if (fetchScheduled || controller || wantedRevision <= revision.value) {
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
fetchScheduled = true;
|
|
145
|
+
// Coalesce a burst of `outputs` events (history replay) into one fetch.
|
|
146
|
+
queueMicrotask(() => {
|
|
147
|
+
fetchScheduled = false;
|
|
148
|
+
const current = id.value;
|
|
149
|
+
const target = wantedRevision;
|
|
150
|
+
if (!current || controller || target <= revision.value) return;
|
|
151
|
+
const ctl = (controller = new AbortController());
|
|
152
|
+
api
|
|
153
|
+
.fetchOutputs(current, ctl.signal)
|
|
154
|
+
.then((decoded) => {
|
|
155
|
+
if (controller !== ctl) return;
|
|
156
|
+
outputs.value = decoded;
|
|
157
|
+
revision.value = target;
|
|
158
|
+
if (error.value === outputsError) error.value = undefined;
|
|
159
|
+
outputsError = undefined;
|
|
160
|
+
controller = undefined;
|
|
161
|
+
// Revisions that arrived meanwhile.
|
|
162
|
+
scheduleOutputs();
|
|
163
|
+
})
|
|
164
|
+
.catch((e: unknown) => {
|
|
165
|
+
if (controller !== ctl) return;
|
|
166
|
+
controller = undefined;
|
|
167
|
+
// The next `outputs` event, or the run finishing, retries.
|
|
168
|
+
outputsError = error.value = errorMessage(e);
|
|
169
|
+
});
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function appendLog(event: LogEvent) {
|
|
174
|
+
const lines = log.value;
|
|
175
|
+
const entry: LogLine = { stream: event.stream, line: event.line };
|
|
176
|
+
const prev = overwriteIndex[event.stream];
|
|
177
|
+
if (event.overwrite && prev !== undefined && lines[prev]) {
|
|
178
|
+
lines[prev] = entry;
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
lines.push(entry);
|
|
182
|
+
if (event.overwrite) {
|
|
183
|
+
overwriteIndex[event.stream] = lines.length - 1;
|
|
184
|
+
} else {
|
|
185
|
+
delete overwriteIndex[event.stream];
|
|
186
|
+
}
|
|
187
|
+
if (lines.length > MAX_LOG_LINES) {
|
|
188
|
+
lines.splice(0, lines.length - MAX_LOG_LINES);
|
|
189
|
+
overwriteIndex = {};
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function subscribe(runId: string) {
|
|
194
|
+
const es = new EventSource(api.eventsUrl(runId));
|
|
195
|
+
source = es;
|
|
196
|
+
const on = <T>(type: string, handler: (data: T) => void) => {
|
|
197
|
+
es.addEventListener(type, (e) => {
|
|
198
|
+
// The browser also dispatches its own connection "error" Event here,
|
|
199
|
+
// which carries no data; `onerror` below handles that one.
|
|
200
|
+
const data = (e as MessageEvent).data as unknown;
|
|
201
|
+
if (source !== es || typeof data !== "string") return;
|
|
202
|
+
handler(JSON.parse(data) as T);
|
|
203
|
+
});
|
|
204
|
+
};
|
|
205
|
+
on<{ status: RunStatus }>("status", (d) => {
|
|
206
|
+
status.value = d.status;
|
|
207
|
+
});
|
|
208
|
+
on<RunProgress>("progress", (d) => {
|
|
209
|
+
progress.value = { fraction: d.fraction, message: d.message ?? null };
|
|
210
|
+
});
|
|
211
|
+
on<LogEvent>("log", appendLog);
|
|
212
|
+
on<{ revision: number }>("outputs", (d) => requestOutputs(d.revision));
|
|
213
|
+
on("done", () => finish("done"));
|
|
214
|
+
on<{ message: string }>("error", (d) => {
|
|
215
|
+
error.value = d.message;
|
|
216
|
+
finish("error");
|
|
217
|
+
});
|
|
218
|
+
on("cancelled", () => finish("cancelled"));
|
|
219
|
+
es.onerror = () => {
|
|
220
|
+
if (source !== es) return;
|
|
221
|
+
// Until `seed` has told us the status, a closed stream may simply be a
|
|
222
|
+
// finished run from an earlier server session; `seed` closes those.
|
|
223
|
+
if (!status.value) {
|
|
224
|
+
streamEnded = true;
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
if (TERMINAL_STATUSES.has(status.value)) {
|
|
228
|
+
closeSource();
|
|
229
|
+
void loadSavedLog();
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
// The browser reconnects on its own; say so until the next event.
|
|
233
|
+
if (!error.value) error.value = CONNECTION_LOST;
|
|
234
|
+
};
|
|
235
|
+
es.onopen = () => {
|
|
236
|
+
if (source !== es) return;
|
|
237
|
+
streamEnded = false;
|
|
238
|
+
if (error.value === CONNECTION_LOST) error.value = undefined;
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
async function seed(runId: string) {
|
|
243
|
+
try {
|
|
244
|
+
const [summary, runInputs] = await Promise.all([
|
|
245
|
+
api.getRun(runId),
|
|
246
|
+
api.fetchInputs(runId),
|
|
247
|
+
]);
|
|
248
|
+
if (id.value !== runId) return;
|
|
249
|
+
// Events may have moved things along while we fetched.
|
|
250
|
+
if (!status.value) status.value = summary.status;
|
|
251
|
+
// A finished run's stream replays its history and then ends, which
|
|
252
|
+
// `onerror` handles; one that already ended had nothing to replay.
|
|
253
|
+
if (TERMINAL_STATUSES.has(status.value) && streamEnded) {
|
|
254
|
+
closeSource();
|
|
255
|
+
void loadSavedLog();
|
|
256
|
+
}
|
|
257
|
+
if (!progress.value && summary.progress)
|
|
258
|
+
progress.value = summary.progress;
|
|
259
|
+
inputs.value = runInputs;
|
|
260
|
+
if (summary.outputs) requestOutputs(summary.outputs.revision);
|
|
261
|
+
if (summary.error && !error.value) error.value = summary.error.message;
|
|
262
|
+
} catch (e: unknown) {
|
|
263
|
+
if (id.value !== runId) return;
|
|
264
|
+
error.value = errorMessage(e);
|
|
265
|
+
}
|
|
266
|
+
void refreshFiles();
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
watch(
|
|
270
|
+
() => toValue(runId),
|
|
271
|
+
(next) => {
|
|
272
|
+
teardown();
|
|
273
|
+
reset();
|
|
274
|
+
id.value = next;
|
|
275
|
+
if (!next) return;
|
|
276
|
+
subscribe(next);
|
|
277
|
+
void seed(next);
|
|
278
|
+
},
|
|
279
|
+
{ immediate: true },
|
|
280
|
+
);
|
|
281
|
+
|
|
282
|
+
onScopeDispose(teardown);
|
|
283
|
+
|
|
284
|
+
return {
|
|
285
|
+
id,
|
|
286
|
+
status,
|
|
287
|
+
progress,
|
|
288
|
+
log,
|
|
289
|
+
outputs,
|
|
290
|
+
revision,
|
|
291
|
+
inputs,
|
|
292
|
+
files,
|
|
293
|
+
error,
|
|
294
|
+
active,
|
|
295
|
+
fileUrl: (path: string) => (id.value ? api.fileUrl(id.value, path) : ""),
|
|
296
|
+
refreshFiles,
|
|
297
|
+
};
|
|
298
|
+
}
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import { onScopeDispose, ref, watch } from "vue";
|
|
2
|
+
import type { MaybeRefOrGetter, Ref } from "vue";
|
|
3
|
+
import { ServerError, createApi, errorMessage } from "./api.js";
|
|
4
|
+
import { useRun } from "./useRun.js";
|
|
5
|
+
import type {
|
|
6
|
+
RunHandle,
|
|
7
|
+
RunSummary,
|
|
8
|
+
ServerOptions,
|
|
9
|
+
TaskInfo,
|
|
10
|
+
} from "./types.js";
|
|
11
|
+
import { TERMINAL_STATUSES } from "./types.js";
|
|
12
|
+
|
|
13
|
+
const RECONNECT_INTERVAL_MS = 3000;
|
|
14
|
+
|
|
15
|
+
const UNREACHABLE = (baseUrl: string) =>
|
|
16
|
+
`Could not reach the cfasim server at ${baseUrl}. Is it running? (In dev, \`pnpm dev\` starts it through the Vite plugin.)`;
|
|
17
|
+
|
|
18
|
+
export interface ServerModel {
|
|
19
|
+
tasks: Ref<TaskInfo[]>;
|
|
20
|
+
runs: Ref<RunSummary[]>;
|
|
21
|
+
/**
|
|
22
|
+
* `false` while the server cannot be reached; it is retried every few
|
|
23
|
+
* seconds until it answers.
|
|
24
|
+
*/
|
|
25
|
+
connected: Ref<boolean>;
|
|
26
|
+
error: Ref<string | undefined>;
|
|
27
|
+
refreshTasks: () => Promise<void>;
|
|
28
|
+
refreshRuns: () => Promise<void>;
|
|
29
|
+
/**
|
|
30
|
+
* Start `task` with `inputs`; the new run becomes `current`. Resolves to
|
|
31
|
+
* its id, or `undefined` when the server refused it (`error` says why). A
|
|
32
|
+
* `name` labels the run and prefixes its id and folder.
|
|
33
|
+
*/
|
|
34
|
+
start: (
|
|
35
|
+
task: string,
|
|
36
|
+
inputs: Record<string, unknown>,
|
|
37
|
+
options?: { name?: string },
|
|
38
|
+
) => Promise<string | undefined>;
|
|
39
|
+
cancel: (runId?: string) => Promise<void>;
|
|
40
|
+
/** Make an existing run `current` (its events replay from the server). */
|
|
41
|
+
load: (runId: string | undefined) => void;
|
|
42
|
+
current: RunHandle;
|
|
43
|
+
/** Follow any other run, e.g. to compare two side by side. */
|
|
44
|
+
useRun: (runId: MaybeRefOrGetter<string | undefined>) => RunHandle;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Talk to a cfasim task server: list its tasks and saved runs, start and
|
|
49
|
+
* cancel runs, and follow the current one.
|
|
50
|
+
*/
|
|
51
|
+
export function useServerModel(options: ServerOptions = {}): ServerModel {
|
|
52
|
+
const api = createApi(options.baseUrl);
|
|
53
|
+
const tasks = ref<TaskInfo[]>([]);
|
|
54
|
+
const runs = ref<RunSummary[]>([]);
|
|
55
|
+
const connected = ref(true);
|
|
56
|
+
const error = ref<string>();
|
|
57
|
+
const currentId = ref<string>();
|
|
58
|
+
const current = useRun(currentId, { api });
|
|
59
|
+
|
|
60
|
+
let reconnectTimer: ReturnType<typeof setTimeout> | undefined;
|
|
61
|
+
let runsRequest = 0;
|
|
62
|
+
|
|
63
|
+
// A network error, or the dev proxy's 502/504 when nothing listens behind it.
|
|
64
|
+
const unreachable = (e: unknown) =>
|
|
65
|
+
e instanceof TypeError ||
|
|
66
|
+
(e instanceof ServerError && (e.status === 502 || e.status === 504));
|
|
67
|
+
|
|
68
|
+
function fail(e: unknown) {
|
|
69
|
+
if (unreachable(e)) {
|
|
70
|
+
connected.value = false;
|
|
71
|
+
error.value = UNREACHABLE(api.baseUrl);
|
|
72
|
+
reconnectTimer ??= setTimeout(() => {
|
|
73
|
+
reconnectTimer = undefined;
|
|
74
|
+
void refreshTasks().then(() => {
|
|
75
|
+
if (connected.value) void refreshRuns();
|
|
76
|
+
});
|
|
77
|
+
}, RECONNECT_INTERVAL_MS);
|
|
78
|
+
} else {
|
|
79
|
+
error.value = errorMessage(e);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async function load<T>(fetchIt: () => Promise<T>, apply: (value: T) => void) {
|
|
84
|
+
try {
|
|
85
|
+
const value = await fetchIt();
|
|
86
|
+
apply(value);
|
|
87
|
+
if (!connected.value) {
|
|
88
|
+
connected.value = true;
|
|
89
|
+
if (error.value === UNREACHABLE(api.baseUrl)) error.value = undefined;
|
|
90
|
+
}
|
|
91
|
+
} catch (e) {
|
|
92
|
+
fail(e);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const refreshTasks = () =>
|
|
97
|
+
load(api.listTasks, (value) => {
|
|
98
|
+
tasks.value = value;
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
function refreshRuns() {
|
|
102
|
+
// Responses can arrive out of order; only the newest request applies.
|
|
103
|
+
const request = ++runsRequest;
|
|
104
|
+
return load(api.listRuns, (value) => {
|
|
105
|
+
if (request === runsRequest) runs.value = value;
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
async function start(
|
|
110
|
+
task: string,
|
|
111
|
+
inputs: Record<string, unknown>,
|
|
112
|
+
options: { name?: string } = {},
|
|
113
|
+
) {
|
|
114
|
+
error.value = undefined;
|
|
115
|
+
const name = options.name?.trim() || undefined;
|
|
116
|
+
try {
|
|
117
|
+
const { run_id } = await api.startRun(task, inputs, name);
|
|
118
|
+
currentId.value = run_id;
|
|
119
|
+
void refreshRuns();
|
|
120
|
+
return run_id;
|
|
121
|
+
} catch (e) {
|
|
122
|
+
fail(e);
|
|
123
|
+
return undefined;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async function cancel(runId: string | undefined = currentId.value) {
|
|
128
|
+
if (!runId) return;
|
|
129
|
+
try {
|
|
130
|
+
await api.cancelRun(runId);
|
|
131
|
+
} catch (e) {
|
|
132
|
+
fail(e);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
watch(current.status, (next) => {
|
|
137
|
+
if (next && TERMINAL_STATUSES.has(next)) void refreshRuns();
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
onScopeDispose(() => clearTimeout(reconnectTimer));
|
|
141
|
+
|
|
142
|
+
void refreshTasks();
|
|
143
|
+
void refreshRuns();
|
|
144
|
+
|
|
145
|
+
return {
|
|
146
|
+
tasks,
|
|
147
|
+
runs,
|
|
148
|
+
connected,
|
|
149
|
+
error,
|
|
150
|
+
refreshTasks,
|
|
151
|
+
refreshRuns,
|
|
152
|
+
start,
|
|
153
|
+
cancel,
|
|
154
|
+
load: (runId) => {
|
|
155
|
+
currentId.value = runId;
|
|
156
|
+
},
|
|
157
|
+
current,
|
|
158
|
+
useRun: (runId) => useRun(runId, { api }),
|
|
159
|
+
};
|
|
160
|
+
}
|
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { readFileSync } from "node:fs";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* @typedef {object} CfasimServerOptions
|
|
6
|
+
* @property {string} [bin] The `cfasim` executable to run (default: `$CFASIM_BIN`, else `cfasim` on PATH, falling back to `uvx cfasim@<this package's version>`)
|
|
7
|
+
* @property {string} [tasks] Passed as `--tasks`: a Python module or `.py` file, or the name of the Rust tasks binary (default: `cfasim serve` detects it from the project)
|
|
8
|
+
* @property {string[]} [command] Full command to start the server; overrides every other option that shapes it, and does not get `--app-url` (default: `cfasim serve --port <port> --output <output> --app-url <dev server url>`)
|
|
9
|
+
* @property {number} [port] Port the server listens on (default: 8765)
|
|
10
|
+
* @property {string} [output] Directory that holds one folder per run, passed as `--output` (default: "output")
|
|
11
|
+
* @property {boolean} [csv] Also write `<table>.csv` for each output table when a run finishes (passes `--csv`)
|
|
12
|
+
* @property {boolean} [debug] Build a Rust tasks binary without `--release` (passes `--debug`)
|
|
13
|
+
* @property {string} [cwd] Directory to start the server in (default: `process.cwd()`, the project root where `pyproject.toml` or `Cargo.toml` lives)
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
const DEFAULT_PORT = 8765;
|
|
17
|
+
const SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
|
|
18
|
+
const STOP_TIMEOUT_MS = 5000;
|
|
19
|
+
|
|
20
|
+
/** @type {Record<symbol, Map<number, Promise<void>> | undefined>} */
|
|
21
|
+
const globals = /** @type {any} */ (globalThis);
|
|
22
|
+
/**
|
|
23
|
+
* Servers still shutting down, by port. A Vite restart builds a new plugin
|
|
24
|
+
* instance whose server must wait for the old one to free the port; the map
|
|
25
|
+
* lives on globalThis so a re-bundled copy of this module shares it.
|
|
26
|
+
*/
|
|
27
|
+
const stopping = (globals[Symbol.for("cfasim-server.stopping")] ??= new Map());
|
|
28
|
+
|
|
29
|
+
/** @param {import("node:child_process").ChildProcess} proc */
|
|
30
|
+
const exited = (proc) => proc.exitCode !== null || proc.signalCode !== null;
|
|
31
|
+
|
|
32
|
+
/** This package's version, which is also the matching `cfasim` CLI version. */
|
|
33
|
+
function packageVersion() {
|
|
34
|
+
try {
|
|
35
|
+
const pkg = JSON.parse(
|
|
36
|
+
readFileSync(new URL("../package.json", import.meta.url), "utf8"),
|
|
37
|
+
);
|
|
38
|
+
return typeof pkg.version === "string" ? pkg.version : undefined;
|
|
39
|
+
} catch {
|
|
40
|
+
return undefined;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Signal a child's whole process group (a detached child leads one); falls
|
|
46
|
+
* back to the child alone where groups are unavailable.
|
|
47
|
+
* @param {number} pid
|
|
48
|
+
* @param {NodeJS.Signals} signal
|
|
49
|
+
*/
|
|
50
|
+
function signalGroup(pid, signal) {
|
|
51
|
+
try {
|
|
52
|
+
process.kill(-pid, signal);
|
|
53
|
+
} catch {
|
|
54
|
+
try {
|
|
55
|
+
process.kill(pid, signal);
|
|
56
|
+
} catch {
|
|
57
|
+
// already gone
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* The `serve` arguments shared by every launcher.
|
|
64
|
+
* @param {CfasimServerOptions} options
|
|
65
|
+
* @param {string} [appUrl]
|
|
66
|
+
* @returns {string[]}
|
|
67
|
+
*/
|
|
68
|
+
function serveArgs(options, appUrl) {
|
|
69
|
+
const args = [
|
|
70
|
+
"serve",
|
|
71
|
+
"--port",
|
|
72
|
+
String(options.port ?? DEFAULT_PORT),
|
|
73
|
+
"--output",
|
|
74
|
+
options.output ?? "output",
|
|
75
|
+
];
|
|
76
|
+
if (options.csv) args.push("--csv");
|
|
77
|
+
if (options.debug) args.push("--debug");
|
|
78
|
+
if (options.tasks) args.push("--tasks", options.tasks);
|
|
79
|
+
if (appUrl) args.push("--app-url", appUrl);
|
|
80
|
+
return args;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Build the argv used to start the server.
|
|
85
|
+
* @param {CfasimServerOptions} [options]
|
|
86
|
+
* @param {string} [appUrl] Where the page is served; the server prints it once it is up
|
|
87
|
+
* @returns {string[]}
|
|
88
|
+
*/
|
|
89
|
+
export function serverCommand(options = {}, appUrl) {
|
|
90
|
+
if (options.command) return [...options.command];
|
|
91
|
+
const bin = options.bin ?? process.env.CFASIM_BIN ?? "cfasim";
|
|
92
|
+
return [bin, ...serveArgs(options, appUrl)];
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* The command to try when `cfasim` is not installed: the matching release
|
|
97
|
+
* through `uvx`, which caches it after the first run. `undefined` when the
|
|
98
|
+
* user chose the executable themselves.
|
|
99
|
+
* @param {CfasimServerOptions} [options]
|
|
100
|
+
* @param {string} [appUrl]
|
|
101
|
+
* @returns {string[] | undefined}
|
|
102
|
+
*/
|
|
103
|
+
export function fallbackCommand(options = {}, appUrl) {
|
|
104
|
+
if (options.command || options.bin || process.env.CFASIM_BIN)
|
|
105
|
+
return undefined;
|
|
106
|
+
const version = packageVersion();
|
|
107
|
+
const spec = version ? `cfasim@${version}` : "cfasim";
|
|
108
|
+
return ["uvx", spec, ...serveArgs(options, appUrl)];
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* The dev server's local URL, from the bound port (Vite may not get the port
|
|
113
|
+
* it asked for) and the resolved config.
|
|
114
|
+
* @param {import("vite").ViteDevServer} server
|
|
115
|
+
* @returns {string | undefined}
|
|
116
|
+
*/
|
|
117
|
+
function appUrl(server) {
|
|
118
|
+
const address = server.httpServer?.address();
|
|
119
|
+
if (!address || typeof address === "string") return undefined;
|
|
120
|
+
const protocol = server.config.server.https ? "https" : "http";
|
|
121
|
+
return `${protocol}://localhost:${address.port}${server.config.base}`;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Vite plugin that starts `cfasim serve` next to the dev server and proxies
|
|
126
|
+
* `/api` to it. It only runs for `vite dev`; a production build is a static
|
|
127
|
+
* site that you serve with `cfasim serve --static dist`.
|
|
128
|
+
*
|
|
129
|
+
* @param {CfasimServerOptions} [options]
|
|
130
|
+
* @returns {import("vite").Plugin}
|
|
131
|
+
*/
|
|
132
|
+
export function cfasimServer(options = {}) {
|
|
133
|
+
const port = options.port ?? DEFAULT_PORT;
|
|
134
|
+
const cwd = options.cwd ?? process.cwd();
|
|
135
|
+
|
|
136
|
+
return {
|
|
137
|
+
name: "cfasim-server",
|
|
138
|
+
apply: "serve",
|
|
139
|
+
config() {
|
|
140
|
+
return {
|
|
141
|
+
server: {
|
|
142
|
+
proxy: {
|
|
143
|
+
"/api": { target: `http://127.0.0.1:${port}` },
|
|
144
|
+
},
|
|
145
|
+
},
|
|
146
|
+
};
|
|
147
|
+
},
|
|
148
|
+
configureServer(server) {
|
|
149
|
+
const logger = server.config.logger;
|
|
150
|
+
let closing = false;
|
|
151
|
+
/** @type {import("node:child_process").ChildProcess | undefined} */
|
|
152
|
+
let child;
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* @param {string[]} command
|
|
156
|
+
* @param {string[] | undefined} fallback Tried when `command[0]` is not installed
|
|
157
|
+
*/
|
|
158
|
+
const launch = (command, fallback) => {
|
|
159
|
+
logger.info(`[cfasim-server] starting: ${command.join(" ")}`);
|
|
160
|
+
// Own process group, so stopping signals a launcher (uvx) and the
|
|
161
|
+
// server it started together.
|
|
162
|
+
child = spawn(command[0], command.slice(1), {
|
|
163
|
+
cwd,
|
|
164
|
+
stdio: "inherit",
|
|
165
|
+
detached: true,
|
|
166
|
+
});
|
|
167
|
+
child.on("error", (err) => {
|
|
168
|
+
if (
|
|
169
|
+
fallback &&
|
|
170
|
+
!closing &&
|
|
171
|
+
/** @type {NodeJS.ErrnoException} */ (err).code === "ENOENT"
|
|
172
|
+
) {
|
|
173
|
+
logger.warn(
|
|
174
|
+
`[cfasim-server] ${command[0]} is not installed; trying ${fallback.slice(0, 2).join(" ")}`,
|
|
175
|
+
);
|
|
176
|
+
launch(fallback, undefined);
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
logger.error(
|
|
180
|
+
`[cfasim-server] failed to start (${err.message}). Install the cfasim CLI (\`cargo install cfasim\` or \`uv tool install cfasim\`) or set CFASIM_BIN to its path.`,
|
|
181
|
+
);
|
|
182
|
+
});
|
|
183
|
+
child.on("exit", (code, signal) => {
|
|
184
|
+
if (closing || code === 0 || code === null) return;
|
|
185
|
+
logger.error(
|
|
186
|
+
`[cfasim-server] exited with code ${code}${signal ? ` (${signal})` : ""}. If port ${port} is in use, stop the other server or set a different \`port\`.`,
|
|
187
|
+
);
|
|
188
|
+
});
|
|
189
|
+
};
|
|
190
|
+
|
|
191
|
+
// Start once Vite has its port, so the server can tell the user which
|
|
192
|
+
// URL to open (the API port is the one people open by mistake).
|
|
193
|
+
const start = () => {
|
|
194
|
+
if (closing) return;
|
|
195
|
+
const previous = stopping.get(port);
|
|
196
|
+
if (previous) {
|
|
197
|
+
// After a Vite restart, the old server may still hold the port.
|
|
198
|
+
void previous.then(start);
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
const url = appUrl(server);
|
|
202
|
+
const opts = { ...options, port };
|
|
203
|
+
launch(serverCommand(opts, url), fallbackCommand(opts, url));
|
|
204
|
+
};
|
|
205
|
+
const httpServer = server.httpServer;
|
|
206
|
+
if (httpServer && !httpServer.listening) {
|
|
207
|
+
httpServer.once("listening", start);
|
|
208
|
+
} else {
|
|
209
|
+
start();
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
const stop = () => {
|
|
213
|
+
if (closing) return;
|
|
214
|
+
closing = true;
|
|
215
|
+
for (const sig of SIGNALS) process.off(sig, onSignal);
|
|
216
|
+
process.off("exit", stop);
|
|
217
|
+
const proc = child;
|
|
218
|
+
const pid = proc?.pid;
|
|
219
|
+
if (!proc || exited(proc) || pid === undefined) return;
|
|
220
|
+
/** @type {Promise<void>} */
|
|
221
|
+
const done = new Promise((resolve) => {
|
|
222
|
+
proc.once("exit", () => resolve());
|
|
223
|
+
setTimeout(resolve, STOP_TIMEOUT_MS).unref();
|
|
224
|
+
});
|
|
225
|
+
stopping.set(port, done);
|
|
226
|
+
void done.then(() => {
|
|
227
|
+
if (stopping.get(port) === done) stopping.delete(port);
|
|
228
|
+
});
|
|
229
|
+
signalGroup(pid, "SIGTERM");
|
|
230
|
+
// The server stops its worker and exits on SIGTERM; this is the
|
|
231
|
+
// backstop for a launcher that ignores it.
|
|
232
|
+
const backstop = setTimeout(() => {
|
|
233
|
+
if (!exited(proc)) signalGroup(pid, "SIGKILL");
|
|
234
|
+
}, 3000);
|
|
235
|
+
backstop.unref();
|
|
236
|
+
};
|
|
237
|
+
// Vite's own SIGTERM handling exits without running "exit" listeners,
|
|
238
|
+
// so hook the signals too or the server outlives the dev server.
|
|
239
|
+
// Listening suppresses Node's default exit, so hand the signal back
|
|
240
|
+
// afterwards (signal-exit, which rolldown installs, only re-raises when
|
|
241
|
+
// it is the sole listener, so waiting for it would hang). SIGTERM is
|
|
242
|
+
// Vite's to finish: it closes the server and exits.
|
|
243
|
+
/** @param {NodeJS.Signals} sig */
|
|
244
|
+
const onSignal = (sig) => {
|
|
245
|
+
stop();
|
|
246
|
+
if (sig !== "SIGTERM") process.kill(process.pid, sig);
|
|
247
|
+
};
|
|
248
|
+
for (const sig of SIGNALS) process.once(sig, onSignal);
|
|
249
|
+
process.once("exit", stop);
|
|
250
|
+
httpServer?.once("close", stop);
|
|
251
|
+
},
|
|
252
|
+
};
|
|
253
|
+
}
|
package/README.md
DELETED