@shivaedev/server 0.17.0 → 0.19.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.
Files changed (95) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +59 -2
  3. package/dist/AppModule.d.ts +22 -0
  4. package/dist/AppModule.d.ts.map +1 -0
  5. package/dist/AppModule.js +2 -0
  6. package/dist/AppModule.js.map +1 -0
  7. package/dist/DuplicateModuleQueue.d.ts +11 -0
  8. package/dist/DuplicateModuleQueue.d.ts.map +1 -0
  9. package/dist/DuplicateModuleQueue.js +11 -0
  10. package/dist/DuplicateModuleQueue.js.map +1 -0
  11. package/dist/adapters/boundedOtlpResponse.d.ts +4 -0
  12. package/dist/adapters/boundedOtlpResponse.d.ts.map +1 -0
  13. package/dist/adapters/boundedOtlpResponse.js +19 -0
  14. package/dist/adapters/boundedOtlpResponse.js.map +1 -0
  15. package/dist/appDatabase.d.ts +1 -1
  16. package/dist/appDatabase.d.ts.map +1 -1
  17. package/dist/appDatabase.js +4 -3
  18. package/dist/appDatabase.js.map +1 -1
  19. package/dist/appHostHttp.d.ts +2 -2
  20. package/dist/appHostHttp.d.ts.map +1 -1
  21. package/dist/appHostHttp.js +1 -1
  22. package/dist/appHostHttp.js.map +1 -1
  23. package/dist/appModules.d.ts +37 -0
  24. package/dist/appModules.d.ts.map +1 -0
  25. package/dist/appModules.js +37 -0
  26. package/dist/appModules.js.map +1 -0
  27. package/dist/browserErrorRoute.d.ts +6 -1
  28. package/dist/browserErrorRoute.d.ts.map +1 -1
  29. package/dist/browserErrorRoute.js +39 -9
  30. package/dist/browserErrorRoute.js.map +1 -1
  31. package/dist/hostChanges.d.ts.map +1 -1
  32. package/dist/hostChanges.js +8 -11
  33. package/dist/hostChanges.js.map +1 -1
  34. package/dist/hostOptions.d.ts +2 -0
  35. package/dist/hostOptions.d.ts.map +1 -1
  36. package/dist/hostRpcRoutes.js +1 -1
  37. package/dist/hostRpcRoutes.js.map +1 -1
  38. package/dist/hostTransport.js +1 -1
  39. package/dist/hostTransport.js.map +1 -1
  40. package/dist/nativeClientOrigins.js +1 -1
  41. package/dist/nativeClientOrigins.js.map +1 -1
  42. package/dist/otlpHttpClient.d.ts.map +1 -1
  43. package/dist/otlpHttpClient.js +2 -1
  44. package/dist/otlpHttpClient.js.map +1 -1
  45. package/dist/otlpTracing.d.ts.map +1 -1
  46. package/dist/otlpTracing.js +7 -4
  47. package/dist/otlpTracing.js.map +1 -1
  48. package/dist/socketRpc.js +1 -1
  49. package/dist/socketRpc.js.map +1 -1
  50. package/dist/testing/HostProcessError.d.ts +10 -0
  51. package/dist/testing/HostProcessError.d.ts.map +1 -0
  52. package/dist/testing/HostProcessError.js +4 -0
  53. package/dist/testing/HostProcessError.js.map +1 -0
  54. package/dist/testing/adapters/hostProcess.d.ts +21 -0
  55. package/dist/testing/adapters/hostProcess.d.ts.map +1 -0
  56. package/dist/testing/adapters/hostProcess.js +81 -0
  57. package/dist/testing/adapters/hostProcess.js.map +1 -0
  58. package/dist/testing/hostProcess.d.ts +20 -0
  59. package/dist/testing/hostProcess.d.ts.map +1 -0
  60. package/dist/testing/hostProcess.js +31 -0
  61. package/dist/testing/hostProcess.js.map +1 -0
  62. package/dist/testing/hostProcessChild.d.ts +6 -0
  63. package/dist/testing/hostProcessChild.d.ts.map +1 -0
  64. package/dist/testing/hostProcessChild.js +16 -0
  65. package/dist/testing/hostProcessChild.js.map +1 -0
  66. package/dist/testing/hostProcessProtocol.d.ts +11 -0
  67. package/dist/testing/hostProcessProtocol.d.ts.map +1 -0
  68. package/dist/testing/hostProcessProtocol.js +4 -0
  69. package/dist/testing/hostProcessProtocol.js.map +1 -0
  70. package/dist/workerHost.d.ts +7 -0
  71. package/dist/workerHost.d.ts.map +1 -0
  72. package/dist/workerHost.js +7 -0
  73. package/dist/workerHost.js.map +1 -0
  74. package/package.json +20 -15
  75. package/src/AppModule.ts +19 -0
  76. package/src/DuplicateModuleQueue.ts +11 -0
  77. package/src/adapters/boundedOtlpResponse.ts +27 -0
  78. package/src/appDatabase.ts +4 -3
  79. package/src/appHostHttp.ts +7 -1
  80. package/src/appModules.ts +99 -0
  81. package/src/browserErrorRoute.ts +52 -9
  82. package/src/hostChanges.ts +8 -11
  83. package/src/hostOptions.ts +2 -0
  84. package/src/hostRpcRoutes.ts +1 -1
  85. package/src/hostTransport.ts +1 -1
  86. package/src/nativeClientOrigins.ts +1 -1
  87. package/src/otlpHttpClient.ts +2 -1
  88. package/src/otlpTracing.ts +12 -11
  89. package/src/socketRpc.ts +1 -1
  90. package/src/testing/HostProcessError.ts +6 -0
  91. package/src/testing/adapters/hostProcess.ts +90 -0
  92. package/src/testing/hostProcess.ts +36 -0
  93. package/src/testing/hostProcessChild.ts +21 -0
  94. package/src/testing/hostProcessProtocol.ts +4 -0
  95. package/src/workerHost.ts +13 -0
