@shivaedev/server 0.28.0 → 0.29.1

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shivaedev/server",
3
- "version": "0.28.0",
3
+ "version": "0.29.1",
4
4
  "description": "The Effect application host: HTTP and RPC serving, health, OTLP export, database and migrations, and development mode",
5
5
  "keywords": [
6
6
  "effect"
@@ -46,26 +46,26 @@
46
46
  ],
47
47
  "dependencies": {
48
48
  "@shivaedev/changes": "0.11.0",
49
- "@shivaedev/contract": "0.40.0",
49
+ "@shivaedev/contract": "0.42.0",
50
50
  "@shivaedev/errors": "0.10.0",
51
51
  "@shivaedev/http": "0.8.0",
52
- "@shivaedev/identity": "0.28.0",
52
+ "@shivaedev/identity": "0.29.1",
53
53
  "@shivaedev/local-postgres": "0.15.0",
54
- "@shivaedev/sql": "0.43.0"
54
+ "@shivaedev/sql": "0.44.0"
55
55
  },
56
56
  "devDependencies": {
57
57
  "@effect/platform-node": "4.1.0",
58
58
  "@effect/sql-pg": "4.1.0",
59
59
  "@effect/vitest": "4.1.0",
60
60
  "@shivaedev/access": "0.6.0",
61
- "@shivaedev/admin": "0.21.1",
62
- "@shivaedev/jobs": "0.40.0",
63
- "@shivaedev/quality": "0.66.0",
64
- "@shivaedev/rate-limit": "0.6.1",
61
+ "@shivaedev/admin": "0.22.1",
62
+ "@shivaedev/jobs": "0.40.1",
63
+ "@shivaedev/quality": "0.67.3",
64
+ "@shivaedev/rate-limit": "0.6.2",
65
65
  "@shivaedev/service": "0.8.0",
66
- "@shivaedev/test-kits": "0.8.1",
67
- "@shivaedev/test-sql": "0.24.1",
68
- "@shivaedev/test-story": "0.42.1",
66
+ "@shivaedev/test-kits": "0.9.2",
67
+ "@shivaedev/test-sql": "0.24.2",
68
+ "@shivaedev/test-story": "0.44.1",
69
69
  "@types/node": "24.19.2",
70
70
  "better-auth": "1.7.14",
71
71
  "effect": "4.1.0",
@@ -77,7 +77,7 @@
77
77
  "@effect/platform-node": "4.1.0",
78
78
  "@effect/sql-pg": "4.1.0",
79
79
  "@effect/vitest": "4.1.0",
80
- "@shivaedev/admin": "0.21.1",
80
+ "@shivaedev/admin": "0.22.1",
81
81
  "better-auth": "1.7.14",
82
82
  "effect": "4.1.0"
83
83
  },
@@ -48,27 +48,23 @@ export const unixHttpServer = Effect.fn("Server.unixHttpServer")(function* (path
48
48
  yield* fs.chmod(pending, 0o600);
49
49
  // Unpublish before Node closes its private bind path.
50
50
  yield* Effect.acquireRelease(fs.rename(pending, path), () => fs.remove(path, { force: true }).pipe(Effect.orDie)).pipe(Scope.provide(scope));
51
- return withUnixRequests({ ...server, address: NetAddress.unixPathAddress(path) }, node, options);
51
+ const published = { ...server, address: NetAddress.unixPathAddress(path) };
52
+ function beginCloseTimeout() {
53
+ const deadline = setTimeout(
54
+ () => node.closeAllConnections(),
55
+ Duration.toMillis(Duration.fromInputUnsafe(options.gracefulShutdownTimeout ?? "20 seconds")),
56
+ );
57
+ node.once("close", () => clearTimeout(deadline));
58
+ }
59
+ return HttpServer.make({
60
+ address: published.address,
61
+ serve: (handler, middleware) =>
62
+ Effect.gen(function* () {
63
+ const unix = handler.pipe(Effect.provideService(UnixSocketRequest, true));
64
+ yield* middleware === undefined ? published.serve(unix) : published.serve(unix, middleware);
65
+ yield* Effect.addFinalizer(() => Effect.sync(beginCloseTimeout));
66
+ }),
67
+ });
52
68
  }),
