@rivetkit/engine-test-runner 2.0.21
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/.turbo/turbo-build.log +17 -0
- package/.turbo/turbo-check-types.log +4 -0
- package/Dockerfile +26 -0
- package/LICENSE +203 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +325 -0
- package/dist/index.js.map +1 -0
- package/package.json +27 -0
- package/src/index.ts +257 -0
- package/src/log.ts +194 -0
- package/tsconfig.json +11 -0
- package/tsup.config.ts +7 -0
- package/turbo.json +4 -0
- package/vitest.config.ts +16 -0
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
|
|
2
|
+
> @rivetkit/engine-test-runner@2.0.21 build /Users/nathan/rivet/engine/sdks/typescript/test-runner
|
|
3
|
+
> tsup src/index.ts
|
|
4
|
+
|
|
5
|
+
CLI Building entry: src/index.ts
|
|
6
|
+
CLI Using tsconfig: tsconfig.json
|
|
7
|
+
CLI tsup v8.5.0
|
|
8
|
+
CLI Using tsup config: /Users/nathan/rivet/engine/sdks/typescript/test-runner/tsup.config.ts
|
|
9
|
+
CLI Target: node16
|
|
10
|
+
CLI Cleaning output folder
|
|
11
|
+
ESM Build start
|
|
12
|
+
ESM dist/index.js 9.89 KB
|
|
13
|
+
ESM dist/index.js.map 19.40 KB
|
|
14
|
+
ESM ⚡️ Build success in 9ms
|
|
15
|
+
DTS Build start
|
|
16
|
+
DTS ⚡️ Build success in 720ms
|
|
17
|
+
DTS dist/index.d.ts 175.00 B
|
package/Dockerfile
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
FROM node:22-slim
|
|
2
|
+
|
|
3
|
+
WORKDIR /app
|
|
4
|
+
|
|
5
|
+
# Install pnpm (match workspace version) and set CI for non-interactive behavior
|
|
6
|
+
RUN corepack enable && corepack prepare pnpm@10.13.1 --activate
|
|
7
|
+
ENV CI=true
|
|
8
|
+
|
|
9
|
+
# Copy and build SDK
|
|
10
|
+
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml tsup.base.ts tsconfig.base.json turbo.json .
|
|
11
|
+
COPY sdks/typescript/runner-protocol ./sdks/typescript/runner-protocol/
|
|
12
|
+
COPY sdks/typescript/runner ./sdks/typescript/runner/
|
|
13
|
+
|
|
14
|
+
# Install dependencies
|
|
15
|
+
COPY sdks/typescript/test-runner/package.json ./sdks/typescript/test-runner/
|
|
16
|
+
RUN pnpm install --no-frozen-lockfile
|
|
17
|
+
|
|
18
|
+
# Build the application
|
|
19
|
+
COPY sdks/typescript/test-runner/ ./sdks/typescript/test-runner/
|
|
20
|
+
RUN pnpm build -F @rivetkit/engine-test-runner
|
|
21
|
+
|
|
22
|
+
# Expose the HTTP server port
|
|
23
|
+
EXPOSE 5050
|
|
24
|
+
|
|
25
|
+
# Run the application
|
|
26
|
+
CMD ["node", "sdks/typescript/test-runner/dist/index.js"]
|
package/LICENSE
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright 2023 Rivet Gaming, Inc.
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
203
|
+
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import { serve } from "@hono/node-server";
|
|
3
|
+
import { Runner } from "@rivetkit/engine-runner";
|
|
4
|
+
import { Hono } from "hono";
|
|
5
|
+
import { streamSSE } from "hono/streaming";
|
|
6
|
+
|
|
7
|
+
// src/log.ts
|
|
8
|
+
import {
|
|
9
|
+
pino,
|
|
10
|
+
stdTimeFunctions
|
|
11
|
+
} from "pino";
|
|
12
|
+
import { inspect } from "util";
|
|
13
|
+
var baseLogger;
|
|
14
|
+
var configuredLogLevel;
|
|
15
|
+
var loggerCache = /* @__PURE__ */ new Map();
|
|
16
|
+
function getPinoLevel(logLevel) {
|
|
17
|
+
if (logLevel) {
|
|
18
|
+
return logLevel;
|
|
19
|
+
}
|
|
20
|
+
if (configuredLogLevel) {
|
|
21
|
+
return configuredLogLevel;
|
|
22
|
+
}
|
|
23
|
+
return (process.env["LOG_LEVEL"] || "warn").toString().toLowerCase();
|
|
24
|
+
}
|
|
25
|
+
function getIncludeTarget() {
|
|
26
|
+
return process.env["LOG_TARGET"] === "1";
|
|
27
|
+
}
|
|
28
|
+
function customWrite(level, o) {
|
|
29
|
+
const entries = {};
|
|
30
|
+
if (process.env["LOG_TIMESTAMP"] === "1" && o.time) {
|
|
31
|
+
const date = typeof o.time === "number" ? new Date(o.time) : /* @__PURE__ */ new Date();
|
|
32
|
+
entries.ts = date;
|
|
33
|
+
}
|
|
34
|
+
entries.level = level.toUpperCase();
|
|
35
|
+
if (o.target) {
|
|
36
|
+
entries.target = o.target;
|
|
37
|
+
}
|
|
38
|
+
if (o.msg) {
|
|
39
|
+
entries.msg = o.msg;
|
|
40
|
+
}
|
|
41
|
+
for (const [key, value] of Object.entries(o)) {
|
|
42
|
+
if (key !== "time" && key !== "level" && key !== "target" && key !== "msg" && key !== "pid" && key !== "hostname") {
|
|
43
|
+
entries[key] = value;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
const output = inspect(entries, {
|
|
47
|
+
compact: true,
|
|
48
|
+
breakLength: Infinity,
|
|
49
|
+
colors: true
|
|
50
|
+
});
|
|
51
|
+
console.log(output);
|
|
52
|
+
}
|
|
53
|
+
async function configureDefaultLogger(logLevel) {
|
|
54
|
+
if (logLevel) {
|
|
55
|
+
configuredLogLevel = logLevel;
|
|
56
|
+
}
|
|
57
|
+
baseLogger = pino({
|
|
58
|
+
level: getPinoLevel(logLevel),
|
|
59
|
+
messageKey: "msg",
|
|
60
|
+
// Do not include pid/hostname in output
|
|
61
|
+
base: {},
|
|
62
|
+
// Keep a string level in the output
|
|
63
|
+
formatters: {
|
|
64
|
+
level(_label, number) {
|
|
65
|
+
return { level: number };
|
|
66
|
+
}
|
|
67
|
+
},
|
|
68
|
+
timestamp: process.env["LOG_TIMESTAMP"] === "1" ? stdTimeFunctions.epochTime : false,
|
|
69
|
+
browser: {
|
|
70
|
+
write: {
|
|
71
|
+
fatal: customWrite.bind(null, "fatal"),
|
|
72
|
+
error: customWrite.bind(null, "error"),
|
|
73
|
+
warn: customWrite.bind(null, "warn"),
|
|
74
|
+
info: customWrite.bind(null, "info"),
|
|
75
|
+
debug: customWrite.bind(null, "debug"),
|
|
76
|
+
trace: customWrite.bind(null, "trace")
|
|
77
|
+
}
|
|
78
|
+
},
|
|
79
|
+
hooks: {
|
|
80
|
+
logMethod(inputArgs, _method, level) {
|
|
81
|
+
const levelMap = {
|
|
82
|
+
10: "trace",
|
|
83
|
+
20: "debug",
|
|
84
|
+
30: "info",
|
|
85
|
+
40: "warn",
|
|
86
|
+
50: "error",
|
|
87
|
+
60: "fatal"
|
|
88
|
+
};
|
|
89
|
+
const levelName = levelMap[level] || "info";
|
|
90
|
+
const time = process.env["LOG_TIMESTAMP"] === "1" ? Date.now() : void 0;
|
|
91
|
+
if (inputArgs.length >= 2) {
|
|
92
|
+
const [objOrMsg, msg] = inputArgs;
|
|
93
|
+
if (typeof objOrMsg === "object" && objOrMsg !== null) {
|
|
94
|
+
customWrite(levelName, { ...objOrMsg, msg, time });
|
|
95
|
+
} else {
|
|
96
|
+
customWrite(levelName, { msg: String(objOrMsg), time });
|
|
97
|
+
}
|
|
98
|
+
} else if (inputArgs.length === 1) {
|
|
99
|
+
const [objOrMsg] = inputArgs;
|
|
100
|
+
if (typeof objOrMsg === "object" && objOrMsg !== null) {
|
|
101
|
+
customWrite(levelName, { ...objOrMsg, time });
|
|
102
|
+
} else {
|
|
103
|
+
customWrite(levelName, { msg: String(objOrMsg), time });
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
});
|
|
109
|
+
loggerCache.clear();
|
|
110
|
+
}
|
|
111
|
+
function getBaseLogger() {
|
|
112
|
+
if (!baseLogger) {
|
|
113
|
+
configureDefaultLogger();
|
|
114
|
+
}
|
|
115
|
+
return baseLogger;
|
|
116
|
+
}
|
|
117
|
+
function getLogger(name = "default") {
|
|
118
|
+
const cached = loggerCache.get(name);
|
|
119
|
+
if (cached) {
|
|
120
|
+
return cached;
|
|
121
|
+
}
|
|
122
|
+
const base = getBaseLogger();
|
|
123
|
+
const child = getIncludeTarget() ? base.child({ target: name }) : base;
|
|
124
|
+
loggerCache.set(name, child);
|
|
125
|
+
return child;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// src/index.ts
|
|
129
|
+
var INTERNAL_SERVER_PORT = process.env.INTERNAL_SERVER_PORT ? Number(process.env.INTERNAL_SERVER_PORT) : 5051;
|
|
130
|
+
var RIVET_NAMESPACE = process.env.RIVET_NAMESPACE ?? "default";
|
|
131
|
+
var RIVET_RUNNER_NAME = process.env.RIVET_RUNNER_NAME ?? "test-runner";
|
|
132
|
+
var RIVET_RUNNER_KEY = process.env.RIVET_RUNNER_KEY ?? `key-${Math.floor(Math.random() * 1e4)}`;
|
|
133
|
+
var RIVET_RUNNER_VERSION = process.env.RIVET_RUNNER_VERSION ? Number(process.env.RIVET_RUNNER_VERSION) : 1;
|
|
134
|
+
var RIVET_RUNNER_TOTAL_SLOTS = process.env.RIVET_RUNNER_TOTAL_SLOTS ? Number(process.env.RIVET_RUNNER_TOTAL_SLOTS) : 100;
|
|
135
|
+
var RIVET_ENDPOINT = process.env.RIVET_ENDPOINT ?? "http://127.0.0.1:6420";
|
|
136
|
+
var RIVET_TOKEN = process.env.RIVET_TOKEN ?? "dev";
|
|
137
|
+
var AUTOSTART_SERVER = process.env.NO_AUTOSTART_SERVER === void 0;
|
|
138
|
+
var AUTOSTART_RUNNER = process.env.NO_AUTOSTART_RUNNER === void 0;
|
|
139
|
+
var runnerStarted = Promise.withResolvers();
|
|
140
|
+
var runnerStopped = Promise.withResolvers();
|
|
141
|
+
var runner = null;
|
|
142
|
+
var actorWebSockets = /* @__PURE__ */ new Map();
|
|
143
|
+
var app = new Hono();
|
|
144
|
+
function loggerMiddleware(logger) {
|
|
145
|
+
return async (c, next) => {
|
|
146
|
+
const method = c.req.method;
|
|
147
|
+
const path = c.req.path;
|
|
148
|
+
const startTime = Date.now();
|
|
149
|
+
await next();
|
|
150
|
+
const duration = Date.now() - startTime;
|
|
151
|
+
logger.debug({
|
|
152
|
+
msg: "http request",
|
|
153
|
+
method,
|
|
154
|
+
path,
|
|
155
|
+
status: c.res.status,
|
|
156
|
+
dt: `${duration}ms`,
|
|
157
|
+
reqSize: c.req.header("content-length"),
|
|
158
|
+
resSize: c.res.headers.get("content-length"),
|
|
159
|
+
userAgent: c.req.header("user-agent")
|
|
160
|
+
});
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
app.use("*", loggerMiddleware(getLogger()));
|
|
164
|
+
app.get("/wait-ready", async (c) => {
|
|
165
|
+
await runnerStarted.promise;
|
|
166
|
+
return c.json(runner == null ? void 0 : runner.runnerId);
|
|
167
|
+
});
|
|
168
|
+
app.get("/has-actor", async (c) => {
|
|
169
|
+
const actorIdQuery = c.req.query("actor");
|
|
170
|
+
const generationQuery = c.req.query("generation");
|
|
171
|
+
const generation = generationQuery ? Number(generationQuery) : void 0;
|
|
172
|
+
if (!actorIdQuery || !(runner == null ? void 0 : runner.hasActor(actorIdQuery, generation))) {
|
|
173
|
+
return c.text("", 404);
|
|
174
|
+
}
|
|
175
|
+
return c.text("ok");
|
|
176
|
+
});
|
|
177
|
+
app.get("/shutdown", async (c) => {
|
|
178
|
+
await (runner == null ? void 0 : runner.shutdown(true));
|
|
179
|
+
return c.text("ok");
|
|
180
|
+
});
|
|
181
|
+
app.get("/start", async (c) => {
|
|
182
|
+
return streamSSE(c, async (stream) => {
|
|
183
|
+
const [runner2, runnerStarted2, runnerStopped2] = await startRunner();
|
|
184
|
+
c.req.raw.signal.addEventListener("abort", () => {
|
|
185
|
+
getLogger().debug("SSE aborted, shutting down runner");
|
|
186
|
+
runner2.shutdown(true);
|
|
187
|
+
});
|
|
188
|
+
await runnerStarted2.promise;
|
|
189
|
+
stream.writeSSE({ data: runner2.getServerlessInitPacket() });
|
|
190
|
+
await runnerStopped2.promise;
|
|
191
|
+
});
|
|
192
|
+
});
|
|
193
|
+
await autoConfigureServerless();
|
|
194
|
+
if (AUTOSTART_SERVER) {
|
|
195
|
+
serve({
|
|
196
|
+
fetch: app.fetch,
|
|
197
|
+
port: INTERNAL_SERVER_PORT
|
|
198
|
+
});
|
|
199
|
+
getLogger().info(
|
|
200
|
+
`Internal HTTP server listening on port ${INTERNAL_SERVER_PORT}`
|
|
201
|
+
);
|
|
202
|
+
}
|
|
203
|
+
if (AUTOSTART_RUNNER)
|
|
204
|
+
[runner, runnerStarted, runnerStopped] = await startRunner();
|
|
205
|
+
async function autoConfigureServerless() {
|
|
206
|
+
const res = await fetch(
|
|
207
|
+
`http://127.0.0.1:6420/runner-configs/${RIVET_RUNNER_NAME}?namespace=${RIVET_NAMESPACE}`,
|
|
208
|
+
{
|
|
209
|
+
method: "PUT",
|
|
210
|
+
headers: {
|
|
211
|
+
Authorization: `Bearer ${RIVET_TOKEN}`,
|
|
212
|
+
"Content-Type": "application/json"
|
|
213
|
+
},
|
|
214
|
+
body: JSON.stringify({
|
|
215
|
+
datacenters: {
|
|
216
|
+
default: {
|
|
217
|
+
serverless: {
|
|
218
|
+
url: `http://localhost:${INTERNAL_SERVER_PORT}`,
|
|
219
|
+
max_runners: 10,
|
|
220
|
+
slots_per_runner: 1,
|
|
221
|
+
request_lifespan: 15
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
})
|
|
226
|
+
}
|
|
227
|
+
);
|
|
228
|
+
if (!res.ok) {
|
|
229
|
+
throw new Error(
|
|
230
|
+
`request failed: ${res.statusText} (${res.status}):
|
|
231
|
+
${await res.text()}`
|
|
232
|
+
);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
async function startRunner() {
|
|
236
|
+
getLogger().info("Starting runner");
|
|
237
|
+
const runnerStarted2 = Promise.withResolvers();
|
|
238
|
+
const runnerStopped2 = Promise.withResolvers();
|
|
239
|
+
const config = {
|
|
240
|
+
logger: getLogger(),
|
|
241
|
+
version: RIVET_RUNNER_VERSION,
|
|
242
|
+
endpoint: RIVET_ENDPOINT,
|
|
243
|
+
token: RIVET_TOKEN,
|
|
244
|
+
namespace: RIVET_NAMESPACE,
|
|
245
|
+
runnerName: RIVET_RUNNER_NAME,
|
|
246
|
+
runnerKey: RIVET_RUNNER_KEY,
|
|
247
|
+
totalSlots: RIVET_RUNNER_TOTAL_SLOTS,
|
|
248
|
+
prepopulateActorNames: {},
|
|
249
|
+
onConnected: () => {
|
|
250
|
+
runnerStarted2.resolve(void 0);
|
|
251
|
+
},
|
|
252
|
+
onDisconnected: () => {
|
|
253
|
+
},
|
|
254
|
+
onShutdown: () => {
|
|
255
|
+
runnerStopped2.resolve(void 0);
|
|
256
|
+
},
|
|
257
|
+
fetch: async (runner3, actorId, request) => {
|
|
258
|
+
getLogger().info(
|
|
259
|
+
`Fetch called for actor ${actorId}, URL: ${request.url}`
|
|
260
|
+
);
|
|
261
|
+
const url = new URL(request.url);
|
|
262
|
+
if (url.pathname === "/ping") {
|
|
263
|
+
const responseData = {
|
|
264
|
+
actorId,
|
|
265
|
+
status: "ok",
|
|
266
|
+
timestamp: Date.now()
|
|
267
|
+
};
|
|
268
|
+
return new Response(JSON.stringify(responseData), {
|
|
269
|
+
status: 200,
|
|
270
|
+
headers: { "Content-Type": "application/json" }
|
|
271
|
+
});
|
|
272
|
+
} else if (url.pathname === "/sleep") {
|
|
273
|
+
runner3.sleepActor(actorId);
|
|
274
|
+
return new Response("ok", {
|
|
275
|
+
status: 200,
|
|
276
|
+
headers: { "Content-Type": "application/json" }
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
return new Response("ok", { status: 200 });
|
|
280
|
+
},
|
|
281
|
+
onActorStart: async (_actorId, _generation, _config) => {
|
|
282
|
+
getLogger().info(
|
|
283
|
+
`Actor ${_actorId} started (generation ${_generation})`
|
|
284
|
+
);
|
|
285
|
+
},
|
|
286
|
+
onActorStop: async (_actorId, _generation) => {
|
|
287
|
+
getLogger().info(
|
|
288
|
+
`Actor ${_actorId} stopped (generation ${_generation})`
|
|
289
|
+
);
|
|
290
|
+
},
|
|
291
|
+
websocket: async (_runner, actorId, ws, request) => {
|
|
292
|
+
getLogger().info(`WebSocket connected for actor ${actorId}`);
|
|
293
|
+
actorWebSockets.set(actorId, ws);
|
|
294
|
+
ws.addEventListener("message", (event) => {
|
|
295
|
+
const data = event.data;
|
|
296
|
+
getLogger().info({
|
|
297
|
+
msg: `WebSocket message from actor ${actorId}`,
|
|
298
|
+
data
|
|
299
|
+
});
|
|
300
|
+
ws.send(`Echo: ${data}`);
|
|
301
|
+
});
|
|
302
|
+
ws.addEventListener("close", () => {
|
|
303
|
+
getLogger().info(`WebSocket closed for actor ${actorId}`);
|
|
304
|
+
actorWebSockets.delete(actorId);
|
|
305
|
+
});
|
|
306
|
+
ws.addEventListener("error", (error) => {
|
|
307
|
+
getLogger().error({
|
|
308
|
+
msg: `WebSocket error for actor ${actorId}:`,
|
|
309
|
+
error
|
|
310
|
+
});
|
|
311
|
+
});
|
|
312
|
+
}
|
|
313
|
+
};
|
|
314
|
+
const runner2 = new Runner(config);
|
|
315
|
+
await runner2.start();
|
|
316
|
+
getLogger().info("Waiting runner start...");
|
|
317
|
+
await runnerStarted2.promise;
|
|
318
|
+
getLogger().info("Runner started");
|
|
319
|
+
return [runner2, runnerStarted2, runnerStopped2];
|
|
320
|
+
}
|
|
321
|
+
var index_default = app;
|
|
322
|
+
export {
|
|
323
|
+
index_default as default
|
|
324
|
+
};
|
|
325
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/log.ts"],"sourcesContent":["import { serve } from \"@hono/node-server\";\nimport type { ActorConfig, RunnerConfig } from \"@rivetkit/engine-runner\";\nimport { Runner } from \"@rivetkit/engine-runner\";\nimport { Hono, type Context as HonoContext, type Next } from \"hono\";\nimport { streamSSE } from \"hono/streaming\";\nimport type { Logger } from \"pino\";\nimport type WebSocket from \"ws\";\nimport { getLogger } from \"./log\";\n\nconst INTERNAL_SERVER_PORT = process.env.INTERNAL_SERVER_PORT\n\t? Number(process.env.INTERNAL_SERVER_PORT)\n\t: 5051;\nconst RIVET_NAMESPACE = process.env.RIVET_NAMESPACE ?? \"default\";\nconst RIVET_RUNNER_NAME = process.env.RIVET_RUNNER_NAME ?? \"test-runner\";\nconst RIVET_RUNNER_KEY =\n\tprocess.env.RIVET_RUNNER_KEY ?? `key-${Math.floor(Math.random() * 10000)}`;\nconst RIVET_RUNNER_VERSION = process.env.RIVET_RUNNER_VERSION\n\t? Number(process.env.RIVET_RUNNER_VERSION)\n\t: 1;\nconst RIVET_RUNNER_TOTAL_SLOTS = process.env.RIVET_RUNNER_TOTAL_SLOTS\n\t? Number(process.env.RIVET_RUNNER_TOTAL_SLOTS)\n\t: 100;\nconst RIVET_ENDPOINT = process.env.RIVET_ENDPOINT ?? \"http://127.0.0.1:6420\";\nconst RIVET_TOKEN = process.env.RIVET_TOKEN ?? \"dev\";\nconst AUTOSTART_SERVER = process.env.NO_AUTOSTART_SERVER === undefined;\nconst AUTOSTART_RUNNER = process.env.NO_AUTOSTART_RUNNER === undefined;\n\nlet runnerStarted = Promise.withResolvers();\nlet runnerStopped = Promise.withResolvers();\nlet runner: Runner | null = null;\nconst actorWebSockets = new Map<string, WebSocket>();\n\n// Create internal server\nconst app = new Hono();\n\nfunction loggerMiddleware(logger: Logger) {\n\treturn async (c: HonoContext, next: Next) => {\n\t\tconst method = c.req.method;\n\t\tconst path = c.req.path;\n\t\tconst startTime = Date.now();\n\n\t\tawait next();\n\n\t\tconst duration = Date.now() - startTime;\n\t\tlogger.debug({\n\t\t\tmsg: \"http request\",\n\t\t\tmethod,\n\t\t\tpath,\n\t\t\tstatus: c.res.status,\n\t\t\tdt: `${duration}ms`,\n\t\t\treqSize: c.req.header(\"content-length\"),\n\t\t\tresSize: c.res.headers.get(\"content-length\"),\n\t\t\tuserAgent: c.req.header(\"user-agent\"),\n\t\t});\n\t};\n}\napp.use(\"*\", loggerMiddleware(getLogger()));\n\napp.get(\"/wait-ready\", async (c) => {\n\tawait runnerStarted.promise;\n\treturn c.json(runner?.runnerId);\n});\n\napp.get(\"/has-actor\", async (c) => {\n\tconst actorIdQuery = c.req.query(\"actor\");\n\tconst generationQuery = c.req.query(\"generation\");\n\tconst generation = generationQuery ? Number(generationQuery) : undefined;\n\n\tif (!actorIdQuery || !runner?.hasActor(actorIdQuery, generation)) {\n\t\treturn c.text(\"\", 404);\n\t}\n\treturn c.text(\"ok\");\n});\n\napp.get(\"/shutdown\", async (c) => {\n\tawait runner?.shutdown(true);\n\treturn c.text(\"ok\");\n});\n\napp.get(\"/start\", async (c) => {\n\treturn streamSSE(c, async (stream) => {\n\t\tconst [runner, runnerStarted, runnerStopped] = await startRunner();\n\n\t\tc.req.raw.signal.addEventListener(\"abort\", () => {\n\t\t\tgetLogger().debug(\"SSE aborted, shutting down runner\");\n\t\t\trunner.shutdown(true);\n\t\t});\n\n\t\tawait runnerStarted.promise;\n\n\t\tstream.writeSSE({ data: runner.getServerlessInitPacket()! });\n\n\t\tawait runnerStopped.promise;\n\t});\n});\n\nawait autoConfigureServerless();\n\nif (AUTOSTART_SERVER) {\n\tserve({\n\t\tfetch: app.fetch,\n\t\tport: INTERNAL_SERVER_PORT,\n\t});\n\tgetLogger().info(\n\t\t`Internal HTTP server listening on port ${INTERNAL_SERVER_PORT}`,\n\t);\n}\n\nif (AUTOSTART_RUNNER)\n\t[runner, runnerStarted, runnerStopped] = await startRunner();\n\nasync function autoConfigureServerless() {\n\tconst res = await fetch(\n\t\t`http://127.0.0.1:6420/runner-configs/${RIVET_RUNNER_NAME}?namespace=${RIVET_NAMESPACE}`,\n\t\t{\n\t\t\tmethod: \"PUT\",\n\t\t\theaders: {\n\t\t\t\tAuthorization: `Bearer ${RIVET_TOKEN}`,\n\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t},\n\t\t\tbody: JSON.stringify({\n\t\t\t\tdatacenters: {\n\t\t\t\t\tdefault: {\n\t\t\t\t\t\tserverless: {\n\t\t\t\t\t\t\turl: `http://localhost:${INTERNAL_SERVER_PORT}`,\n\t\t\t\t\t\t\tmax_runners: 10,\n\t\t\t\t\t\t\tslots_per_runner: 1,\n\t\t\t\t\t\t\trequest_lifespan: 15,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}),\n\t\t},\n\t);\n\n\tif (!res.ok) {\n\t\tthrow new Error(\n\t\t\t`request failed: ${res.statusText} (${res.status}):\\n${await res.text()}`,\n\t\t);\n\t}\n}\n\nasync function startRunner(): Promise<\n\t[Runner, PromiseWithResolvers<unknown>, PromiseWithResolvers<unknown>]\n> {\n\tgetLogger().info(\"Starting runner\");\n\n\tconst runnerStarted = Promise.withResolvers();\n\tconst runnerStopped = Promise.withResolvers();\n\n\tconst config: RunnerConfig = {\n\t\tlogger: getLogger(),\n\t\tversion: RIVET_RUNNER_VERSION,\n\t\tendpoint: RIVET_ENDPOINT,\n\t\ttoken: RIVET_TOKEN,\n\t\tnamespace: RIVET_NAMESPACE,\n\t\trunnerName: RIVET_RUNNER_NAME,\n\t\trunnerKey: RIVET_RUNNER_KEY,\n\t\ttotalSlots: RIVET_RUNNER_TOTAL_SLOTS,\n\t\tprepopulateActorNames: {},\n\t\tonConnected: () => {\n\t\t\trunnerStarted.resolve(undefined);\n\t\t},\n\t\tonDisconnected: () => {},\n\t\tonShutdown: () => {\n\t\t\trunnerStopped.resolve(undefined);\n\t\t},\n\t\tfetch: async (runner: Runner, actorId: string, request: Request) => {\n\t\t\tgetLogger().info(\n\t\t\t\t`Fetch called for actor ${actorId}, URL: ${request.url}`,\n\t\t\t);\n\t\t\tconst url = new URL(request.url);\n\t\t\tif (url.pathname === \"/ping\") {\n\t\t\t\t// Return the actor ID in response\n\t\t\t\tconst responseData = {\n\t\t\t\t\tactorId,\n\t\t\t\t\tstatus: \"ok\",\n\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t};\n\n\t\t\t\treturn new Response(JSON.stringify(responseData), {\n\t\t\t\t\tstatus: 200,\n\t\t\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\t\t});\n\t\t\t} else if (url.pathname === \"/sleep\") {\n\t\t\t\trunner.sleepActor(actorId);\n\n\t\t\t\treturn new Response(\"ok\", {\n\t\t\t\t\tstatus: 200,\n\t\t\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\t\t});\n\t\t\t}\n\n\t\t\treturn new Response(\"ok\", { status: 200 });\n\t\t},\n\t\tonActorStart: async (\n\t\t\t_actorId: string,\n\t\t\t_generation: number,\n\t\t\t_config: ActorConfig,\n\t\t) => {\n\t\t\tgetLogger().info(\n\t\t\t\t`Actor ${_actorId} started (generation ${_generation})`,\n\t\t\t);\n\t\t},\n\t\tonActorStop: async (_actorId: string, _generation: number) => {\n\t\t\tgetLogger().info(\n\t\t\t\t`Actor ${_actorId} stopped (generation ${_generation})`,\n\t\t\t);\n\t\t},\n\t\twebsocket: async (\n\t\t\t_runner: Runner,\n\t\t\tactorId: string,\n\t\t\tws: WebSocket,\n\t\t\trequest: Request,\n\t\t) => {\n\t\t\tgetLogger().info(`WebSocket connected for actor ${actorId}`);\n\t\t\tactorWebSockets.set(actorId, ws);\n\n\t\t\t// Echo server - send back any messages received\n\t\t\tws.addEventListener(\"message\", (event) => {\n\t\t\t\tconst data = event.data;\n\t\t\t\tgetLogger().info({\n\t\t\t\t\tmsg: `WebSocket message from actor ${actorId}`,\n\t\t\t\t\tdata,\n\t\t\t\t});\n\t\t\t\tws.send(`Echo: ${data}`);\n\t\t\t});\n\n\t\t\tws.addEventListener(\"close\", () => {\n\t\t\t\tgetLogger().info(`WebSocket closed for actor ${actorId}`);\n\t\t\t\tactorWebSockets.delete(actorId);\n\t\t\t});\n\n\t\t\tws.addEventListener(\"error\", (error) => {\n\t\t\t\tgetLogger().error({\n\t\t\t\t\tmsg: `WebSocket error for actor ${actorId}:`,\n\t\t\t\t\terror,\n\t\t\t\t});\n\t\t\t});\n\t\t},\n\t};\n\n\tconst runner = new Runner(config);\n\n\t// Start runner\n\tawait runner.start();\n\n\t// Wait for runner to be ready\n\tgetLogger().info(\"Waiting runner start...\");\n\tawait runnerStarted.promise;\n\n\tgetLogger().info(\"Runner started\");\n\n\treturn [runner, runnerStarted, runnerStopped];\n}\n\nexport default app;\n","import {\n\ttype Level,\n\ttype LevelWithSilent,\n\ttype Logger,\n\tpino,\n\tstdTimeFunctions,\n} from \"pino\";\nimport { inspect } from \"util\";\n\nexport type { Logger } from \"pino\";\n\nlet baseLogger: Logger | undefined;\nlet configuredLogLevel: Level | undefined;\n\n/** Cache of child loggers by logger name. */\nconst loggerCache = new Map<string, Logger>();\n\nexport function getPinoLevel(logLevel?: Level): LevelWithSilent {\n\t// Priority: provided > configured > env > default\n\tif (logLevel) {\n\t\treturn logLevel;\n\t}\n\n\tif (configuredLogLevel) {\n\t\treturn configuredLogLevel;\n\t}\n\n\treturn (process.env[\"LOG_LEVEL\"] || \"warn\")\n\t\t.toString()\n\t\t.toLowerCase() as LevelWithSilent;\n}\n\nexport function getIncludeTarget(): boolean {\n\treturn process.env[\"LOG_TARGET\"] === \"1\";\n}\n\n/**\n * Configure a custom base logger.\n */\nexport function configureBaseLogger(logger: Logger): void {\n\tbaseLogger = logger;\n\tloggerCache.clear();\n}\n\n// TODO: This can be simplified in logfmt.ts\nfunction customWrite(level: string, o: any) {\n\tconst entries: any = {};\n\n\t// Add timestamp if enabled\n\tif (process.env[\"LOG_TIMESTAMP\"] === \"1\" && o.time) {\n\t\tconst date = typeof o.time === \"number\" ? new Date(o.time) : new Date();\n\t\tentries.ts = date;\n\t}\n\n\t// Add level\n\tentries.level = level.toUpperCase();\n\n\t// Add target if present\n\tif (o.target) {\n\t\tentries.target = o.target;\n\t}\n\n\t// Add message\n\tif (o.msg) {\n\t\tentries.msg = o.msg;\n\t}\n\n\t// Add other properties\n\tfor (const [key, value] of Object.entries(o)) {\n\t\tif (\n\t\t\tkey !== \"time\" &&\n\t\t\tkey !== \"level\" &&\n\t\t\tkey !== \"target\" &&\n\t\t\tkey !== \"msg\" &&\n\t\t\tkey !== \"pid\" &&\n\t\t\tkey !== \"hostname\"\n\t\t) {\n\t\t\tentries[key] = value;\n\t\t}\n\t}\n\n\tconst output = inspect(entries, {\n\t\tcompact: true,\n\t\tbreakLength: Infinity,\n\t\tcolors: true,\n\t});\n\tconsole.log(output);\n}\n\n/**\n * Configure the default logger with optional log level.\n */\nexport async function configureDefaultLogger(logLevel?: Level): Promise<void> {\n\t// Store the configured log level\n\tif (logLevel) {\n\t\tconfiguredLogLevel = logLevel;\n\t}\n\n\tbaseLogger = pino({\n\t\tlevel: getPinoLevel(logLevel),\n\t\tmessageKey: \"msg\",\n\t\t// Do not include pid/hostname in output\n\t\tbase: {},\n\t\t// Keep a string level in the output\n\t\tformatters: {\n\t\t\tlevel(_label: string, number: number) {\n\t\t\t\treturn { level: number };\n\t\t\t},\n\t\t},\n\t\ttimestamp:\n\t\t\tprocess.env[\"LOG_TIMESTAMP\"] === \"1\"\n\t\t\t\t? stdTimeFunctions.epochTime\n\t\t\t\t: false,\n\t\tbrowser: {\n\t\t\twrite: {\n\t\t\t\tfatal: customWrite.bind(null, \"fatal\"),\n\t\t\t\terror: customWrite.bind(null, \"error\"),\n\t\t\t\twarn: customWrite.bind(null, \"warn\"),\n\t\t\t\tinfo: customWrite.bind(null, \"info\"),\n\t\t\t\tdebug: customWrite.bind(null, \"debug\"),\n\t\t\t\ttrace: customWrite.bind(null, \"trace\"),\n\t\t\t},\n\t\t},\n\t\thooks: {\n\t\t\tlogMethod(inputArgs, _method, level) {\n\t\t\t\t// TODO: This is a hack to not implement our own transport target. We can get better perf if we have our own transport target.\n\n\t\t\t\tconst levelMap: Record<number, string> = {\n\t\t\t\t\t10: \"trace\",\n\t\t\t\t\t20: \"debug\",\n\t\t\t\t\t30: \"info\",\n\t\t\t\t\t40: \"warn\",\n\t\t\t\t\t50: \"error\",\n\t\t\t\t\t60: \"fatal\",\n\t\t\t\t};\n\t\t\t\tconst levelName = levelMap[level] || \"info\";\n\t\t\t\tconst time =\n\t\t\t\t\tprocess.env[\"LOG_TIMESTAMP\"] === \"1\"\n\t\t\t\t\t\t? Date.now()\n\t\t\t\t\t\t: undefined;\n\t\t\t\t// TODO: This can be simplified in logfmt.ts\n\t\t\t\tif (inputArgs.length >= 2) {\n\t\t\t\t\tconst [objOrMsg, msg] = inputArgs;\n\t\t\t\t\tif (typeof objOrMsg === \"object\" && objOrMsg !== null) {\n\t\t\t\t\t\tcustomWrite(levelName, { ...objOrMsg, msg, time });\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcustomWrite(levelName, { msg: String(objOrMsg), time });\n\t\t\t\t\t}\n\t\t\t\t} else if (inputArgs.length === 1) {\n\t\t\t\t\tconst [objOrMsg] = inputArgs;\n\t\t\t\t\tif (typeof objOrMsg === \"object\" && objOrMsg !== null) {\n\t\t\t\t\t\tcustomWrite(levelName, { ...objOrMsg, time });\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcustomWrite(levelName, { msg: String(objOrMsg), time });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t});\n\n\tloggerCache.clear();\n}\n\n/**\n * Get or initialize the base logger.\n */\nexport function getBaseLogger(): Logger {\n\tif (!baseLogger) {\n\t\tconfigureDefaultLogger();\n\t}\n\treturn baseLogger!;\n}\n\n/**\n * Returns a child logger with `target` bound for the given name.\n */\nexport function getLogger(name = \"default\"): Logger {\n\t// Check cache first\n\tconst cached = loggerCache.get(name);\n\tif (cached) {\n\t\treturn cached;\n\t}\n\n\t// Create\n\tconst base = getBaseLogger();\n\n\t// Add target to log if enabled\n\tconst child = getIncludeTarget() ? base.child({ target: name }) : base;\n\n\t// Cache the logger\n\tloggerCache.set(name, child);\n\n\treturn child;\n}\n"],"mappings":";AAAA,SAAS,aAAa;AAEtB,SAAS,cAAc;AACvB,SAAS,YAAoD;AAC7D,SAAS,iBAAiB;;;ACJ1B;AAAA,EAIC;AAAA,EACA;AAAA,OACM;AACP,SAAS,eAAe;AAIxB,IAAI;AACJ,IAAI;AAGJ,IAAM,cAAc,oBAAI,IAAoB;AAErC,SAAS,aAAa,UAAmC;AAE/D,MAAI,UAAU;AACb,WAAO;AAAA,EACR;AAEA,MAAI,oBAAoB;AACvB,WAAO;AAAA,EACR;AAEA,UAAQ,QAAQ,IAAI,WAAW,KAAK,QAClC,SAAS,EACT,YAAY;AACf;AAEO,SAAS,mBAA4B;AAC3C,SAAO,QAAQ,IAAI,YAAY,MAAM;AACtC;AAWA,SAAS,YAAY,OAAe,GAAQ;AAC3C,QAAM,UAAe,CAAC;AAGtB,MAAI,QAAQ,IAAI,eAAe,MAAM,OAAO,EAAE,MAAM;AACnD,UAAM,OAAO,OAAO,EAAE,SAAS,WAAW,IAAI,KAAK,EAAE,IAAI,IAAI,oBAAI,KAAK;AACtE,YAAQ,KAAK;AAAA,EACd;AAGA,UAAQ,QAAQ,MAAM,YAAY;AAGlC,MAAI,EAAE,QAAQ;AACb,YAAQ,SAAS,EAAE;AAAA,EACpB;AAGA,MAAI,EAAE,KAAK;AACV,YAAQ,MAAM,EAAE;AAAA,EACjB;AAGA,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,CAAC,GAAG;AAC7C,QACC,QAAQ,UACR,QAAQ,WACR,QAAQ,YACR,QAAQ,SACR,QAAQ,SACR,QAAQ,YACP;AACD,cAAQ,GAAG,IAAI;AAAA,IAChB;AAAA,EACD;AA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I,CAAC;AAAA,IAC1C;AAAA,IACA,cAAc,OACb,UACA,aACA,YACI;AACJ,gBAAU,EAAE;AAAA,QACX,SAAS,QAAQ,wBAAwB,WAAW;AAAA,MACrD;AAAA,IACD;AAAA,IACA,aAAa,OAAO,UAAkB,gBAAwB;AAC7D,gBAAU,EAAE;AAAA,QACX,SAAS,QAAQ,wBAAwB,WAAW;AAAA,MACrD;AAAA,IACD;AAAA,IACA,WAAW,OACV,SACA,SACA,IACA,YACI;AACJ,gBAAU,EAAE,KAAK,iCAAiC,OAAO,EAAE;AAC3D,sBAAgB,IAAI,SAAS,EAAE;AAG/B,SAAG,iBAAiB,WAAW,CAAC,UAAU;AACzC,cAAM,OAAO,MAAM;AACnB,kBAAU,EAAE,KAAK;AAAA,UAChB,KAAK,gCAAgC,OAAO;AAAA,UAC5C;AAAA,QACD,CAAC;AACD,WAAG,KAAK,SAAS,IAAI,EAAE;AAAA,MACxB,CAAC;AAED,SAAG,iBAAiB,SAAS,MAAM;AAClC,kBAAU,EAAE,KAAK,8BAA8B,OAAO,EAAE;AACxD,wBAAgB,OAAO,OAAO;AAAA,MAC/B,CAAC;AAED,SAAG,iBAAiB,SAAS,CAAC,UAAU;AACvC,kBAAU,EAAE,MAAM;AAAA,UACjB,KAAK,6BAA6B,OAAO;AAAA,UACzC;AAAA,QACD,CAAC;AAAA,MACF,CAAC;AAAA,IACF;AAAA,EACD;AAEA,QAAMA,UAAS,IAAI,OAAO,MAAM;AAGhC,QAAMA,QAAO,MAAM;AAGnB,YAAU,EAAE,KAAK,yBAAyB;AAC1C,QAAMC,eAAc;AAEpB,YAAU,EAAE,KAAK,gBAAgB;AAEjC,SAAO,CAACD,SAAQC,gBAAeC,cAAa;AAC7C;AAEA,IAAO,gBAAQ;","names":["runner","runnerStarted","runnerStopped"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@rivetkit/engine-test-runner",
|
|
3
|
+
"version": "2.0.21",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"dependencies": {
|
|
6
|
+
"@hono/node-server": "^1.19.1",
|
|
7
|
+
"hono": "^4.7.0",
|
|
8
|
+
"pino": "^9.9.5",
|
|
9
|
+
"ws": "^8.18.3",
|
|
10
|
+
"@rivetkit/engine-runner": "2.0.21",
|
|
11
|
+
"@rivetkit/engine-runner-protocol": "2.0.21"
|
|
12
|
+
},
|
|
13
|
+
"devDependencies": {
|
|
14
|
+
"@types/node": "^22.18.1",
|
|
15
|
+
"@types/ws": "^8.18.1",
|
|
16
|
+
"tinybench": "^5.0.1",
|
|
17
|
+
"tsup": "^8.5.0",
|
|
18
|
+
"tsx": "^4.20.5",
|
|
19
|
+
"typescript": "^5.9.2",
|
|
20
|
+
"vitest": "^1.6.1"
|
|
21
|
+
},
|
|
22
|
+
"scripts": {
|
|
23
|
+
"start": "tsx src/index.ts",
|
|
24
|
+
"build": "tsup src/index.ts",
|
|
25
|
+
"check-types": "tsc --noEmit"
|
|
26
|
+
}
|
|
27
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
import { serve } from "@hono/node-server";
|
|
2
|
+
import type { ActorConfig, RunnerConfig } from "@rivetkit/engine-runner";
|
|
3
|
+
import { Runner } from "@rivetkit/engine-runner";
|
|
4
|
+
import { Hono, type Context as HonoContext, type Next } from "hono";
|
|
5
|
+
import { streamSSE } from "hono/streaming";
|
|
6
|
+
import type { Logger } from "pino";
|
|
7
|
+
import type WebSocket from "ws";
|
|
8
|
+
import { getLogger } from "./log";
|
|
9
|
+
|
|
10
|
+
const INTERNAL_SERVER_PORT = process.env.INTERNAL_SERVER_PORT
|
|
11
|
+
? Number(process.env.INTERNAL_SERVER_PORT)
|
|
12
|
+
: 5051;
|
|
13
|
+
const RIVET_NAMESPACE = process.env.RIVET_NAMESPACE ?? "default";
|
|
14
|
+
const RIVET_RUNNER_NAME = process.env.RIVET_RUNNER_NAME ?? "test-runner";
|
|
15
|
+
const RIVET_RUNNER_KEY =
|
|
16
|
+
process.env.RIVET_RUNNER_KEY ?? `key-${Math.floor(Math.random() * 10000)}`;
|
|
17
|
+
const RIVET_RUNNER_VERSION = process.env.RIVET_RUNNER_VERSION
|
|
18
|
+
? Number(process.env.RIVET_RUNNER_VERSION)
|
|
19
|
+
: 1;
|
|
20
|
+
const RIVET_RUNNER_TOTAL_SLOTS = process.env.RIVET_RUNNER_TOTAL_SLOTS
|
|
21
|
+
? Number(process.env.RIVET_RUNNER_TOTAL_SLOTS)
|
|
22
|
+
: 100;
|
|
23
|
+
const RIVET_ENDPOINT = process.env.RIVET_ENDPOINT ?? "http://127.0.0.1:6420";
|
|
24
|
+
const RIVET_TOKEN = process.env.RIVET_TOKEN ?? "dev";
|
|
25
|
+
const AUTOSTART_SERVER = process.env.NO_AUTOSTART_SERVER === undefined;
|
|
26
|
+
const AUTOSTART_RUNNER = process.env.NO_AUTOSTART_RUNNER === undefined;
|
|
27
|
+
|
|
28
|
+
let runnerStarted = Promise.withResolvers();
|
|
29
|
+
let runnerStopped = Promise.withResolvers();
|
|
30
|
+
let runner: Runner | null = null;
|
|
31
|
+
const actorWebSockets = new Map<string, WebSocket>();
|
|
32
|
+
|
|
33
|
+
// Create internal server
|
|
34
|
+
const app = new Hono();
|
|
35
|
+
|
|
36
|
+
function loggerMiddleware(logger: Logger) {
|
|
37
|
+
return async (c: HonoContext, next: Next) => {
|
|
38
|
+
const method = c.req.method;
|
|
39
|
+
const path = c.req.path;
|
|
40
|
+
const startTime = Date.now();
|
|
41
|
+
|
|
42
|
+
await next();
|
|
43
|
+
|
|
44
|
+
const duration = Date.now() - startTime;
|
|
45
|
+
logger.debug({
|
|
46
|
+
msg: "http request",
|
|
47
|
+
method,
|
|
48
|
+
path,
|
|
49
|
+
status: c.res.status,
|
|
50
|
+
dt: `${duration}ms`,
|
|
51
|
+
reqSize: c.req.header("content-length"),
|
|
52
|
+
resSize: c.res.headers.get("content-length"),
|
|
53
|
+
userAgent: c.req.header("user-agent"),
|
|
54
|
+
});
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
app.use("*", loggerMiddleware(getLogger()));
|
|
58
|
+
|
|
59
|
+
app.get("/wait-ready", async (c) => {
|
|
60
|
+
await runnerStarted.promise;
|
|
61
|
+
return c.json(runner?.runnerId);
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
app.get("/has-actor", async (c) => {
|
|
65
|
+
const actorIdQuery = c.req.query("actor");
|
|
66
|
+
const generationQuery = c.req.query("generation");
|
|
67
|
+
const generation = generationQuery ? Number(generationQuery) : undefined;
|
|
68
|
+
|
|
69
|
+
if (!actorIdQuery || !runner?.hasActor(actorIdQuery, generation)) {
|
|
70
|
+
return c.text("", 404);
|
|
71
|
+
}
|
|
72
|
+
return c.text("ok");
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
app.get("/shutdown", async (c) => {
|
|
76
|
+
await runner?.shutdown(true);
|
|
77
|
+
return c.text("ok");
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
app.get("/start", async (c) => {
|
|
81
|
+
return streamSSE(c, async (stream) => {
|
|
82
|
+
const [runner, runnerStarted, runnerStopped] = await startRunner();
|
|
83
|
+
|
|
84
|
+
c.req.raw.signal.addEventListener("abort", () => {
|
|
85
|
+
getLogger().debug("SSE aborted, shutting down runner");
|
|
86
|
+
runner.shutdown(true);
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
await runnerStarted.promise;
|
|
90
|
+
|
|
91
|
+
stream.writeSSE({ data: runner.getServerlessInitPacket()! });
|
|
92
|
+
|
|
93
|
+
await runnerStopped.promise;
|
|
94
|
+
});
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
await autoConfigureServerless();
|
|
98
|
+
|
|
99
|
+
if (AUTOSTART_SERVER) {
|
|
100
|
+
serve({
|
|
101
|
+
fetch: app.fetch,
|
|
102
|
+
port: INTERNAL_SERVER_PORT,
|
|
103
|
+
});
|
|
104
|
+
getLogger().info(
|
|
105
|
+
`Internal HTTP server listening on port ${INTERNAL_SERVER_PORT}`,
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
if (AUTOSTART_RUNNER)
|
|
110
|
+
[runner, runnerStarted, runnerStopped] = await startRunner();
|
|
111
|
+
|
|
112
|
+
async function autoConfigureServerless() {
|
|
113
|
+
const res = await fetch(
|
|
114
|
+
`http://127.0.0.1:6420/runner-configs/${RIVET_RUNNER_NAME}?namespace=${RIVET_NAMESPACE}`,
|
|
115
|
+
{
|
|
116
|
+
method: "PUT",
|
|
117
|
+
headers: {
|
|
118
|
+
Authorization: `Bearer ${RIVET_TOKEN}`,
|
|
119
|
+
"Content-Type": "application/json",
|
|
120
|
+
},
|
|
121
|
+
body: JSON.stringify({
|
|
122
|
+
datacenters: {
|
|
123
|
+
default: {
|
|
124
|
+
serverless: {
|
|
125
|
+
url: `http://localhost:${INTERNAL_SERVER_PORT}`,
|
|
126
|
+
max_runners: 10,
|
|
127
|
+
slots_per_runner: 1,
|
|
128
|
+
request_lifespan: 15,
|
|
129
|
+
},
|
|
130
|
+
},
|
|
131
|
+
},
|
|
132
|
+
}),
|
|
133
|
+
},
|
|
134
|
+
);
|
|
135
|
+
|
|
136
|
+
if (!res.ok) {
|
|
137
|
+
throw new Error(
|
|
138
|
+
`request failed: ${res.statusText} (${res.status}):\n${await res.text()}`,
|
|
139
|
+
);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
async function startRunner(): Promise<
|
|
144
|
+
[Runner, PromiseWithResolvers<unknown>, PromiseWithResolvers<unknown>]
|
|
145
|
+
> {
|
|
146
|
+
getLogger().info("Starting runner");
|
|
147
|
+
|
|
148
|
+
const runnerStarted = Promise.withResolvers();
|
|
149
|
+
const runnerStopped = Promise.withResolvers();
|
|
150
|
+
|
|
151
|
+
const config: RunnerConfig = {
|
|
152
|
+
logger: getLogger(),
|
|
153
|
+
version: RIVET_RUNNER_VERSION,
|
|
154
|
+
endpoint: RIVET_ENDPOINT,
|
|
155
|
+
token: RIVET_TOKEN,
|
|
156
|
+
namespace: RIVET_NAMESPACE,
|
|
157
|
+
runnerName: RIVET_RUNNER_NAME,
|
|
158
|
+
runnerKey: RIVET_RUNNER_KEY,
|
|
159
|
+
totalSlots: RIVET_RUNNER_TOTAL_SLOTS,
|
|
160
|
+
prepopulateActorNames: {},
|
|
161
|
+
onConnected: () => {
|
|
162
|
+
runnerStarted.resolve(undefined);
|
|
163
|
+
},
|
|
164
|
+
onDisconnected: () => {},
|
|
165
|
+
onShutdown: () => {
|
|
166
|
+
runnerStopped.resolve(undefined);
|
|
167
|
+
},
|
|
168
|
+
fetch: async (runner: Runner, actorId: string, request: Request) => {
|
|
169
|
+
getLogger().info(
|
|
170
|
+
`Fetch called for actor ${actorId}, URL: ${request.url}`,
|
|
171
|
+
);
|
|
172
|
+
const url = new URL(request.url);
|
|
173
|
+
if (url.pathname === "/ping") {
|
|
174
|
+
// Return the actor ID in response
|
|
175
|
+
const responseData = {
|
|
176
|
+
actorId,
|
|
177
|
+
status: "ok",
|
|
178
|
+
timestamp: Date.now(),
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
return new Response(JSON.stringify(responseData), {
|
|
182
|
+
status: 200,
|
|
183
|
+
headers: { "Content-Type": "application/json" },
|
|
184
|
+
});
|
|
185
|
+
} else if (url.pathname === "/sleep") {
|
|
186
|
+
runner.sleepActor(actorId);
|
|
187
|
+
|
|
188
|
+
return new Response("ok", {
|
|
189
|
+
status: 200,
|
|
190
|
+
headers: { "Content-Type": "application/json" },
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
return new Response("ok", { status: 200 });
|
|
195
|
+
},
|
|
196
|
+
onActorStart: async (
|
|
197
|
+
_actorId: string,
|
|
198
|
+
_generation: number,
|
|
199
|
+
_config: ActorConfig,
|
|
200
|
+
) => {
|
|
201
|
+
getLogger().info(
|
|
202
|
+
`Actor ${_actorId} started (generation ${_generation})`,
|
|
203
|
+
);
|
|
204
|
+
},
|
|
205
|
+
onActorStop: async (_actorId: string, _generation: number) => {
|
|
206
|
+
getLogger().info(
|
|
207
|
+
`Actor ${_actorId} stopped (generation ${_generation})`,
|
|
208
|
+
);
|
|
209
|
+
},
|
|
210
|
+
websocket: async (
|
|
211
|
+
_runner: Runner,
|
|
212
|
+
actorId: string,
|
|
213
|
+
ws: WebSocket,
|
|
214
|
+
request: Request,
|
|
215
|
+
) => {
|
|
216
|
+
getLogger().info(`WebSocket connected for actor ${actorId}`);
|
|
217
|
+
actorWebSockets.set(actorId, ws);
|
|
218
|
+
|
|
219
|
+
// Echo server - send back any messages received
|
|
220
|
+
ws.addEventListener("message", (event) => {
|
|
221
|
+
const data = event.data;
|
|
222
|
+
getLogger().info({
|
|
223
|
+
msg: `WebSocket message from actor ${actorId}`,
|
|
224
|
+
data,
|
|
225
|
+
});
|
|
226
|
+
ws.send(`Echo: ${data}`);
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
ws.addEventListener("close", () => {
|
|
230
|
+
getLogger().info(`WebSocket closed for actor ${actorId}`);
|
|
231
|
+
actorWebSockets.delete(actorId);
|
|
232
|
+
});
|
|
233
|
+
|
|
234
|
+
ws.addEventListener("error", (error) => {
|
|
235
|
+
getLogger().error({
|
|
236
|
+
msg: `WebSocket error for actor ${actorId}:`,
|
|
237
|
+
error,
|
|
238
|
+
});
|
|
239
|
+
});
|
|
240
|
+
},
|
|
241
|
+
};
|
|
242
|
+
|
|
243
|
+
const runner = new Runner(config);
|
|
244
|
+
|
|
245
|
+
// Start runner
|
|
246
|
+
await runner.start();
|
|
247
|
+
|
|
248
|
+
// Wait for runner to be ready
|
|
249
|
+
getLogger().info("Waiting runner start...");
|
|
250
|
+
await runnerStarted.promise;
|
|
251
|
+
|
|
252
|
+
getLogger().info("Runner started");
|
|
253
|
+
|
|
254
|
+
return [runner, runnerStarted, runnerStopped];
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
export default app;
|
package/src/log.ts
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type Level,
|
|
3
|
+
type LevelWithSilent,
|
|
4
|
+
type Logger,
|
|
5
|
+
pino,
|
|
6
|
+
stdTimeFunctions,
|
|
7
|
+
} from "pino";
|
|
8
|
+
import { inspect } from "util";
|
|
9
|
+
|
|
10
|
+
export type { Logger } from "pino";
|
|
11
|
+
|
|
12
|
+
let baseLogger: Logger | undefined;
|
|
13
|
+
let configuredLogLevel: Level | undefined;
|
|
14
|
+
|
|
15
|
+
/** Cache of child loggers by logger name. */
|
|
16
|
+
const loggerCache = new Map<string, Logger>();
|
|
17
|
+
|
|
18
|
+
export function getPinoLevel(logLevel?: Level): LevelWithSilent {
|
|
19
|
+
// Priority: provided > configured > env > default
|
|
20
|
+
if (logLevel) {
|
|
21
|
+
return logLevel;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
if (configuredLogLevel) {
|
|
25
|
+
return configuredLogLevel;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
return (process.env["LOG_LEVEL"] || "warn")
|
|
29
|
+
.toString()
|
|
30
|
+
.toLowerCase() as LevelWithSilent;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function getIncludeTarget(): boolean {
|
|
34
|
+
return process.env["LOG_TARGET"] === "1";
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Configure a custom base logger.
|
|
39
|
+
*/
|
|
40
|
+
export function configureBaseLogger(logger: Logger): void {
|
|
41
|
+
baseLogger = logger;
|
|
42
|
+
loggerCache.clear();
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// TODO: This can be simplified in logfmt.ts
|
|
46
|
+
function customWrite(level: string, o: any) {
|
|
47
|
+
const entries: any = {};
|
|
48
|
+
|
|
49
|
+
// Add timestamp if enabled
|
|
50
|
+
if (process.env["LOG_TIMESTAMP"] === "1" && o.time) {
|
|
51
|
+
const date = typeof o.time === "number" ? new Date(o.time) : new Date();
|
|
52
|
+
entries.ts = date;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// Add level
|
|
56
|
+
entries.level = level.toUpperCase();
|
|
57
|
+
|
|
58
|
+
// Add target if present
|
|
59
|
+
if (o.target) {
|
|
60
|
+
entries.target = o.target;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// Add message
|
|
64
|
+
if (o.msg) {
|
|
65
|
+
entries.msg = o.msg;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// Add other properties
|
|
69
|
+
for (const [key, value] of Object.entries(o)) {
|
|
70
|
+
if (
|
|
71
|
+
key !== "time" &&
|
|
72
|
+
key !== "level" &&
|
|
73
|
+
key !== "target" &&
|
|
74
|
+
key !== "msg" &&
|
|
75
|
+
key !== "pid" &&
|
|
76
|
+
key !== "hostname"
|
|
77
|
+
) {
|
|
78
|
+
entries[key] = value;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const output = inspect(entries, {
|
|
83
|
+
compact: true,
|
|
84
|
+
breakLength: Infinity,
|
|
85
|
+
colors: true,
|
|
86
|
+
});
|
|
87
|
+
console.log(output);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Configure the default logger with optional log level.
|
|
92
|
+
*/
|
|
93
|
+
export async function configureDefaultLogger(logLevel?: Level): Promise<void> {
|
|
94
|
+
// Store the configured log level
|
|
95
|
+
if (logLevel) {
|
|
96
|
+
configuredLogLevel = logLevel;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
baseLogger = pino({
|
|
100
|
+
level: getPinoLevel(logLevel),
|
|
101
|
+
messageKey: "msg",
|
|
102
|
+
// Do not include pid/hostname in output
|
|
103
|
+
base: {},
|
|
104
|
+
// Keep a string level in the output
|
|
105
|
+
formatters: {
|
|
106
|
+
level(_label: string, number: number) {
|
|
107
|
+
return { level: number };
|
|
108
|
+
},
|
|
109
|
+
},
|
|
110
|
+
timestamp:
|
|
111
|
+
process.env["LOG_TIMESTAMP"] === "1"
|
|
112
|
+
? stdTimeFunctions.epochTime
|
|
113
|
+
: false,
|
|
114
|
+
browser: {
|
|
115
|
+
write: {
|
|
116
|
+
fatal: customWrite.bind(null, "fatal"),
|
|
117
|
+
error: customWrite.bind(null, "error"),
|
|
118
|
+
warn: customWrite.bind(null, "warn"),
|
|
119
|
+
info: customWrite.bind(null, "info"),
|
|
120
|
+
debug: customWrite.bind(null, "debug"),
|
|
121
|
+
trace: customWrite.bind(null, "trace"),
|
|
122
|
+
},
|
|
123
|
+
},
|
|
124
|
+
hooks: {
|
|
125
|
+
logMethod(inputArgs, _method, level) {
|
|
126
|
+
// TODO: This is a hack to not implement our own transport target. We can get better perf if we have our own transport target.
|
|
127
|
+
|
|
128
|
+
const levelMap: Record<number, string> = {
|
|
129
|
+
10: "trace",
|
|
130
|
+
20: "debug",
|
|
131
|
+
30: "info",
|
|
132
|
+
40: "warn",
|
|
133
|
+
50: "error",
|
|
134
|
+
60: "fatal",
|
|
135
|
+
};
|
|
136
|
+
const levelName = levelMap[level] || "info";
|
|
137
|
+
const time =
|
|
138
|
+
process.env["LOG_TIMESTAMP"] === "1"
|
|
139
|
+
? Date.now()
|
|
140
|
+
: undefined;
|
|
141
|
+
// TODO: This can be simplified in logfmt.ts
|
|
142
|
+
if (inputArgs.length >= 2) {
|
|
143
|
+
const [objOrMsg, msg] = inputArgs;
|
|
144
|
+
if (typeof objOrMsg === "object" && objOrMsg !== null) {
|
|
145
|
+
customWrite(levelName, { ...objOrMsg, msg, time });
|
|
146
|
+
} else {
|
|
147
|
+
customWrite(levelName, { msg: String(objOrMsg), time });
|
|
148
|
+
}
|
|
149
|
+
} else if (inputArgs.length === 1) {
|
|
150
|
+
const [objOrMsg] = inputArgs;
|
|
151
|
+
if (typeof objOrMsg === "object" && objOrMsg !== null) {
|
|
152
|
+
customWrite(levelName, { ...objOrMsg, time });
|
|
153
|
+
} else {
|
|
154
|
+
customWrite(levelName, { msg: String(objOrMsg), time });
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
},
|
|
158
|
+
},
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
loggerCache.clear();
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Get or initialize the base logger.
|
|
166
|
+
*/
|
|
167
|
+
export function getBaseLogger(): Logger {
|
|
168
|
+
if (!baseLogger) {
|
|
169
|
+
configureDefaultLogger();
|
|
170
|
+
}
|
|
171
|
+
return baseLogger!;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Returns a child logger with `target` bound for the given name.
|
|
176
|
+
*/
|
|
177
|
+
export function getLogger(name = "default"): Logger {
|
|
178
|
+
// Check cache first
|
|
179
|
+
const cached = loggerCache.get(name);
|
|
180
|
+
if (cached) {
|
|
181
|
+
return cached;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// Create
|
|
185
|
+
const base = getBaseLogger();
|
|
186
|
+
|
|
187
|
+
// Add target to log if enabled
|
|
188
|
+
const child = getIncludeTarget() ? base.child({ target: name }) : base;
|
|
189
|
+
|
|
190
|
+
// Cache the logger
|
|
191
|
+
loggerCache.set(name, child);
|
|
192
|
+
|
|
193
|
+
return child;
|
|
194
|
+
}
|
package/tsconfig.json
ADDED
package/tsup.config.ts
ADDED
package/turbo.json
ADDED
package/vitest.config.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { resolve } from "node:path";
|
|
2
|
+
import { defineConfig } from "vitest/config";
|
|
3
|
+
import defaultConfig from "../../../../vitest.base.ts";
|
|
4
|
+
|
|
5
|
+
export default defineConfig({
|
|
6
|
+
...defaultConfig,
|
|
7
|
+
resolve: {
|
|
8
|
+
alias: {
|
|
9
|
+
"@": resolve(__dirname, "./src"),
|
|
10
|
+
},
|
|
11
|
+
},
|
|
12
|
+
test: {
|
|
13
|
+
...defaultConfig.test,
|
|
14
|
+
include: ["tests/**/*.test.ts"],
|
|
15
|
+
},
|
|
16
|
+
});
|