@@ -0,0 +1,16 @@
1
+ import process from "node:process";
2
+ import { Effect } from "effect";
3
+ import { HttpServer } from "effect/http";
4
+ import { sendHostMessage } from "#testing/adapters/hostProcess.ts";
5
+ import { HostProcessError } from "./HostProcessError.js";
6
+ export const reportHostReady = HttpServer.HttpServer.pipe(Effect.flatMap((server) => Effect.tryPromise({
7
+ catch: (cause) => new HostProcessError({ cause, operation: "launch" }),
8
+ try: () => sendHostMessage({ pid: process.pid, type: "host-ready", url: HttpServer.formatAddress(server.address) }),
9
+ })));
10
+ export function acknowledgeHostSignal(signal) {
11
+ return Effect.tryPromise({
12
+ catch: (cause) => new HostProcessError({ cause, operation: "signal" }),
13
+ try: () => sendHostMessage({ signal, type: "host-signal" }),
14
+ });
15
+ }
16
+ //# sourceMappingURL=hostProcessChild.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hostProcessChild.js","sourceRoot":"","sources":["../../src/testing/hostProcessChild.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,cAAc,CAAC;AACnC,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AACnE,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAEzD,MAAM,CAAC,MAAM,eAAe,GAAG,UAAU,CAAC,UAAU,CAAC,IAAI,CACxD,MAAM,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,EAAE,CACzB,MAAM,CAAC,UAAU,CAAC;IACjB,KAAK,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,IAAI,gBAAgB,CAAC,EAAE,KAAK,EAAE,SAAS,EAAE,QAAQ,EAAE,CAAC;IACtE,GAAG,EAAE,GAAG,EAAE,CAAC,eAAe,CAAC,EAAE,GAAG,EAAE,OAAO,CAAC,GAAG,EAAE,IAAI,EAAE,YAAY,EAAE,GAAG,EAAE,UAAU,CAAC,aAAa,CAAC,MAAM,CAAC,OAAO,CAAC,EAAE,CAAC;CACnH,CAAC,CACF,CACD,CAAC;AAEF,MAAM,UAAU,qBAAqB,CAAC,MAAsB;IAC3D,OAAO,MAAM,CAAC,UAAU,CAAC;QACxB,KAAK,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,IAAI,gBAAgB,CAAC,EAAE,KAAK,EAAE,SAAS,EAAE,QAAQ,EAAE,CAAC;QACtE,GAAG,EAAE,GAAG,EAAE,CAAC,eAAe,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,aAAa,EAAE,CAAC;KAC3D,CAAC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,11 @@
1
+ import { Schema } from "effect";
2
+ export declare const HostReady: Schema.Struct<{
3
+ readonly pid: Schema.Number;
4
+ readonly type: Schema.Literal<"host-ready">;
5
+ readonly url: Schema.String;
6
+ }>;
7
+ export declare const HostSignal: Schema.Struct<{
8
+ readonly signal: Schema.String;
9
+ readonly type: Schema.Literal<"host-signal">;
10
+ }>;
11
+ //# sourceMappingURL=hostProcessProtocol.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hostProcessProtocol.d.ts","sourceRoot":"","sources":["../../src/testing/hostProcessProtocol.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEhC,eAAO,MAAM,SAAS;;;;EAAgG,CAAC;AACvH,eAAO,MAAM,UAAU;;;EAAgF,CAAC"}
@@ -0,0 +1,4 @@
1
+ import { Schema } from "effect";
2
+ export const HostReady = Schema.Struct({ pid: Schema.Number, type: Schema.Literal("host-ready"), url: Schema.String });
3
+ export const HostSignal = Schema.Struct({ signal: Schema.String, type: Schema.Literal("host-signal") });
4
+ //# sourceMappingURL=hostProcessProtocol.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hostProcessProtocol.js","sourceRoot":"","sources":["../../src/testing/hostProcessProtocol.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEhC,MAAM,CAAC,MAAM,SAAS,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,OAAO,CAAC,YAAY,CAAC,EAAE,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC;AACvH,MAAM,CAAC,MAAM,UAAU,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,OAAO,CAAC,aAAa,CAAC,EAAE,CAAC,CAAC"}
@@ -0,0 +1,7 @@
1
+ import { Layer } from "effect";
2
+ import type { AppDatabaseOptions } from "#appHost.ts";
3
+ export declare function workerHost<R, E, TRequirements, TServices, TServiceError, TServiceRequirements, TMigrations = never, TMigrationError = never>(options: AppDatabaseOptions<TMigrations, TMigrationError> & {
4
+ readonly workers: Layer.Layer<R, E, TRequirements>;
5
+ readonly services: Layer.Layer<TServices, TServiceError, TServiceRequirements>;
6
+ }): Layer.Layer<"@shivaedev/contract/LiveServer" | R | TServices | import("@effect/sql-pg/PgClient").PgClient | import("@effect/sql-pg/PgPool").PgPool | import("effect/reactivity/Reactivity").Reactivity | import("effect/sql/SqlClient").SqlClient, E | TMigrationError | TServiceError | import("effect/Config").ConfigError | import("effect/sql/Migrator").MigrationError | import("@shivaedev/sql/PostgresListenerError.ts").PostgresListenerError | import("effect/Schema").SchemaError | import("effect/sql/SqlError").SqlError, Exclude<Exclude<TServiceRequirements, "@shivaedev/contract/LiveServer" | import("@effect/sql-pg/PgClient").PgClient | import("@effect/sql-pg/PgPool").PgPool | import("effect/reactivity/Reactivity").Reactivity | import("effect/sql/SqlClient").SqlClient>, import("effect/Crypto").Crypto> | Exclude<Exclude<Exclude<TMigrations, import("effect/Scope").Scope>, "@shivaedev/contract/LiveServer" | import("@effect/sql-pg/PgClient").PgClient | import("@effect/sql-pg/PgPool").PgPool | import("effect/reactivity/Reactivity").Reactivity | import("effect/sql/SqlClient").SqlClient>, import("effect/Crypto").Crypto> | Exclude<Exclude<Exclude<TRequirements, TServices>, "@shivaedev/contract/LiveServer" | import("@effect/sql-pg/PgClient").PgClient | import("@effect/sql-pg/PgPool").PgPool | import("effect/reactivity/Reactivity").Reactivity | import("effect/sql/SqlClient").SqlClient>, import("effect/Crypto").Crypto>>;
7
+ //# sourceMappingURL=workerHost.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"workerHost.d.ts","sourceRoot":"","sources":["../src/workerHost.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,EAAE,MAAM,QAAQ,CAAC;AAE/B,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAEtD,wBAAgB,UAAU,CAAC,CAAC,EAAE,CAAC,EAAE,aAAa,EAAE,SAAS,EAAE,aAAa,EAAE,oBAAoB,EAAE,WAAW,GAAG,KAAK,EAAE,eAAe,GAAG,KAAK,EAC3I,OAAO,EAAE,kBAAkB,CAAC,WAAW,EAAE,eAAe,CAAC,GAAG;IAC3D,QAAQ,CAAC,OAAO,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,EAAE,aAAa,CAAC,CAAC;IACnD,QAAQ,CAAC,QAAQ,EAAE,KAAK,CAAC,KAAK,CAAC,SAAS,EAAE,aAAa,EAAE,oBAAoB,CAAC,CAAC;CAC/E,m5CAGD"}
@@ -0,0 +1,7 @@
1
+ import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2
+ import { Layer } from "effect";
3
+ import { appDatabase } from "#appDatabase.ts";
4
+ export function workerHost(options) {
5
+ return options.workers.pipe(Layer.provideMerge(options.services), Layer.provideMerge(appDatabase(options)), Layer.provide(NodeCrypto.layer));
6
+ }
7
+ //# sourceMappingURL=workerHost.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"workerHost.js","sourceRoot":"","sources":["../src/workerHost.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,UAAU,MAAM,kCAAkC,CAAC;AAC/D,OAAO,EAAE,KAAK,EAAE,MAAM,QAAQ,CAAC;AAC/B,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAG9C,MAAM,UAAU,UAAU,CACzB,OAGC;IAED,OAAO,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE,KAAK,CAAC,YAAY,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC,EAAE,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC;AAC9I,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shivaedev/server",
3
- "version": "0.17.0",
3
+ "version": "0.19.0",
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"
@@ -45,25 +45,26 @@
45
45
  "README.md"
