@shivaedev/server 0.18.0 → 0.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +51 -0
- package/README.md +81 -17
- package/dist/AppModule.d.ts +22 -0
- package/dist/AppModule.d.ts.map +1 -0
- package/dist/AppModule.js +2 -0
- package/dist/AppModule.js.map +1 -0
- package/dist/DuplicateModuleQueue.d.ts +11 -0
- package/dist/DuplicateModuleQueue.d.ts.map +1 -0
- package/dist/DuplicateModuleQueue.js +11 -0
- package/dist/DuplicateModuleQueue.js.map +1 -0
- package/dist/{runtime/makePlatform.d.ts → adapters/makePlatformRuntime.d.ts} +2 -2
- package/dist/adapters/makePlatformRuntime.d.ts.map +1 -0
- package/dist/{runtime/makePlatform.js → adapters/makePlatformRuntime.js} +1 -1
- package/dist/adapters/makePlatformRuntime.js.map +1 -0
- package/dist/{nodeHttpServer.d.ts → adapters/nodeHttpServer.d.ts} +1 -0
- package/dist/adapters/nodeHttpServer.d.ts.map +1 -0
- package/dist/{nodeHttpServer.js → adapters/nodeHttpServer.js} +5 -0
- package/dist/adapters/nodeHttpServer.js.map +1 -0
- package/dist/adapters/subscriptionSignal.d.ts.map +1 -0
- package/dist/adapters/subscriptionSignal.js.map +1 -0
- package/dist/appDatabase.d.ts +2 -2
- package/dist/appDatabase.d.ts.map +1 -1
- package/dist/appDatabase.js +8 -3
- package/dist/appDatabase.js.map +1 -1
- package/dist/appHost.d.ts.map +1 -1
- package/dist/appHost.js +11 -4
- package/dist/appHost.js.map +1 -1
- package/dist/appHostHttp.d.ts +48 -30
- package/dist/appHostHttp.d.ts.map +1 -1
- package/dist/appHostHttp.js +2 -2
- package/dist/appHostHttp.js.map +1 -1
- package/dist/appModules.d.ts +37 -0
- package/dist/appModules.d.ts.map +1 -0
- package/dist/appModules.js +37 -0
- package/dist/appModules.js.map +1 -0
- package/dist/boundedRpcRequest.d.ts +3 -2
- package/dist/boundedRpcRequest.d.ts.map +1 -1
- package/dist/boundedRpcRequest.js +6 -5
- package/dist/boundedRpcRequest.js.map +1 -1
- package/dist/boundedRpcSocket.d.ts +4 -0
- package/dist/boundedRpcSocket.d.ts.map +1 -0
- package/dist/boundedRpcSocket.js +29 -0
- package/dist/boundedRpcSocket.js.map +1 -0
- package/dist/browserErrorRoute.js +1 -1
- package/dist/browserErrorRoute.js.map +1 -1
- package/dist/hostChanges.d.ts +4 -2
- package/dist/hostChanges.d.ts.map +1 -1
- package/dist/hostChanges.js +37 -42
- package/dist/hostChanges.js.map +1 -1
- package/dist/hostRpc.d.ts +4 -9
- package/dist/hostRpc.d.ts.map +1 -1
- package/dist/hostRpc.js +9 -17
- package/dist/hostRpc.js.map +1 -1
- package/dist/hostRpcRoutes.d.ts +5 -3
- package/dist/hostRpcRoutes.d.ts.map +1 -1
- package/dist/hostRpcRoutes.js +5 -4
- package/dist/hostRpcRoutes.js.map +1 -1
- package/dist/hostTransport.js +1 -1
- package/dist/hostTransport.js.map +1 -1
- package/dist/nativeClientOrigins.js +1 -1
- package/dist/nativeClientOrigins.js.map +1 -1
- package/dist/otlpHttpClient.js +2 -2
- package/dist/otlpHttpClient.js.map +1 -1
- package/dist/otlpTracing.d.ts.map +1 -1
- package/dist/otlpTracing.js +4 -4
- package/dist/otlpTracing.js.map +1 -1
- package/dist/publishCommand.d.ts +3 -0
- package/dist/publishCommand.d.ts.map +1 -0
- package/dist/publishCommand.js +36 -0
- package/dist/publishCommand.js.map +1 -0
- package/dist/redactingRpcSerialization.d.ts +3 -2
- package/dist/redactingRpcSerialization.d.ts.map +1 -1
- package/dist/redactingRpcSerialization.js +8 -8
- package/dist/redactingRpcSerialization.js.map +1 -1
- package/dist/rerunQuery.d.ts +7 -3
- package/dist/rerunQuery.d.ts.map +1 -1
- package/dist/rerunQuery.js +3 -4
- package/dist/rerunQuery.js.map +1 -1
- package/dist/setupDatabases.d.ts +1 -1
- package/dist/setupDatabases.d.ts.map +1 -1
- package/dist/setupDatabases.js +3 -3
- package/dist/setupDatabases.js.map +1 -1
- package/dist/socketRpc.js +1 -1
- package/dist/socketRpc.js.map +1 -1
- package/dist/testing/HostProcessError.d.ts +10 -0
- package/dist/testing/HostProcessError.d.ts.map +1 -0
- package/dist/testing/HostProcessError.js +4 -0
- package/dist/testing/HostProcessError.js.map +1 -0
- package/dist/testing/adapters/hostProcess.d.ts +23 -0
- package/dist/testing/adapters/hostProcess.d.ts.map +1 -0
- package/dist/testing/adapters/hostProcess.js +84 -0
- package/dist/testing/adapters/hostProcess.js.map +1 -0
- package/dist/testing/adapters/hostProcessReadouts.d.ts +10 -0
- package/dist/testing/adapters/hostProcessReadouts.d.ts.map +1 -0
- package/dist/testing/adapters/hostProcessReadouts.js +26 -0
- package/dist/testing/adapters/hostProcessReadouts.js.map +1 -0
- package/dist/testing/hostProcess.d.ts +24 -0
- package/dist/testing/hostProcess.d.ts.map +1 -0
- package/dist/testing/hostProcess.js +49 -0
- package/dist/testing/hostProcess.js.map +1 -0
- package/dist/testing/hostProcessChild.d.ts +6 -0
- package/dist/testing/hostProcessChild.d.ts.map +1 -0
- package/dist/testing/hostProcessChild.js +15 -0
- package/dist/testing/hostProcessChild.js.map +1 -0
- package/dist/testing/hostProcessProtocol.d.ts +17 -0
- package/dist/testing/hostProcessProtocol.d.ts.map +1 -0
- package/dist/testing/hostProcessProtocol.js +10 -0
- package/dist/testing/hostProcessProtocol.js.map +1 -0
- package/dist/testing/hostProcessReadouts.d.ts +7 -0
- package/dist/testing/hostProcessReadouts.d.ts.map +1 -0
- package/dist/testing/hostProcessReadouts.js +37 -0
- package/dist/testing/hostProcessReadouts.js.map +1 -0
- package/dist/workerHost.d.ts +7 -0
- package/dist/workerHost.d.ts.map +1 -0
- package/dist/workerHost.js +7 -0
- package/dist/workerHost.js.map +1 -0
- package/package.json +25 -17
- package/src/AppModule.ts +19 -0
- package/src/DuplicateModuleQueue.ts +11 -0
- package/src/{runtime/makePlatform.ts → adapters/makePlatformRuntime.ts} +1 -1
- package/src/{nodeHttpServer.ts → adapters/nodeHttpServer.ts} +7 -0
- package/src/appDatabase.ts +9 -3
- package/src/appHost.ts +17 -7
- package/src/appHostHttp.ts +2 -2
- package/src/appModules.ts +99 -0
- package/src/boundedRpcRequest.ts +6 -5
- package/src/boundedRpcSocket.ts +32 -0
- package/src/browserErrorRoute.ts +1 -1
- package/src/hostChanges.ts +66 -50
- package/src/hostRpc.ts +9 -23
- package/src/hostRpcRoutes.ts +22 -12
- package/src/hostTransport.ts +1 -1
- package/src/nativeClientOrigins.ts +1 -1
- package/src/otlpHttpClient.ts +2 -2
- package/src/otlpTracing.ts +8 -6
- package/src/publishCommand.ts +47 -0
- package/src/redactingRpcSerialization.ts +11 -12
- package/src/rerunQuery.ts +18 -6
- package/src/setupDatabases.ts +3 -3
- package/src/socketRpc.ts +1 -1
- package/src/testing/HostProcessError.ts +6 -0
- package/src/testing/adapters/hostProcess.ts +95 -0
- package/src/testing/adapters/hostProcessReadouts.ts +29 -0
- package/src/testing/hostProcess.ts +60 -0
- package/src/testing/hostProcessChild.ts +20 -0
- package/src/testing/hostProcessProtocol.ts +10 -0
- package/src/testing/hostProcessReadouts.ts +46 -0
- package/src/workerHost.ts +13 -0
- package/dist/node-http/subscriptionSignal.d.ts.map +0 -1
- package/dist/node-http/subscriptionSignal.js.map +0 -1
- package/dist/nodeHttpServer.d.ts.map +0 -1
- package/dist/nodeHttpServer.js.map +0 -1
- package/dist/runtime/makePlatform.d.ts.map +0 -1
- package/dist/runtime/makePlatform.js.map +0 -1
- /package/dist/{node-http → adapters}/subscriptionSignal.d.ts +0 -0
- /package/dist/{node-http → adapters}/subscriptionSignal.js +0 -0
- /package/src/{node-http → adapters}/subscriptionSignal.ts +0 -0
package/src/browserErrorRoute.ts
CHANGED
|
@@ -4,7 +4,7 @@ import * as HttpStatus from "effect/http/HttpStatus";
|
|
|
4
4
|
import { RateLimiter } from "effect/persistence";
|
|
5
5
|
import { redactBrowserText } from "@shivaedev/errors/redactBrowserText.ts";
|
|
6
6
|
import { isAuthUnavailable, isForbidden } from "@shivaedev/errors/taxonomy.ts";
|
|
7
|
-
import { localTransport, trustedProxyPeer } from "@shivaedev/identity/server/local.ts";
|
|
7
|
+
import { localTransport, trustedProxyPeer } from "@shivaedev/identity/server/adapters/local.ts";
|
|
8
8
|
import { SessionPolicy } from "@shivaedev/identity/server/SessionPolicy.ts";
|
|
9
9
|
import { resolveSession } from "@shivaedev/identity/server/session.ts";
|
|
10
10
|
|
package/src/hostChanges.ts
CHANGED
|
@@ -1,70 +1,86 @@
|
|
|
1
1
|
import { Context, Effect, Layer, Option, Stream } from "effect";
|
|
2
2
|
import { Headers } from "effect/http";
|
|
3
|
-
import { Rpc,
|
|
3
|
+
import type { Rpc, RpcGroup } from "effect/rpc";
|
|
4
|
+
import { changesHandlerLayer } from "@shivaedev/contract/changesHandlerLayer.ts";
|
|
4
5
|
import { LiveServer } from "@shivaedev/contract/LiveServer.ts";
|
|
5
6
|
import { CurrentViewer, type Viewer } from "@shivaedev/contract/readPolicy.ts";
|
|
6
7
|
import type { QueryReference } from "@shivaedev/contract/serverMetadata.ts";
|
|
7
|
-
import {
|
|
8
|
+
import { currentSessionContext } from "@shivaedev/identity/server/currentSessionContext.ts";
|
|
8
9
|
import { recheckSession } from "@shivaedev/identity/server/recheckSession.ts";
|
|
10
|
+
import { resolveChanges } from "@shivaedev/identity/server/resolveChanges.ts";
|
|
9
11
|
import { revalidateStream } from "@shivaedev/identity/server/revalidateStream.ts";
|
|
10
12
|
import { SessionPolicy } from "@shivaedev/identity/server/SessionPolicy.ts";
|
|
11
|
-
import { resolveChanges } from "@shivaedev/identity/server/sessionKeys.ts";
|
|
12
13
|
import { rerunQuery } from "#rerunQuery.ts";
|
|
13
14
|
|
|
14
|
-
export function hostChanges<R extends Rpc.Any>(
|
|
15
|
-
|
|
15
|
+
export function hostChanges<R extends Rpc.Any>(
|
|
16
|
+
group: RpcGroup.RpcGroup<R>,
|
|
17
|
+
): Layer.Layer<
|
|
18
|
+
Rpc.ToHandler<Extract<R, { readonly _tag: `${string}.$changes` }>>,
|
|
19
|
+
never,
|
|
20
|
+
Rpc.ExtractRequires<Extract<R, { readonly _tag: `${string}.$changes` }>, `${string}.$changes`>
|
|
21
|
+
>;
|
|
22
|
+
export function hostChanges(group: RpcGroup.RpcGroup<Rpc.Any>) {
|
|
23
|
+
return Layer.unwrap(
|
|
16
24
|
Effect.gen(function* () {
|
|
17
25
|
const changes = yield* Effect.serviceOption(LiveServer);
|
|
18
26
|
const sessions = yield* Effect.serviceOption(SessionPolicy);
|
|
19
|
-
const
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
? Stream.unwrap(changes.value.subscribe({ ...subscription, authorized }, context, rerunQuery(group, options)))
|
|
31
|
-
: Stream.concat(Stream.succeed({ _tag: "Resync" } as const), Stream.never);
|
|
32
|
-
if (Option.isNone(sessions) || Option.isNone(viewer)) {
|
|
33
|
-
return stream;
|
|
34
|
-
}
|
|
35
|
-
const revalidation = Effect.never.pipe(
|
|
36
|
-
revalidateStream(rpc, viewer.value.id, recheckSession(Headers.empty, rpc._tag)),
|
|
37
|
-
Effect.provideService(SessionPolicy, sessions.value),
|
|
38
|
-
);
|
|
39
|
-
return Stream.interruptWhen(stream, revalidation);
|
|
40
|
-
}),
|
|
41
|
-
);
|
|
42
|
-
}
|
|
43
|
-
for (const rpc of group.requests.values()) {
|
|
44
|
-
if (!(Rpc.isRpc(rpc) && rpc._tag.endsWith(".$changes"))) {
|
|
45
|
-
continue;
|
|
46
|
-
}
|
|
47
|
-
const provided = services.mapUnsafe.get(rpc.key);
|
|
48
|
-
if (Option.isNone(changes) && provided !== undefined) {
|
|
49
|
-
handlers.set(rpc.key, provided);
|
|
50
|
-
continue;
|
|
27
|
+
const retained: Layer.Layer<Rpc.Handler<string>>[] = [];
|
|
28
|
+
if (Option.isNone(changes)) {
|
|
29
|
+
for (const rpc of group.requests.values()) {
|
|
30
|
+
if (!rpc._tag.endsWith(".$changes")) {
|
|
31
|
+
continue;
|
|
32
|
+
}
|
|
33
|
+
const key = Context.Service<Rpc.Handler<string>>(rpc.key);
|
|
34
|
+
const provided = yield* Effect.serviceOption(key);
|
|
35
|
+
if (Option.isSome(provided)) {
|
|
36
|
+
retained.push(Layer.succeed(key, provided.value));
|
|
37
|
+
}
|
|
51
38
|
}
|
|
52
|
-
handlers.set(rpc.key, {
|
|
53
|
-
context: services,
|
|
54
|
-
handler: ({ queries }: { readonly queries: readonly QueryReference[] }, options: Parameters<Rpc.Handler<string>["handler"]>[1]) =>
|
|
55
|
-
subscribe(rpc, queries, options),
|
|
56
|
-
tag: rpc._tag,
|
|
57
|
-
});
|
|
58
39
|
}
|
|
59
|
-
|
|
40
|
+
const hosted = changesHandlerLayer(
|
|
41
|
+
group,
|
|
42
|
+
(rpc) =>
|
|
43
|
+
({ queries }: { readonly queries: readonly QueryReference[] }, options: Parameters<Rpc.Handler<string>["handler"]>[1]) =>
|
|
44
|
+
subscribe(group, changes, sessions, rpc, queries, options),
|
|
45
|
+
);
|
|
46
|
+
return Layer.mergeAll(hosted, ...retained);
|
|
60
47
|
}),
|
|
61
48
|
);
|
|
62
49
|
}
|
|
63
50
|
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
51
|
+
function subscribe(
|
|
52
|
+
group: RpcGroup.RpcGroup<Rpc.Any>,
|
|
53
|
+
changes: Option.Option<Context.Service.Shape<typeof LiveServer>>,
|
|
54
|
+
sessions: Option.Option<typeof SessionPolicy.Service>,
|
|
55
|
+
rpc: Rpc.AnyWithProps,
|
|
56
|
+
queries: readonly QueryReference[],
|
|
57
|
+
options: Parameters<Rpc.Handler<string>["handler"]>[1],
|
|
58
|
+
) {
|
|
59
|
+
return Stream.unwrap(
|
|
60
|
+
Effect.gen(function* () {
|
|
61
|
+
const subscription = yield* resolveChanges(rpc, queries);
|
|
62
|
+
const viewer = yield* CurrentViewer;
|
|
63
|
+
const refresh = refreshSession(sessions, viewer, rpc._tag);
|
|
64
|
+
const read = rerunQuery(group, options);
|
|
65
|
+
type Failure = Effect.Error<typeof subscription.authorized | typeof refresh | ReturnType<typeof read>>;
|
|
66
|
+
const stream = Option.isSome(changes)
|
|
67
|
+
? Stream.unwrap(changes.value.subscribe<Failure, Effect.Services<ReturnType<typeof read>>, typeof read>({ ...subscription, refresh }, read))
|
|
68
|
+
: Stream.concat(Stream.succeed({ _tag: "Resync" } as const), Stream.never);
|
|
69
|
+
if (Option.isNone(sessions) || Option.isNone(viewer)) {
|
|
70
|
+
return stream;
|
|
71
|
+
}
|
|
72
|
+
const revalidation = Effect.never.pipe(
|
|
73
|
+
revalidateStream(rpc, viewer.value.id, recheckSession(Headers.empty, rpc._tag)),
|
|
74
|
+
Effect.provideService(SessionPolicy, sessions.value),
|
|
75
|
+
);
|
|
76
|
+
return Stream.interruptWhen(stream, revalidation);
|
|
77
|
+
}),
|
|
78
|
+
);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function refreshSession(sessions: Option.Option<typeof SessionPolicy.Service>, viewer: Option.Option<Viewer>, tag: string) {
|
|
82
|
+
if (Option.isNone(sessions) || Option.isNone(viewer)) {
|
|
83
|
+
return Effect.context<never>();
|
|
68
84
|
}
|
|
69
|
-
return
|
|
70
|
-
}
|
|
85
|
+
return currentSessionContext(viewer.value.id, recheckSession(Headers.empty, tag)).pipe(Effect.provideService(SessionPolicy, sessions.value));
|
|
86
|
+
}
|
package/src/hostRpc.ts
CHANGED
|
@@ -1,33 +1,19 @@
|
|
|
1
|
-
import { Effect
|
|
1
|
+
import { Effect } from "effect";
|
|
2
2
|
import { type HttpEffect, HttpServerResponse } from "effect/http";
|
|
3
|
-
import { type Rpc, type RpcGroup,
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
3
|
+
import { type Rpc, type RpcGroup, RpcServer } from "effect/rpc";
|
|
4
|
+
import { CommandGuard, commandGuardLayer, guardCommands } from "@shivaedev/contract/CommandGuard.ts";
|
|
5
|
+
import { ReadPolicyGuard, readPolicyGuardLayer } from "@shivaedev/contract/ReadPolicyGuard.ts";
|
|
6
|
+
import { publishCommand } from "#publishCommand.ts";
|
|
7
7
|
import { tracedGroup } from "#tracedGroup.ts";
|
|
8
8
|
|
|
9
|
-
class HostedReadPolicy extends RpcMiddleware.Service<HostedReadPolicy>()("@shivaedev/server/HostedReadPolicy", {
|
|
10
|
-
error: Schema.Union([MissingReadPolicy, QueryReadDenied, WebSocketRequired]),
|
|
11
|
-
}) {}
|
|
12
|
-
|
|
13
|
-
export type { HostedReadPolicy };
|
|
14
|
-
|
|
15
9
|
export const rpcCacheControl: HttpEffect.PreResponseHandler = (_, response) =>
|
|
16
10
|
Effect.succeed(HttpServerResponse.setHeader(response, "cache-control", "private, no-store"));
|
|
17
11
|
|
|
18
12
|
export const hostRpc = Effect.fnUntraced(function* <R extends Rpc.Any>(group: RpcGroup.RpcGroup<R>, websocket = false) {
|
|
19
|
-
const guarded = group
|
|
20
|
-
// Keep the policy inside identity middleware so it sees the request's viewer.
|
|
21
|
-
for (const rpc of guarded.requests.values()) {
|
|
22
|
-
Object.assign(rpc, { middlewares: new Set([HostedReadPolicy, ...rpc.middlewares]) });
|
|
23
|
-
}
|
|
13
|
+
const guarded = yield* guardCommands(group);
|
|
24
14
|
const traced = tracedGroup(guarded);
|
|
15
|
+
const readPolicy = yield* ReadPolicyGuard.pipe(Effect.provide(readPolicyGuardLayer({ websocket })));
|
|
16
|
+
const publication = yield* CommandGuard.pipe(Effect.provide(commandGuardLayer(publishCommand)));
|
|
25
17
|
const handler = websocket ? RpcServer.toHttpEffectWebsocket(traced) : RpcServer.toHttpEffect(traced);
|
|
26
|
-
return yield* handler.pipe(
|
|
27
|
-
Effect.provideService(HostedReadPolicy, (effect, request) =>
|
|
28
|
-
!websocket && request.rpc._tag.endsWith(".$changes")
|
|
29
|
-
? Effect.fail(new WebSocketRequired({ message: `${request.rpc._tag} needs the WebSocket protocol` }))
|
|
30
|
-
: Effect.flatMap(CurrentViewer, (viewer) => authorizeReads(effect, request, viewer)),
|
|
31
|
-
),
|
|
32
|
-
);
|
|
18
|
+
return yield* handler.pipe(Effect.provideService(ReadPolicyGuard, readPolicy), Effect.provideService(CommandGuard, publication));
|
|
33
19
|
});
|
package/src/hostRpcRoutes.ts
CHANGED
|
@@ -4,10 +4,11 @@ import * as HttpStatus from "effect/http/HttpStatus";
|
|
|
4
4
|
import { type Rpc, type RpcGroup, RpcSerialization } from "effect/rpc";
|
|
5
5
|
import { validateReadPolicies } from "@shivaedev/contract/validateReadPolicies.ts";
|
|
6
6
|
import type { schemaSensitiveKeys } from "@shivaedev/errors/schemaSensitiveKeys.ts";
|
|
7
|
-
import { localRpcGuard } from "@shivaedev/identity/server/local.ts";
|
|
7
|
+
import { localRpcGuard } from "@shivaedev/identity/server/adapters/local.ts";
|
|
8
8
|
import type { SessionPolicy } from "@shivaedev/identity/server/SessionPolicy.ts";
|
|
9
9
|
import { authenticatedLayer, maybeAuthenticatedLayer } from "@shivaedev/identity/server/session.ts";
|
|
10
10
|
import { boundedRpcRequest } from "#boundedRpcRequest.ts";
|
|
11
|
+
import { boundedRpcSocket } from "#boundedRpcSocket.ts";
|
|
11
12
|
import { hostChanges } from "#hostChanges.ts";
|
|
12
13
|
import type { HostPolicy } from "#hostOptions.ts";
|
|
13
14
|
import { hostRpc, rpcCacheControl } from "#hostRpc.ts";
|
|
@@ -57,7 +58,7 @@ function buildRpcRoutes<TRpcs extends Rpc.Any, THandlers, TError, TRequirements>
|
|
|
57
58
|
return HttpRouter.use((router) =>
|
|
58
59
|
Effect.gen(function* () {
|
|
59
60
|
yield* validateReadPolicies(options.group);
|
|
60
|
-
const wire = redactingRpcSerialization(yield* RpcSerialization.RpcSerialization, sensitive
|
|
61
|
+
const wire = redactingRpcSerialization(yield* RpcSerialization.RpcSerialization, sensitive);
|
|
61
62
|
const handler = yield* hostRpc(options.group).pipe(Effect.provideService(RpcSerialization.RpcSerialization, wire));
|
|
62
63
|
const guarded = localRpcGuard(handler, trustedProxy, nativeOrigins);
|
|
63
64
|
const websocket = yield* hostRpc(options.group, true).pipe(Effect.provideService(RpcSerialization.RpcSerialization, wire));
|
|
@@ -68,17 +69,26 @@ function buildRpcRoutes<TRpcs extends Rpc.Any, THandlers, TError, TRequirements>
|
|
|
68
69
|
status: HttpStatus.fromLiteral("Forbidden"),
|
|
69
70
|
}),
|
|
70
71
|
);
|
|
71
|
-
yield* router.add(
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
72
|
+
yield* router.add("GET", options.rpcPath ?? "/rpc", () =>
|
|
73
|
+
boundedRpcSocket(bodySize).pipe(
|
|
74
|
+
Effect.flatMap((request) =>
|
|
75
|
+
socketRpc(websocket, options, trustedProxy, nativeOrigins).pipe(
|
|
76
|
+
Effect.provideService(HttpServerRequest.HttpServerRequest, request),
|
|
77
|
+
Effect.provideService(RpcSerialization.RpcSerialization, wire),
|
|
78
|
+
),
|
|
79
|
+
),
|
|
80
|
+
),
|
|
75
81
|
);
|
|
76
|
-
yield* router.add("POST", options.rpcPath ?? "/rpc", (
|
|
77
|
-
|
|
78
|
-
Effect.
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
+
yield* router.add("POST", options.rpcPath ?? "/rpc", () =>
|
|
83
|
+
boundedRpcRequest().pipe(
|
|
84
|
+
Effect.flatMap((request) =>
|
|
85
|
+
guarded.pipe(
|
|
86
|
+
Effect.provideService(HttpIncomingMessage.MaxBodySize, ByteSize.bytes(bodySize)),
|
|
87
|
+
Effect.provideService(HttpServerRequest.HttpServerRequest, request),
|
|
88
|
+
Effect.provideService(RpcSerialization.RpcSerialization, wire),
|
|
89
|
+
HttpEffect.withPreResponseHandler(rpcCacheControl),
|
|
90
|
+
),
|
|
91
|
+
),
|
|
82
92
|
),
|
|
83
93
|
);
|
|
84
94
|
}),
|
package/src/hostTransport.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Config, Effect, Option, Result, Schema } from "effect";
|
|
2
2
|
import * as NetAddress from "effect/net/NetAddress";
|
|
3
|
-
import { TrustedProxy } from "@shivaedev/identity/server/trustedProxy.ts";
|
|
3
|
+
import { TrustedProxy } from "@shivaedev/identity/server/adapters/trustedProxy.ts";
|
|
4
4
|
import { NativeOrigins } from "#nativeClientOrigins.ts";
|
|
5
5
|
import { TrustedProxyRequired } from "#TrustedProxyRequired.ts";
|
|
6
6
|
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Effect, Schema } from "effect";
|
|
2
2
|
import { Headers, HttpMiddleware, HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http";
|
|
3
3
|
import * as HttpStatus from "effect/http/HttpStatus";
|
|
4
|
-
import { localTransport } from "@shivaedev/identity/server/local.ts";
|
|
4
|
+
import { localTransport } from "@shivaedev/identity/server/adapters/local.ts";
|
|
5
5
|
|
|
6
6
|
export const NativeOrigins = Schema.Array(
|
|
7
7
|
Schema.String.check(
|
package/src/otlpHttpClient.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Effect, Layer } from "effect";
|
|
2
2
|
import { FetchHttpClient, HttpClient, HttpClientError, type HttpClientRequest, type HttpClientResponse } from "effect/http";
|
|
3
3
|
import { redactText } from "@shivaedev/errors/sensitive.ts";
|
|
4
|
-
import {
|
|
4
|
+
import { checkStatus } from "@shivaedev/http/checkStatus.ts";
|
|
5
5
|
import { boundedOtlpResponse } from "#adapters/boundedOtlpResponse.ts";
|
|
6
6
|
import { RedactionPolicy } from "#RedactionPolicy.ts";
|
|
7
7
|
|
|
@@ -32,7 +32,7 @@ export function otlpHttpClient(timeout = 10_000) {
|
|
|
32
32
|
Effect.orElseSucceed(() => "Unable to read collector response"),
|
|
33
33
|
Effect.map((body) => ({ "otlp.response": redactText(body, sensitive), "otlp.status": response.status })),
|
|
34
34
|
);
|
|
35
|
-
const checked =
|
|
35
|
+
const checked = checkStatus(response);
|
|
36
36
|
return Effect.matchEffect(checked, {
|
|
37
37
|
onFailure: () => warnOnce(diagnostic),
|
|
38
38
|
onSuccess: () =>
|
package/src/otlpTracing.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Config, Effect, Layer, Schema } from "effect";
|
|
1
|
+
import { Config, Context, Effect, Layer, Schema } from "effect";
|
|
2
2
|
import { OtlpSerialization, OtlpTracer } from "effect/observability";
|
|
3
3
|
import { traceDiagnostics } from "#adapters/traceDiagnostics.ts";
|
|
4
4
|
import { otlpHttpClient } from "#otlpHttpClient.ts";
|
|
@@ -9,7 +9,7 @@ import { safeOtlpSerialization } from "#safeOtlpSerialization.ts";
|
|
|
9
9
|
|
|
10
10
|
const endpointUrl = Schema.URL.check(Schema.makeFilter((url) => url.protocol === "http:" || url.protocol === "https:"));
|
|
11
11
|
|
|
12
|
-
export const otlpTracing: Layer.Layer<never, Config.ConfigError> = Layer.
|
|
12
|
+
export const otlpTracing: Layer.Layer<never, Config.ConfigError> = Layer.effectContext(
|
|
13
13
|
Effect.gen(function* () {
|
|
14
14
|
const tracesEndpoint = yield* Config.schema(endpointUrl, "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT").pipe(Config.withDefault(undefined));
|
|
15
15
|
const endpoint =
|
|
@@ -22,7 +22,7 @@ export const otlpTracing: Layer.Layer<never, Config.ConfigError> = Layer.unwrap(
|
|
|
22
22
|
Config.withDefault(undefined),
|
|
23
23
|
));
|
|
24
24
|
if (endpoint === undefined) {
|
|
25
|
-
return
|
|
25
|
+
return Context.empty();
|
|
26
26
|
}
|
|
27
27
|
const configuredProtocol = yield* Config.String("OTEL_EXPORTER_OTLP_TRACES_PROTOCOL").pipe(
|
|
28
28
|
Config.orElse(() => Config.String("OTEL_EXPORTER_OTLP_PROTOCOL")),
|
|
@@ -60,9 +60,11 @@ export const otlpTracing: Layer.Layer<never, Config.ConfigError> = Layer.unwrap(
|
|
|
60
60
|
Layer.provide(otlpHttpClient(requestTimeout)),
|
|
61
61
|
);
|
|
62
62
|
const sensitive = yield* RedactionPolicy;
|
|
63
|
-
return
|
|
64
|
-
|
|
65
|
-
|
|
63
|
+
return yield* Layer.build(
|
|
64
|
+
redactingDiagnostics(sensitive).pipe(
|
|
65
|
+
Layer.provideMerge(traceDiagnostics),
|
|
66
|
+
Layer.provideMerge(redactingTracer(sensitive).pipe(Layer.provideMerge(tracer))),
|
|
67
|
+
),
|
|
66
68
|
);
|
|
67
69
|
}),
|
|
68
70
|
);
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { Effect, Option, Schedule } from "effect";
|
|
2
|
+
import * as Reactivity from "effect/reactivity/Reactivity";
|
|
3
|
+
import { CommandPublication, type CommandPublicationError } from "@shivaedev/changes/commandPublication.ts";
|
|
4
|
+
import { ChangeObserver } from "@shivaedev/sql/transact.ts";
|
|
5
|
+
|
|
6
|
+
const recoverPublication = Effect.fnUntraced(function* (cause: CommandPublicationError) {
|
|
7
|
+
yield* Effect.logError("Committed command invalidation failed; resynchronizing live streams", cause);
|
|
8
|
+
const publication = yield* CommandPublication;
|
|
9
|
+
yield* publication.recover.pipe(
|
|
10
|
+
Effect.catch((error) => Effect.logError("Committed command Resync broadcast failed; other hosts may remain stale", error)),
|
|
11
|
+
);
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
export function publishCommand<A, E, R>(effect: Effect.Effect<A, E, R>, declaredKeys: (result: A) => readonly unknown[]) {
|
|
15
|
+
return Effect.uninterruptibleMask((restore) =>
|
|
16
|
+
Effect.gen(function* () {
|
|
17
|
+
const reactivity = yield* Effect.serviceOption(Reactivity.Reactivity);
|
|
18
|
+
if (Option.isNone(reactivity)) {
|
|
19
|
+
return yield* restore(effect);
|
|
20
|
+
}
|
|
21
|
+
const published = new Set<unknown>();
|
|
22
|
+
const observer = yield* ChangeObserver;
|
|
23
|
+
const result = yield* restore(effect).pipe(
|
|
24
|
+
Effect.provideService(ChangeObserver, (event) => {
|
|
25
|
+
if (event._tag === "Published") {
|
|
26
|
+
for (const key of event.changes) {
|
|
27
|
+
published.add(key);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
return observer(event);
|
|
31
|
+
}),
|
|
32
|
+
);
|
|
33
|
+
const keys = declaredKeys(result).filter((key) => !published.has(key));
|
|
34
|
+
if (keys.length > 0) {
|
|
35
|
+
const publication = yield* CommandPublication;
|
|
36
|
+
yield* publication
|
|
37
|
+
.publish(keys)
|
|
38
|
+
.pipe(
|
|
39
|
+
Effect.provideService(Reactivity.Reactivity, reactivity.value),
|
|
40
|
+
Effect.retry({ schedule: Schedule.exponential("50 millis"), times: 2 }),
|
|
41
|
+
Effect.catch(recoverPublication),
|
|
42
|
+
);
|
|
43
|
+
}
|
|
44
|
+
return result;
|
|
45
|
+
}),
|
|
46
|
+
);
|
|
47
|
+
}
|
|
@@ -1,25 +1,24 @@
|
|
|
1
|
-
import { Predicate } from "effect";
|
|
1
|
+
import { type Effect, Predicate } from "effect";
|
|
2
2
|
import type { RpcSerialization } from "effect/rpc";
|
|
3
3
|
import { redactWire } from "@shivaedev/errors/redact.ts";
|
|
4
|
-
import {
|
|
4
|
+
import type { schemaSensitiveKeys } from "@shivaedev/errors/schemaSensitiveKeys.ts";
|
|
5
|
+
import { REDACTED } from "@shivaedev/errors/sensitive.ts";
|
|
5
6
|
|
|
6
7
|
function isRequestId(value: unknown): value is string | number {
|
|
7
8
|
return typeof value === "string" || typeof value === "number";
|
|
8
9
|
}
|
|
9
10
|
export function redactingRpcSerialization(
|
|
10
11
|
wire: RpcSerialization.RpcSerialization["Service"],
|
|
11
|
-
sensitive:
|
|
12
|
-
maskFailure: (tag: string | undefined, reason: "Fail" | "Die") => boolean = () => false,
|
|
13
|
-
sensitiveForRpc: (tag: string | undefined) => SensitiveKey = () => sensitive,
|
|
12
|
+
sensitive: Effect.Success<ReturnType<typeof schemaSensitiveKeys>>,
|
|
14
13
|
): typeof wire {
|
|
15
14
|
function reason(value: unknown, tag: string | undefined): unknown {
|
|
16
|
-
const redacted = redactWire(value,
|
|
15
|
+
const redacted = redactWire(value, sensitive.forRpc(tag));
|
|
17
16
|
if (Predicate.isObjectOrArray(redacted)) {
|
|
18
|
-
if (Predicate.isTagged(value, "Fail") &&
|
|
19
|
-
return { ...redacted, _tag: "Fail", error:
|
|
17
|
+
if (Predicate.isTagged(value, "Fail") && Predicate.hasProperty(value, "error")) {
|
|
18
|
+
return { ...redacted, _tag: "Fail", error: sensitive.redactFailure(tag, "Fail", value.error) };
|
|
20
19
|
}
|
|
21
|
-
if (Predicate.isTagged(value, "Die") &&
|
|
22
|
-
return { ...redacted, _tag: "Die", defect:
|
|
20
|
+
if (Predicate.isTagged(value, "Die") && Predicate.hasProperty(value, "defect")) {
|
|
21
|
+
return { ...redacted, _tag: "Die", defect: sensitive.redactFailure(tag, "Die", value.defect) };
|
|
23
22
|
}
|
|
24
23
|
}
|
|
25
24
|
if (
|
|
@@ -32,7 +31,7 @@ export function redactingRpcSerialization(
|
|
|
32
31
|
}
|
|
33
32
|
function exit(value: unknown, tag: string | undefined): unknown {
|
|
34
33
|
if (Predicate.isTagged(value, "Failure") && Predicate.hasProperty(value, "cause")) {
|
|
35
|
-
const cause = Array.isArray(value.cause) ? value.cause.map((item) => reason(item, tag)) : redactWire(value.cause,
|
|
34
|
+
const cause = Array.isArray(value.cause) ? value.cause.map((item) => reason(item, tag)) : redactWire(value.cause, sensitive.forRpc(tag));
|
|
36
35
|
return { ...value, cause };
|
|
37
36
|
}
|
|
38
37
|
return value;
|
|
@@ -47,7 +46,7 @@ export function redactingRpcSerialization(
|
|
|
47
46
|
return value.map(response);
|
|
48
47
|
}
|
|
49
48
|
if (Predicate.isTagged(value, "Defect") && Predicate.hasProperty(value, "defect")) {
|
|
50
|
-
return { ...value, defect: maskFailure(undefined, "Die") ? REDACTED : redactWire(value.defect, sensitive) };
|
|
49
|
+
return { ...value, defect: sensitive.maskFailure(undefined, "Die") ? REDACTED : redactWire(value.defect, sensitive) };
|
|
51
50
|
}
|
|
52
51
|
if (
|
|
53
52
|
Predicate.isTagged(value, "Exit")
|
package/src/rerunQuery.ts
CHANGED
|
@@ -1,23 +1,35 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Effect } from "effect";
|
|
2
2
|
import { Rpc, RpcGroup } from "effect/rpc";
|
|
3
|
-
import { authorizeReads, CurrentViewer } from "@shivaedev/contract/readPolicy.ts";
|
|
3
|
+
import { authorizeReads, CurrentViewer, type PolicyChannels } from "@shivaedev/contract/readPolicy.ts";
|
|
4
|
+
import type { MissingReadPolicy, QueryReadDenied } from "@shivaedev/contract/readPolicyErrors.ts";
|
|
4
5
|
import type { QueryRequest } from "@shivaedev/contract/serverMetadata.ts";
|
|
5
6
|
|
|
7
|
+
type Handlers<R extends Rpc.Any> = string extends R["_tag"] ? Rpc.Handler<string> : Rpc.ToHandler<R>;
|
|
8
|
+
|
|
9
|
+
export function rerunQuery<R extends Rpc.Any>(
|
|
10
|
+
group: { readonly requests: ReadonlyMap<string, R> },
|
|
11
|
+
options: Parameters<Rpc.Handler<string>["handler"]>[1],
|
|
12
|
+
): (
|
|
13
|
+
request: QueryRequest,
|
|
14
|
+
) => Effect.Effect<
|
|
15
|
+
unknown,
|
|
16
|
+
Rpc.ErrorExit<R> | PolicyChannels<R>["error"] | MissingReadPolicy | QueryReadDenied,
|
|
17
|
+
Handlers<R> | PolicyChannels<R>["services"]
|
|
18
|
+
>;
|
|
6
19
|
export function rerunQuery(group: { readonly requests: ReadonlyMap<string, Rpc.Any> }, options: Parameters<Rpc.Handler<string>["handler"]>[1]) {
|
|
7
20
|
const prefix = options.rpc._tag.slice(0, -"$changes".length);
|
|
8
|
-
return Effect.fnUntraced(function* ({ payload, query }: QueryRequest)
|
|
21
|
+
return Effect.fnUntraced(function* ({ payload, query }: QueryRequest) {
|
|
9
22
|
const tag = `${prefix}${query.name}`;
|
|
10
23
|
const rpc = group.requests.get(tag);
|
|
11
24
|
if (!Rpc.isRpc(rpc)) {
|
|
12
25
|
return yield* Effect.die(new Error(`Unknown query: ${tag}`));
|
|
13
26
|
}
|
|
14
|
-
const
|
|
15
|
-
const handler = yield* RpcGroup.make(rpc).accessHandler(tag).pipe(Effect.provideContext(services));
|
|
27
|
+
const handler = yield* RpcGroup.make(rpc).accessHandler(tag);
|
|
16
28
|
const viewer = yield* CurrentViewer;
|
|
17
29
|
const result = handler(payload, { ...options });
|
|
18
30
|
if (!Effect.isEffect(result)) {
|
|
19
31
|
return yield* Effect.die(new Error(`Query ${tag} must return an Effect`));
|
|
20
32
|
}
|
|
21
|
-
return yield* authorizeReads(result, { payload, rpc }, viewer)
|
|
33
|
+
return yield* authorizeReads(result, { payload, rpc }, viewer);
|
|
22
34
|
});
|
|
23
35
|
}
|
package/src/setupDatabases.ts
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import { Config, Effect } from "effect";
|
|
2
|
+
import { dockerEnvironment } from "@shivaedev/local-postgres/server/dockerEnvironment.ts";
|
|
2
3
|
import { localPostgres } from "@shivaedev/local-postgres/server/localPostgres.ts";
|
|
3
4
|
|
|
4
5
|
export const setupDatabases = Effect.fn("Platform.setupDatabases")(function* () {
|
|
5
6
|
const config = yield* Config.all({
|
|
6
7
|
"DATABASE_URL": Config.String("DATABASE_URL"),
|
|
7
|
-
"DOCKER_CONTEXT": Config.String("DOCKER_CONTEXT").pipe(Config.withDefault("")),
|
|
8
|
-
"DOCKER_HOST": Config.String("DOCKER_HOST").pipe(Config.withDefault("")),
|
|
9
8
|
"TEST_DATABASE_URL": Config.String("TEST_DATABASE_URL"),
|
|
10
9
|
});
|
|
11
|
-
yield*
|
|
10
|
+
const environment = yield* dockerEnvironment;
|
|
11
|
+
yield* localPostgres(environment).prepareDatabases([config.DATABASE_URL, config.TEST_DATABASE_URL]);
|
|
12
12
|
});
|
package/src/socketRpc.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { Effect, type Scope } from "effect";
|
|
|
2
2
|
import { Headers, HttpServerRequest, HttpServerResponse } from "effect/http";
|
|
3
3
|
import * as HttpStatus from "effect/http/HttpStatus";
|
|
4
4
|
import { isAuthUnavailable, isForbidden } from "@shivaedev/errors/taxonomy.ts";
|
|
5
|
-
import { localTransport } from "@shivaedev/identity/server/local.ts";
|
|
5
|
+
import { localTransport } from "@shivaedev/identity/server/adapters/local.ts";
|
|
6
6
|
import { SessionPolicy } from "@shivaedev/identity/server/SessionPolicy.ts";
|
|
7
7
|
import { resolveSession } from "@shivaedev/identity/server/session.ts";
|
|
8
8
|
import { makeSocketSession, SocketSession } from "@shivaedev/identity/server/socketSession.ts";
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { type ChildProcess, type ForkOptions, fork } from "node:child_process";
|
|
2
|
+
import process from "node:process";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import { Option, type Redacted, Schema } from "effect";
|
|
5
|
+
|
|
6
|
+
export interface HostProcessOptions {
|
|
7
|
+
readonly args?: readonly string[];
|
|
8
|
+
readonly cwd?: string;
|
|
9
|
+
readonly databaseUrl?: Redacted.Redacted<string>;
|
|
10
|
+
readonly env?: NodeJS.ProcessEnv;
|
|
11
|
+
readonly execArgv?: readonly string[];
|
|
12
|
+
readonly module: string | URL;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function forkHost(options: HostProcessOptions, databaseUrl?: string) {
|
|
16
|
+
const settings: ForkOptions = {
|
|
17
|
+
cwd: options.cwd,
|
|
18
|
+
env: databaseUrl === undefined ? options.env : { ...options.env, "DATABASE_URL": databaseUrl },
|
|
19
|
+
execArgv: [...(options.execArgv ?? [])],
|
|
20
|
+
stdio: ["ignore", "ignore", "inherit", "ipc"],
|
|
21
|
+
};
|
|
22
|
+
return fork(typeof options.module === "string" ? options.module : fileURLToPath(options.module), [...(options.args ?? [])], settings);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function receiveHostMessage<A>(child: ChildProcess, schema: Schema.Codec<A>, signal: AbortSignal, action?: () => void) {
|
|
26
|
+
return new Promise<A>((resolve, reject) => {
|
|
27
|
+
function cleanup() {
|
|
28
|
+
child.off("message", message);
|
|
29
|
+
child.off("exit", exited);
|
|
30
|
+
child.off("error", failed);
|
|
31
|
+
signal.removeEventListener("abort", aborted);
|
|
32
|
+
}
|
|
33
|
+
function failed(cause: unknown) {
|
|
34
|
+
cleanup();
|
|
35
|
+
reject(cause);
|
|
36
|
+
}
|
|
37
|
+
function exited(code: number | null, delivered: NodeJS.Signals | null) {
|
|
38
|
+
failed(new Error(`Host exited (${delivered ?? code}) before IPC acknowledgement`));
|
|
39
|
+
}
|
|
40
|
+
function aborted() {
|
|
41
|
+
failed(signal.reason);
|
|
42
|
+
}
|
|
43
|
+
function message(value: unknown) {
|
|
44
|
+
const decoded = Schema.decodeUnknownOption(schema)(value);
|
|
45
|
+
if (Option.isSome(decoded)) {
|
|
46
|
+
cleanup();
|
|
47
|
+
resolve(decoded.value);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
child.on("message", message);
|
|
51
|
+
child.once("exit", exited);
|
|
52
|
+
child.once("error", failed);
|
|
53
|
+
signal.addEventListener("abort", aborted, { once: true });
|
|
54
|
+
if (signal.aborted) {
|
|
55
|
+
aborted();
|
|
56
|
+
} else if (child.exitCode !== null || child.signalCode !== null) {
|
|
57
|
+
exited(child.exitCode, child.signalCode);
|
|
58
|
+
} else {
|
|
59
|
+
try {
|
|
60
|
+
action?.();
|
|
61
|
+
} catch (cause) {
|
|
62
|
+
failed(cause);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function stopHost(child: ChildProcess) {
|
|
69
|
+
if (child.pid === undefined || child.exitCode !== null || child.signalCode !== null) {
|
|
70
|
+
return Promise.resolve();
|
|
71
|
+
}
|
|
72
|
+
return new Promise<void>((resolve) => {
|
|
73
|
+
child.once("exit", () => resolve());
|
|
74
|
+
child.kill("SIGKILL");
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function sendHostMessage(message: unknown) {
|
|
79
|
+
return new Promise<void>((resolve, reject) => {
|
|
80
|
+
if (process.send === undefined) {
|
|
81
|
+
reject(new Error("Host process needs a parent IPC channel"));
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
process.send(message, (error) => (error === null ? resolve() : reject(error)));
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function sendHostReady(url: string) {
|
|
89
|
+
return sendHostMessage({ pid: process.pid, type: "host-ready", url });
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export async function hostResponse(url: string, path: string, signal: AbortSignal) {
|
|
93
|
+
const response = await fetch(new URL(path, url), { redirect: "manual", signal });
|
|
94
|
+
return { body: await response.text(), headers: Object.fromEntries(response.headers), status: response.status };
|
|
95
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { ChildProcess } from "node:child_process";
|
|
2
|
+
import process from "node:process";
|
|
3
|
+
import { Option, Predicate, Schema } from "effect";
|
|
4
|
+
import { HostReadouts } from "#testing/hostProcessProtocol.ts";
|
|
5
|
+
import { receiveHostMessage } from "./hostProcess.ts";
|
|
6
|
+
|
|
7
|
+
export function listenHostReadouts(read: () => typeof HostReadouts.Type) {
|
|
8
|
+
function requested(message: unknown) {
|
|
9
|
+
if (Predicate.hasProperty(message, "type") && message.type === "host-readouts") {
|
|
10
|
+
process.send?.(read());
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
process.on("message", requested);
|
|
14
|
+
return () => process.off("message", requested);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function collectHostReadouts(child: ChildProcess) {
|
|
18
|
+
let completed: typeof HostReadouts.Type | undefined;
|
|
19
|
+
child.on("message", (message: unknown) => {
|
|
20
|
+
const decoded = Schema.decodeUnknownOption(HostReadouts)(message);
|
|
21
|
+
if (Option.isSome(decoded) && decoded.value.shutdownDuration !== null) {
|
|
22
|
+
completed = decoded.value;
|
|
23
|
+
}
|
|
24
|
+
});
|
|
25
|
+
return (signal: AbortSignal) =>
|
|
26
|
+
completed === undefined
|
|
27
|
+
? receiveHostMessage(child, HostReadouts, signal, () => child.send({ type: "host-readouts" }))
|
|
28
|
+
: Promise.resolve(completed);
|
|
29
|
+
}
|