53
69
  );
54
70
  });
55
-
56
- function withUnixRequests(server: HttpServer.HttpServer["Service"], node: ReturnType<typeof createServer>, options: NodeHttpServer.Options) {
57
- return HttpServer.make({
58
- address: server.address,
59
- serve: (handler, middleware) =>
60
- Effect.gen(function* () {
61
- const unix = handler.pipe(Effect.provideService(UnixSocketRequest, true));
62
- yield* middleware === undefined ? server.serve(unix) : server.serve(unix, middleware);
63
- yield* Effect.addFinalizer(() =>
64
- Effect.sync(() => {
65
- const deadline = setTimeout(
66
- () => node.closeAllConnections(),
67
- Duration.toMillis(Duration.fromInputUnsafe(options.gracefulShutdownTimeout ?? "20 seconds")),
68
- );
69
- node.once("close", () => clearTimeout(deadline));
70
- }),
71
- );
72
- }),
73
- });
74
- }
@@ -53,25 +53,29 @@ const receiveReport = Effect.fnUntraced(function* (options: BrowserErrorOptions,
53
53
  return HttpServerResponse.empty({ status: HttpStatus.fromLiteral("Accepted") });
54
54
  });
55
55
 
56
- const receiveForSession = Effect.fnUntraced(function* (options: BrowserErrorOptions, policy: Option.Option<SessionPolicy["Service"]>) {
57
- if (!(options.requireSession || options.includeUserId)) {
58
- return yield* receiveReport(options);
59
- }
60
- const request = yield* HttpServerRequest.HttpServerRequest;
61
- const session = Option.isSome(policy)
62
- ? yield* resolveSession(request.headers, "$browserError").pipe(Effect.provideService(SessionPolicy, policy.value))
63
- : Option.none();
64
- if (options.requireSession && Option.isNone(session)) {
65
- return HttpServerResponse.empty({ status: HttpStatus.fromLiteral("Unauthorized") });
66
- }
67
- return yield* receiveReport(options, options.includeUserId && Option.isSome(session) ? session.value.user.id : undefined);
68
- });
69
-
70
56
  export function browserErrorRoute(trustedProxy?: string, options: BrowserErrorOptions = {}) {
71
57
  return HttpRouter.use((router) =>
72
58
  Effect.gen(function* () {
73
59
  const limiter = yield* RateLimiter.RateLimiter;
74
60
  const policy = yield* Effect.serviceOption(SessionPolicy);
61
+ const receiveForSession = Effect.fnUntraced(function* () {
62
+ if (!(options.requireSession || options.includeUserId)) {
63
+ return yield* receiveReport(options);
64
+ }
65
+ const request = yield* HttpServerRequest.HttpServerRequest;
66
+ const session = yield* Option.match(policy, {
67
+ onNone: () => Effect.succeed(Option.none()),
68
+ onSome: (configured) => resolveSession(request.headers, "$browserError").pipe(Effect.provideService(SessionPolicy, configured)),
69
+ });
70
+ if (options.requireSession && Option.isNone(session)) {
71
+ return HttpServerResponse.empty({ status: HttpStatus.fromLiteral("Unauthorized") });
72
+ }
73
+ return yield* receiveReport(
74
+ options,
75
+ options.includeUserId ? Option.getOrUndefined(Option.map(session, (current) => current.user.id)) : undefined,
76
+ );
77
+ });
78
+
75
79
  const allowed = localTransport(trustedProxy);
76
80
  const trusted = trustedProxyPeer(trustedProxy);
77
81
  yield* router.add(
@@ -88,7 +92,7 @@ export function browserErrorRoute(trustedProxy?: string, options: BrowserErrorOp
88
92
  if (!accepted) {
89
93
  return HttpServerResponse.empty({ status: HttpStatus.fromLiteral("TooManyRequests") });
90
94
  }
91
- return yield* receiveForSession(options, policy);
95
+ return yield* receiveForSession();
92
96
  }).pipe(
93
97
  Effect.catchIf(isAuthUnavailable, () => Effect.succeed(HttpServerResponse.empty({ status: HttpStatus.fromLiteral("ServiceUnavailable") }))),
94
98
  Effect.catchIf(isForbidden, () => Effect.succeed(HttpServerResponse.empty({ status: HttpStatus.fromLiteral("Forbidden") }))),
@@ -2,6 +2,7 @@ import { Context, Effect, Layer, Option, Stream } from "effect";
2
2
  import { Headers } from "effect/http";
3
3
  import type { Rpc, RpcGroup } from "effect/rpc";
4
4
  import { changesHandlerLayer } from "@shivaedev/contract/changesHandlerLayer.ts";
5
+ import { compareQueries } from "@shivaedev/contract/compareQueries.ts";
5
6
  import { LiveServer } from "@shivaedev/contract/live-server/service.ts";
6
7
  import { subscribe as subscribeQueries } from "@shivaedev/contract/live-server/subscribe.ts";
7
8
  import { CurrentViewer, type Viewer } from "@shivaedev/contract/readPolicy.ts";
@@ -18,74 +19,68 @@ export function hostChanges<R extends Rpc.Any>(
18
19
  ): Layer.Layer<
19
20
  Rpc.ToHandler<Extract<R, { readonly _tag: `${string}.$changes` }>>,
20
21
  never,
21
- Rpc.ExtractRequires<Extract<R, { readonly _tag: `${string}.$changes` }>, `${string}.$changes`>
22
+ | Rpc.ExtractRequires<Extract<R, { readonly _tag: `${string}.$changes` }>, `${string}.$changes`>
23
+ | Rpc.ToHandler<Exclude<R, { readonly _tag: `${string}.$changes` }>>
22
24
  >;
23
25
  export function hostChanges(group: RpcGroup.RpcGroup<Rpc.Any>) {
24
- return Layer.unwrap(
25
- Effect.gen(function* () {
26
- const changes = yield* Effect.serviceOption(LiveServer);
27
- const sessions = yield* Effect.serviceOption(SessionPolicy);
28
- const retained: Layer.Layer<Rpc.Handler<string>>[] = [];
29
- if (Option.isNone(changes)) {
30
- for (const rpc of group.requests.values()) {
31
- if (!rpc._tag.endsWith(".$changes")) {
32
- continue;
33
- }
34
- const key = Context.Service<Rpc.Handler<string>>(rpc.key);
35
- const provided = yield* Effect.serviceOption(key);
36
- if (Option.isSome(provided)) {
37
- retained.push(Layer.succeed(key, provided.value));
38
- }
39
- }
40
- }
41
- const hosted = changesHandlerLayer(
42
- group,
43
- (rpc) =>
44
- ({ queries }: { readonly queries: readonly QueryReference[] }, options: Parameters<Rpc.Handler<string>["handler"]>[1]) =>
45
- subscribe(group, changes, sessions, rpc, queries, options),
46
- );
47
- return Layer.mergeAll(hosted, ...retained);
48
- }),
49
- );
26
+ return Layer.unwrap(initializeHostChanges(group));
50
27
  }
51
28
 
52
- function subscribe(
53
- group: RpcGroup.RpcGroup<Rpc.Any>,
54
- changes: Option.Option<Context.Service.Shape<typeof LiveServer>>,
55
- sessions: Option.Option<typeof SessionPolicy.Service>,
56
- rpc: Rpc.AnyWithProps,
57
- queries: readonly QueryReference[],
58
- options: Parameters<Rpc.Handler<string>["handler"]>[1],
59
- ) {
60
- return Stream.unwrap(
61
- Effect.gen(function* () {
62
- const subscription = yield* resolveChanges(rpc, queries);
63
- const viewer = yield* CurrentViewer;
64
- const refresh = refreshSession(sessions, viewer, rpc._tag);
65
- const read = rerunQuery(group, options);
66
- type Failure = Effect.Error<typeof subscription.authorized | typeof refresh | ReturnType<typeof read>>;
67
- const stream = Option.isSome(changes)
68
- ? Stream.unwrap(
69
- subscribeQueries<Failure, Effect.Services<ReturnType<typeof read>>, typeof read>({ ...subscription, refresh }, read).pipe(
70
- Effect.provideService(LiveServer, changes.value),
71
- ),
72
- )
73
- : Stream.concat(Stream.succeed({ _tag: "Resync" } as const), Stream.never);
74
- if (Option.isNone(sessions) || Option.isNone(viewer)) {
75
- return stream;
76
- }
77
- const revalidation = Effect.never.pipe(
78
- revalidateStream(rpc, viewer.value.id, recheckSession(Headers.empty, rpc._tag)),
79
- Effect.provideService(SessionPolicy, sessions.value),
80
- );
81
- return Stream.interruptWhen(stream, revalidation);
82
- }),
83
- );
84
- }
29
+ const initializeHostChanges = Effect.fnUntraced(function* (group: RpcGroup.RpcGroup<Rpc.Any>) {
30
+ const changes = yield* Effect.serviceOption(LiveServer);
31
+ const sessions = yield* Effect.serviceOption(SessionPolicy);
32
+ function subscribe(rpc: Rpc.AnyWithProps, queries: readonly QueryReference[], options: Parameters<Rpc.Handler<string>["handler"]>[1]) {
33
+ return Stream.unwrap(
34
+ Effect.gen(function* () {
35
+ const subscription = yield* resolveChanges(rpc, queries);
36
+ const viewer = yield* CurrentViewer;
37
+ const refresh = refreshSession(viewer, rpc._tag);
38
+ const read = rerunQuery(group, options);
39
+ type Failure = Effect.Error<typeof subscription.authorized | typeof refresh | ReturnType<typeof read>>;
40
+ const pending = subscribeQueries<Failure, Effect.Services<ReturnType<typeof read>>, typeof read>({ ...subscription, refresh }, read);
41
+ const stream = Option.isSome(changes)
42
+ ? Stream.unwrap(pending.pipe(Effect.provideService(LiveServer, changes.value)))
43
+ : Stream.concat(
44
+ Stream.fromEffect(compareQueries(subscription, read)({ _tag: "Resync" })).pipe(Stream.flatMap(Stream.fromIterable)),
45
+ Stream.never,
46
+ );
47
+ if (Option.isNone(sessions) || Option.isNone(viewer)) {
48
+ return stream;
49
+ }
50
+ const revalidation = Effect.never.pipe(
51
+ revalidateStream(rpc, viewer.value.id, recheckSession(Headers.empty, rpc._tag)),
52
+ Effect.provideService(SessionPolicy, sessions.value),
53
+ );
54
+ return Stream.interruptWhen(stream, revalidation);
55
+ }),
56
+ );
57
+ }
85
58
 
86
- function refreshSession(sessions: Option.Option<typeof SessionPolicy.Service>, viewer: Option.Option<Viewer>, tag: string) {
87
- if (Option.isNone(sessions) || Option.isNone(viewer)) {
88
- return Effect.context<never>();
59
+ function refreshSession(viewer: Option.Option<Viewer>, tag: string) {
60
+ if (Option.isNone(sessions) || Option.isNone(viewer)) {
61
+ return Effect.context<never>();
62
+ }
63
+ return currentSessionContext(viewer.value.id, recheckSession(Headers.empty, tag)).pipe(Effect.provideService(SessionPolicy, sessions.value));
89
64
  }
90
- return currentSessionContext(viewer.value.id, recheckSession(Headers.empty, tag)).pipe(Effect.provideService(SessionPolicy, sessions.value));
91
- }
65
+
66
+ const retained: Layer.Layer<Rpc.Handler<string>>[] = [];
67
+ if (Option.isNone(changes)) {
68
+ for (const rpc of group.requests.values()) {
69
+ if (!rpc._tag.endsWith(".$changes")) {
70
+ continue;
71
+ }
72
+ const key = Context.Service<Rpc.Handler<string>>(rpc.key);
73
+ const provided = yield* Effect.serviceOption(key);
74
+ if (Option.isSome(provided)) {
75
+ retained.push(Layer.succeed(key, provided.value));
76
+ }
77
+ }
78
+ }
79
+ const hosted = changesHandlerLayer(
80
+ group,
81
+ (rpc) =>
82
+ ({ queries }: { readonly queries: readonly QueryReference[] }, options: Parameters<Rpc.Handler<string>["handler"]>[1]) =>
83
+ subscribe(rpc, queries, options),
84
+ );
85
+ return Layer.mergeAll(hosted, ...retained);
86
+ });