46
46
  ],
47
47
  "dependencies": {
48
- "@shivaedev/changes": "0.6.0",
49
- "@shivaedev/contract": "0.30.1",
50
- "@shivaedev/errors": "0.4.1",
51
- "@shivaedev/http": "0.3.1",
52
- "@shivaedev/identity": "0.17.0",
53
- "@shivaedev/local-postgres": "0.8.0",
54
- "@shivaedev/sql": "0.31.0"
48
+ "@shivaedev/changes": "0.8.0",
49
+ "@shivaedev/contract": "0.31.0",
50
+ "@shivaedev/errors": "0.5.0",
51
+ "@shivaedev/http": "0.4.0",
52
+ "@shivaedev/identity": "0.19.0",
53
+ "@shivaedev/local-postgres": "0.10.0",
54
+ "@shivaedev/sql": "0.33.0"
55
55
  },
56
56
  "devDependencies": {
57
57
  "@effect/platform-node": "4.0.6",
58
58
  "@effect/sql-pg": "4.0.6",
59
59
  "@effect/vitest": "4.0.6",
60
- "@shivaedev/access": "0.3.5",
61
- "@shivaedev/admin": "0.17.0",
62
- "@shivaedev/jobs": "0.29.1",
63
- "@shivaedev/quality": "0.54.0",
64
- "@shivaedev/test": "0.12.0",
65
- "@shivaedev/test-sql": "0.16.0",
66
- "@shivaedev/test-story": "0.32.0",
60
+ "@shivaedev/access": "0.3.6",
61
+ "@shivaedev/admin": "0.18.1",
62
+ "@shivaedev/jobs": "0.30.0",
63
+ "@shivaedev/quality": "0.56.0",
64
+ "@shivaedev/rate-limit": "0.2.1",
65
+ "@shivaedev/test": "0.13.0",
66
+ "@shivaedev/test-sql": "0.16.2",
67
+ "@shivaedev/test-story": "0.34.0",
67
68
  "@types/node": "24.19.2",
68
69
  "better-auth": "1.7.12",
69
70
  "effect": "4.0.6",
@@ -75,6 +76,7 @@
75
76
  "@effect/platform-node": "4.0.6",
76
77
  "@effect/sql-pg": "4.0.6",
77
78
  "@effect/vitest": "4.0.6",
79
+ "@shivaedev/admin": "0.18.1",
78
80
  "better-auth": "1.7.12",
79
81
  "effect": "4.0.6"
80
82
  },
@@ -88,6 +90,9 @@
88
90
  "@effect/vitest": {
89
91
  "optional": true
90
92
  },
93
+ "@shivaedev/admin": {
94
+ "optional": true
95
+ },
91
96
  "better-auth": {
92
97
  "optional": true
93
98
  }
@@ -0,0 +1,19 @@
1
+ import type { Layer, Pipeable } from "effect";
2
+ import type { RpcGroup } from "effect/rpc";
3
+ import type { AnyAdminRegistry } from "@shivaedev/admin/registry.ts";
4
+ import type { MigrationOptions } from "#MigrationOptions.ts";
5
+
6
+ export type ModuleLayer = Layer.Any & Pipeable.Pipeable;
7
+ export type ModuleAdmin = AnyAdminRegistry & { readonly handlers: ModuleLayer };
8
+
9
+ export interface AppModule {
10
+ readonly admin?: ModuleAdmin;
11
+ readonly group: RpcGroup.Any;
12
+ readonly handlers: ModuleLayer;
13
+ readonly migrations: Pick<MigrationOptions<unknown, unknown>, "loader" | "components">;
14
+ readonly name: string;
15
+ readonly ports?: ModuleLayer;
16
+ readonly queues?: readonly { readonly name: string }[];
17
+ readonly services: ModuleLayer;
18
+ readonly workers?: ModuleLayer;
19
+ }
@@ -0,0 +1,11 @@
1
+ import { Schema } from "effect";
2
+
3
+ export class DuplicateModuleQueue extends Schema.TaggedError<DuplicateModuleQueue>()("DuplicateModuleQueue", {
4
+ firstModule: Schema.String,
5
+ queue: Schema.String,
6
+ secondModule: Schema.String,
7
+ }) {
8
+ override get message() {
9
+ return `Queue "${this.queue}" is declared by both "${this.firstModule}" and "${this.secondModule}".`;
10
+ }
11
+ }
@@ -0,0 +1,27 @@
1
+ import { Effect } from "effect";
2
+ import { HttpClientError, HttpClientResponse } from "effect/http";
3
+ import { readBoundedBody } from "@shivaedev/http/body.ts";
4
+
5
+ const responseLimit = 64 * 1024;
6
+
7
+ export const boundedOtlpResponse = Effect.fnUntraced(function* (response: HttpClientResponse.HttpClientResponse) {
8
+ const bytes = yield* readBoundedBody(response, responseLimit).pipe(
9
+ Effect.mapError((error) =>
10
+ HttpClientError.isHttpClientError(error)
11
+ ? error
12
+ : new HttpClientError.HttpClientError({
13
+ reason: new HttpClientError.DecodeError({
14
+ description: `OTLP collector response exceeds ${responseLimit} bytes`,
15
+ request: response.request,
16
+ response,
17
+ }),
18
+ }),
19
+ ),
20
+ );
21
+ const buffered = HttpClientResponse.fromWeb(
22
+ response.request,
23
+ new Response(bytes.byteLength === 0 ? null : bytes, { headers: response.headers, status: response.status }),
24
+ );
25
+ yield* buffered.arrayBuffer;
26
+ return buffered;
27
+ });
@@ -32,16 +32,15 @@ export function appDatabase<R, E = never>(options: AppDatabaseOptions<R, E>) {
32
32
  postgresLayer(url, config).pipe(Layer.provide(clock)),
33
33
  ),
34
34
  );
35
- const prepared = Layer.effectDiscard(prepareMigrations(options.migrations)).pipe(Layer.provideMerge(pool));
36
35
  const live = LiveServer.layer.pipe(Layer.provideMerge(Reactivity.layer));
37
36
  const migrations = options.migrations;
38
37
  const worker =
39
38
  migrations.mode === "wait" && migrations.release !== undefined
40
39
  ? Layer.effect(WorkerRelease, coordinateWorkerRelease(migrations.release, migrations.pollInterval, migrations.table))
41
40
  : Layer.empty;
42
- const base = Layer.merge(worker.pipe(Layer.provideMerge(prepared)), live);
41
+ const base = Layer.merge(pool, live);
43
42
  const changes = options.config?.changes;
44
- return Layer.unwrap(
43
+ const connected = Layer.unwrap(
45
44
  Effect.gen(function* () {
46
45
  const client = yield* PgClient.PgClient;
47
46
  const hints = yield* LiveServer;
@@ -71,6 +70,8 @@ export function appDatabase<R, E = never>(options: AppDatabaseOptions<R, E>) {
71
70
  }).pipe(Layer.provide(clock));
72
71
  }),
73
72
  ).pipe(Layer.provideMerge(base));
73
+ const prepared = Layer.effectDiscard(prepareMigrations(migrations)).pipe(Layer.provideMerge(connected));
74
+ return worker.pipe(Layer.provideMerge(prepared));
74
75
  }
75
76
 
76
77
  function prepareMigrations<R, E>(migrations: AppDatabaseOptions<R, E>["migrations"]) {
@@ -55,7 +55,13 @@ export function appHostHttp<
55
55
  const sessions = Layer.mergeAll(Layer.empty, ...(options.sessions === undefined ? [] : [options.sessions]));
56
56
  const server = nodeHttpServer(host, options.config);
57
57
  const applicationRoutes = hostApplicationRoutes(options.routes, bodySize);
58
- const httpRoutes = Layer.mergeAll(routes, healthRoute, browserErrorRoute(trustedProxy), assets, applicationRoutes).pipe(
58
+ const httpRoutes = Layer.mergeAll(
59
+ routes,
60
+ healthRoute,
61
+ browserErrorRoute(trustedProxy, options.browserErrors),
62
+ assets,
63
+ applicationRoutes,
64
+ ).pipe(
59
65
  Layer.provide(nativeClientOrigins(nativeOrigins, trustedProxy, false, options.rpcPath)),
60
66
  Layer.provide(nativeClientOrigins(nativeOrigins, trustedProxy, options.nativeOrigins === undefined ? "preflight" : true)),
61
67
  );
@@ -0,0 +1,99 @@
1
+ import { Effect, Layer } from "effect";
2
+ import { RpcGroup } from "effect/rpc";
3
+ import type { Migrator } from "effect/sql";
4
+ import type { AdminPage } from "@shivaedev/admin/page.ts";
5
+ import type { AdminRegistry, AnyAdminRegistry } from "@shivaedev/admin/registry.ts";
6
+ import { mergeAdminRegistrations } from "@shivaedev/admin/server/mergeAdminRegistrations.ts";
7
+ import type { SchemaComponent } from "@shivaedev/sql/SchemaComponent.ts";
8
+ import type { AppModule, ModuleAdmin, ModuleLayer } from "#AppModule.ts";
9
+ import { DuplicateModuleQueue } from "#DuplicateModuleQueue.ts";
10
+ import type { MigrationOptions } from "#MigrationOptions.ts";
11
+
12
+ type ModuleField<TModules, TKey extends PropertyKey> = TModules extends unknown ? (TKey extends keyof TModules ? TModules[TKey] : never) : never;
13
+ type Layers<TModules extends readonly AppModule[], TKey extends "handlers" | "services" | "ports" | "workers"> = Extract<
14
+ ModuleField<TModules[number], TKey>,
15
+ Layer.Any
16
+ >;
17
+ type Admin<TModules extends readonly AppModule[]> = Extract<ModuleField<TModules[number], "admin">, ModuleAdmin>;
18
+ type Handlers<TModules extends readonly AppModule[]> = Layers<TModules, "handlers"> | Extract<ModuleField<Admin<TModules>, "handlers">, Layer.Any>;
19
+ type Pages<TModules extends readonly AppModule[]> = Extract<ModuleField<Admin<TModules>, "pages">, readonly AdminPage[]>;
20
+ type Queues<TModules extends readonly AppModule[]> = Extract<ModuleField<TModules[number], "queues">, readonly { readonly name: string }[]>[number];
21
+ type Ports<TModules extends readonly AppModule[]> = Layers<TModules, "ports">;
22
+ type Services<TModules extends readonly AppModule[]> = Layers<TModules, "services">;
23
+ type MigrationRequirements<TModules extends readonly AppModule[]> = Effect.Services<TModules[number]["migrations"]["loader"]>;
24
+ type Components<T> = T extends readonly (infer TComponent extends SchemaComponent<unknown, unknown>)[] ? TComponent : never;
25
+ type ModuleComponents<TModules extends AppModule> = Components<ModuleField<TModules["migrations"], "components">>;
26
+
27
+ export function appModules<const TModules extends readonly AppModule[], R = never, E = never, TRequirements = never>(
28
+ modules: TModules,
29
+ options?: { readonly replacements?: Layer.Layer<R, E, TRequirements> },
30
+ ): Effect.Effect<
31
+ {
32
+ readonly workers: Layer.Layer<
33
+ Layer.Success<Layers<TModules, "workers">>,
34
+ Layer.Error<Layers<TModules, "workers">>,
35
+ Layer.Services<Layers<TModules, "workers">>
36
+ >;
37
+ readonly queues: readonly Queues<TModules>[];
38
+ readonly admin: AdminRegistry<readonly Pages<TModules>[number][]>;
39
+ readonly group: RpcGroup.RpcGroup<RpcGroup.Rpcs<TModules[number]["group"] | ModuleField<Admin<TModules>, "group">>>;
40
+ readonly handlers: Layer.Layer<Layer.Success<Handlers<TModules>>, Layer.Error<Handlers<TModules>>, Layer.Services<Handlers<TModules>>>;
41
+ readonly services: Layer.Layer<
42
+ Layer.Success<Services<TModules> | Ports<TModules>> | R,
43
+ Layer.Error<Services<TModules> | Ports<TModules>> | E,
44
+ Exclude<Layer.Services<Services<TModules>>, Layer.Success<Ports<TModules>> | R> | Layer.Services<Ports<TModules>> | TRequirements
45
+ >;
46
+ readonly migrations: {
47
+ readonly loader: Migrator.Loader<MigrationRequirements<TModules>>;
48
+ readonly components: readonly ModuleComponents<TModules[number]>[];
49
+ };
50
+ },
51
+ DuplicateModuleQueue
52
+ >;
53
+ export function appModules(
54
+ modules: readonly AppModule[],
55
+ options?: { readonly replacements?: ModuleLayer },
56
+ ): Effect.Effect<
57
+ {
58
+ readonly workers: ModuleLayer;
59
+ readonly queues: readonly { readonly name: string }[];
60
+ readonly admin: AnyAdminRegistry;
61
+ readonly group: RpcGroup.Any;
62
+ readonly handlers: ModuleLayer;
63
+ readonly migrations: MigrationOptions<unknown, unknown>;
64
+ readonly services: ModuleLayer;
65
+ },
66
+ DuplicateModuleQueue
67
+ > {
68
+ return composeModules(modules, options);
69
+ }
70
+
71
+ const composeModules = Effect.fnUntraced(function* (modules: readonly AppModule[], options?: { readonly replacements?: ModuleLayer }) {
72
+ const owners = new Map<string, string>();
73
+ for (const module of modules) {
74
+ for (const queue of module.queues ?? []) {
75
+ const firstModule = owners.get(queue.name);
76
+ if (firstModule !== undefined) {
77
+ return yield* new DuplicateModuleQueue({ firstModule, queue: queue.name, secondModule: module.name });
78
+ }
79
+ owners.set(queue.name, module.name);
80
+ }
81
+ }
82
+ const queues = modules.flatMap((module) => module.queues ?? []);
83
+ const registrations = modules.flatMap((module) => (module.admin === undefined ? [] : [module.admin]));
84
+ const admin = mergeAdminRegistrations(...registrations);
85
+ const defaults = Layer.mergeAll(Layer.empty, ...modules.map((module) => module.ports ?? Layer.empty));
86
+ const ports = Layer.merge(defaults, options?.replacements ?? Layer.empty);
87
+ return {
88
+ admin,
89
+ group: RpcGroup.make().merge(...modules.map((module) => module.group), admin.group),
90
+ handlers: Layer.mergeAll(admin.handlers, ...modules.map((module) => module.handlers)),
91
+ migrations: {
92
+ components: modules.flatMap((module) => module.migrations.components ?? []),
93
+ loader: Effect.all(modules.map((module) => module.migrations.loader)).pipe(Effect.map((entries) => entries.flat())),
94
+ },
95
+ queues,
96
+ services: Layer.mergeAll(Layer.empty, ...modules.map((module) => module.services)).pipe(Layer.provideMerge(ports)),
97
+ workers: Layer.mergeAll(Layer.empty, ...modules.map((module) => module.workers ?? Layer.empty)),
98
+ };
99
+ });
@@ -2,7 +2,11 @@ import { ByteSize, Cause, Effect, ErrorReporter, Layer, Option, Schema } from "e
2
2
  import { HttpIncomingMessage, HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http";
3
3
  import * as HttpStatus from "effect/http/HttpStatus";
4
4
  import { RateLimiter } from "effect/persistence";
5
- import { localTransport, trustedProxyPeer } from "@shivaedev/identity/server/local.ts";
5
+ import { redactBrowserText } from "@shivaedev/errors/redactBrowserText.ts";
6
+ import { isAuthUnavailable, isForbidden } from "@shivaedev/errors/taxonomy.ts";
7
+ import { localTransport, trustedProxyPeer } from "@shivaedev/identity/server/adapters/local.ts";
8
+ import { SessionPolicy } from "@shivaedev/identity/server/SessionPolicy.ts";
9
+ import { resolveSession } from "@shivaedev/identity/server/session.ts";
6
10
 
7
11
  const BrowserErrorReport = Schema.Struct({
8
12
  kind: Schema.Literals(["error", "unhandledrejection"]),
@@ -11,7 +15,18 @@ const BrowserErrorReport = Schema.Struct({
11
15
  url: Schema.String,
12
16
  });
13
17
 
14
- const receiveReport = Effect.gen(function* () {
18
+ export interface BrowserErrorOptions {
19
+ readonly includeUserId?: boolean;
20
+ readonly log?: boolean;
21
+ readonly requireSession?: boolean;
22
+ }
23
+
24
+ class BrowserError extends Error {
25
+ override readonly name = "BrowserError";
26
+ override readonly [ErrorReporter.severity] = "Error";
27
+ }
28
+
29
+ const receiveReport = Effect.fnUntraced(function* (options: BrowserErrorOptions, userId?: string) {
15
30
  const parsed = yield* HttpServerRequest.schemaBodyJson(BrowserErrorReport).pipe(
16
31
  Effect.provideService(HttpIncomingMessage.MaxBodySize, ByteSize.kibibytes(16)),
17
32
  Effect.option,
@@ -19,19 +34,44 @@ const receiveReport = Effect.gen(function* () {
19
34
  if (Option.isNone(parsed)) {
20
35
  return HttpServerResponse.empty({ status: HttpStatus.fromLiteral("BadRequest") });
21
36
  }
22
- const error = new Error(parsed.value.message);
23
- error.name = "BrowserError";
37
+ const error = new BrowserError(redactBrowserText(parsed.value.message));
24
38
  if (parsed.value.stack !== undefined) {
25
- error.stack = parsed.value.stack;
39
+ error.stack = redactBrowserText(parsed.value.stack);
40
+ }
41
+ const cause = Cause.die(error);
42
+ if (userId !== undefined) {
43
+ yield* Effect.annotateCurrentSpan("user.id", userId);
26
44
  }
27
- yield* ErrorReporter.report(Cause.die(error)).pipe(Effect.annotateLogs({ "browser.kind": parsed.value.kind, "url.full": parsed.value.url }));
45
+ yield* Effect.gen(function* () {
46
+ yield* ErrorReporter.report(cause);
47
+ if (options.log) {
48
+ yield* Effect.logError("Browser error", cause);
49
+ }
50
+ }).pipe(
51
+ Effect.annotateLogs({ "browser.kind": parsed.value.kind, "url.full": parsed.value.url, ...(userId === undefined ? {} : { "user.id": userId }) }),
52
+ );
28
53
  return HttpServerResponse.empty({ status: HttpStatus.fromLiteral("Accepted") });
29
54
  });
30
55
 
31
- export function browserErrorRoute(trustedProxy?: string) {
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
+ export function browserErrorRoute(trustedProxy?: string, options: BrowserErrorOptions = {}) {
32
71
  return HttpRouter.use((router) =>
33
72
  Effect.gen(function* () {
34
73
  const limiter = yield* RateLimiter.RateLimiter;
74
+ const policy = yield* Effect.serviceOption(SessionPolicy);
35
75
  const allowed = localTransport(trustedProxy);
36
76
  const trusted = trustedProxyPeer(trustedProxy);
37
77
  yield* router.add(
@@ -48,8 +88,11 @@ export function browserErrorRoute(trustedProxy?: string) {
48
88
  if (!accepted) {
49
89
  return HttpServerResponse.empty({ status: HttpStatus.fromLiteral("TooManyRequests") });
50
90
  }
51
- return yield* receiveReport;
52
- }),
91
+ return yield* receiveForSession(options, policy);
92
+ }).pipe(
93
+ Effect.catchIf(isAuthUnavailable, () => Effect.succeed(HttpServerResponse.empty({ status: HttpStatus.fromLiteral("ServiceUnavailable") }))),
94
+ Effect.catchIf(isForbidden, () => Effect.succeed(HttpServerResponse.empty({ status: HttpStatus.fromLiteral("Forbidden") }))),
95
+ ),
53
96
  );
54
97
  }),
55
98
  ).pipe(Layer.provide(RateLimiter.layer.pipe(Layer.provide(RateLimiter.layerStoreMemory))));
@@ -4,7 +4,7 @@ import { Rpc, type RpcGroup } from "effect/rpc";
4
4
  import { LiveServer } from "@shivaedev/contract/LiveServer.ts";
5
5
  import { CurrentViewer, type Viewer } from "@shivaedev/contract/readPolicy.ts";
6
6
  import type { QueryReference } from "@shivaedev/contract/serverMetadata.ts";
7
- import { Unauthorized } from "@shivaedev/errors/taxonomy.ts";
7
+ import { currentSessionContext } from "@shivaedev/identity/server/currentSessionContext.ts";
8
8
  import { recheckSession } from "@shivaedev/identity/server/recheckSession.ts";
9
9
  import { revalidateStream } from "@shivaedev/identity/server/revalidateStream.ts";
10
10
  import { SessionPolicy } from "@shivaedev/identity/server/SessionPolicy.ts";
@@ -23,11 +23,9 @@ export function hostChanges<R extends Rpc.Any>(group: RpcGroup.RpcGroup<R>) {
23
23
  Effect.gen(function* () {
24
24
  const { subscription, context } = yield* resolveChanges(rpc, queries);
25
25
  const viewer = yield* CurrentViewer;
26
- const authorized = Option.isNone(sessions)
27
- ? subscription.authorized
28
- : authorizeSession(rpc._tag, viewer, subscription.authorized).pipe(Effect.provideService(SessionPolicy, sessions.value));
26
+ const refresh = refreshSession(sessions, viewer, rpc._tag);
29
27
  const stream = Option.isSome(changes)
30
- ? Stream.unwrap(changes.value.subscribe({ ...subscription, authorized }, context, rerunQuery(group, options)))
28
+ ? Stream.unwrap(changes.value.subscribe({ ...subscription, refresh }, context, rerunQuery(group, options)))
31
29
  : Stream.concat(Stream.succeed({ _tag: "Resync" } as const), Stream.never);
32
30
  if (Option.isNone(sessions) || Option.isNone(viewer)) {
33
31
  return stream;
@@ -61,10 +59,9 @@ export function hostChanges<R extends Rpc.Any>(group: RpcGroup.RpcGroup<R>) {
61
59
  );
62
60
  }
63
61
 
64
- const authorizeSession = Effect.fnUntraced(function* <E, R>(tag: string, viewer: Option.Option<Viewer>, policy: Effect.Effect<boolean, E, R>) {
65
- const current = yield* recheckSession(Headers.empty, tag);
66
- if (Option.isSome(viewer) && (Option.isNone(current) || current.value.user.id !== viewer.value.id)) {
67
- return yield* new Unauthorized({ message: "Authentication required" });
62
+ function refreshSession(sessions: Option.Option<typeof SessionPolicy.Service>, viewer: Option.Option<Viewer>, tag: string) {
63
+ if (Option.isNone(sessions) || Option.isNone(viewer)) {
64
+ return Effect.context<never>();
68
65
  }
69
- return yield* policy;
70
- });
66
+ return currentSessionContext(viewer.value.id, recheckSession(Headers.empty, tag)).pipe(Effect.provideService(SessionPolicy, sessions.value));
67
+ }
@@ -4,11 +4,13 @@ import type { Rpc, RpcGroup } from "effect/rpc";
4
4
  import type { SessionPolicy } from "@shivaedev/identity/server/SessionPolicy.ts";
5
5
  import type { AssetOptions } from "#AssetOptions.ts";
6
6
  import type { AppDatabaseOptions } from "#appHost.ts";
7
+ import type { BrowserErrorOptions } from "#browserErrorRoute.ts";
7
8
 
8
9
  export type HostRouteRequirements = HttpRouter.HttpRouter | HttpRouter.Request<"Error", unknown>;
9
10
 
10
11
  export type HostCoreOptions<TRpcs extends Rpc.Any, THandlers, THandlerError, THandlerRequirements, TServices, TServiceError, TServiceRequirements> = {
11
12
  readonly assets?: string | AssetOptions;
13
+ readonly browserErrors?: BrowserErrorOptions;
12
14
  readonly config?: AppDatabaseOptions["config"] & {
13
15
  readonly port?: number;
14
16
  readonly host?: string;
@@ -4,7 +4,7 @@ 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";
@@ -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(
@@ -2,6 +2,7 @@ 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
4
  import { filterStatus } from "@shivaedev/http/filterStatus.ts";
5
+ import { boundedOtlpResponse } from "#adapters/boundedOtlpResponse.ts";
5
6
  import { RedactionPolicy } from "#RedactionPolicy.ts";
6
7
 
7
8
  function timeoutError(request: HttpClientRequest.HttpClientRequest) {
@@ -41,7 +42,7 @@ export function otlpHttpClient(timeout = 10_000) {
41
42
  });
42
43
  }
43
44
  return client.pipe(
44
- HttpClient.tap((response) => response.arrayBuffer),
45
+ HttpClient.transformResponse(Effect.flatMap(boundedOtlpResponse)),
45
46
  HttpClient.transform((requestEffect, request) =>
46
47
  requestEffect.pipe(
47
48
  Effect.timeoutOrElse({
@@ -7,19 +7,20 @@ import { redactingDiagnostics } from "#redactingDiagnostics.ts";
7
7
  import { redactingTracer } from "#redactingTracer.ts";
8
8
  import { safeOtlpSerialization } from "#safeOtlpSerialization.ts";
9
9
 
10
+ const endpointUrl = Schema.URL.check(Schema.makeFilter((url) => url.protocol === "http:" || url.protocol === "https:"));
11
+
10
12
  export const otlpTracing: Layer.Layer<never, Config.ConfigError> = Layer.unwrap(
11
13
  Effect.gen(function* () {
12
- const endpoint = yield* Config.URL("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT").pipe(
13
- Config.orElse(() =>
14
- Config.URL("OTEL_EXPORTER_OTLP_ENDPOINT").pipe(
15
- Config.map((url) => {
16
- url.pathname = `${url.pathname.replace(/\/$/u, "")}/v1/traces`;
17
- return url;
18
- }),
19
- ),
20
- ),
21
- Config.withDefault(undefined),
22
- );
14
+ const tracesEndpoint = yield* Config.schema(endpointUrl, "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT").pipe(Config.withDefault(undefined));
15
+ const endpoint =
16
+ tracesEndpoint
17
+ ?? (yield* Config.schema(endpointUrl, "OTEL_EXPORTER_OTLP_ENDPOINT").pipe(
18
+ Config.map((url) => {
19
+ url.pathname = `${url.pathname.replace(/\/$/u, "")}/v1/traces`;
20
+ return url;
21
+ }),
22
+ Config.withDefault(undefined),
23
+ ));
23
24
  if (endpoint === undefined) {
24
25
  return Layer.empty;
25
26
  }
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,6 @@
1
+ import { Data } from "effect";
2
+
3
+ export class HostProcessError extends Data.TaggedError("HostProcessError")<{
4
+ readonly operation: "launch" | "signal" | "request";
5
+ readonly cause: unknown;
6
+ }> {}