@effect-app/infra 4.0.0-beta.16 → 4.0.0-beta.161
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 +1060 -0
- package/dist/CUPS.d.ts +15 -7
- package/dist/CUPS.d.ts.map +1 -1
- package/dist/CUPS.js +10 -12
- package/dist/Emailer/Sendgrid.d.ts +14 -14
- package/dist/Emailer/Sendgrid.d.ts.map +1 -1
- package/dist/Emailer/Sendgrid.js +16 -15
- package/dist/Emailer/fake.d.ts +1 -1
- package/dist/Emailer/service.d.ts +9 -3
- package/dist/Emailer/service.d.ts.map +1 -1
- package/dist/Emailer/service.js +3 -3
- package/dist/Emailer.d.ts +1 -1
- package/dist/MainFiberSet.d.ts +5 -5
- package/dist/MainFiberSet.d.ts.map +1 -1
- package/dist/MainFiberSet.js +3 -3
- package/dist/Model/Repository/Registry.d.ts +20 -0
- package/dist/Model/Repository/Registry.d.ts.map +1 -0
- package/dist/Model/Repository/Registry.js +17 -0
- package/dist/Model/Repository/ext.d.ts +33 -15
- package/dist/Model/Repository/ext.d.ts.map +1 -1
- package/dist/Model/Repository/ext.js +54 -2
- package/dist/Model/Repository/internal/internal.d.ts +6 -6
- package/dist/Model/Repository/internal/internal.d.ts.map +1 -1
- package/dist/Model/Repository/internal/internal.js +43 -32
- package/dist/Model/Repository/legacy.d.ts +1 -1
- package/dist/Model/Repository/makeRepo.d.ts +7 -6
- package/dist/Model/Repository/makeRepo.d.ts.map +1 -1
- package/dist/Model/Repository/makeRepo.js +5 -1
- package/dist/Model/Repository/service.d.ts +28 -23
- package/dist/Model/Repository/service.d.ts.map +1 -1
- package/dist/Model/Repository/validation.d.ts +142 -17
- package/dist/Model/Repository/validation.d.ts.map +1 -1
- package/dist/Model/Repository/validation.js +5 -5
- package/dist/Model/Repository.d.ts +2 -1
- package/dist/Model/Repository.d.ts.map +1 -1
- package/dist/Model/Repository.js +2 -1
- package/dist/Model/dsl.d.ts +4 -4
- package/dist/Model/dsl.d.ts.map +1 -1
- package/dist/Model/filter/filterApi.d.ts +5 -5
- package/dist/Model/filter/filterApi.d.ts.map +1 -1
- package/dist/Model/filter/types/errors.d.ts +1 -1
- package/dist/Model/filter/types/fields.d.ts +1 -1
- package/dist/Model/filter/types/path/common.d.ts +1 -1
- package/dist/Model/filter/types/path/eager.d.ts +1 -1
- package/dist/Model/filter/types/path/eager.d.ts.map +1 -1
- package/dist/Model/filter/types/path/index.d.ts +1 -1
- package/dist/Model/filter/types/utils.d.ts +1 -1
- package/dist/Model/filter/types/validator.d.ts +1 -1
- package/dist/Model/filter/types.d.ts +1 -1
- package/dist/Model/query/dsl.d.ts +1 -1
- package/dist/Model/query/dsl.d.ts.map +1 -1
- package/dist/Model/query/new-kid-interpreter.d.ts +6 -6
- package/dist/Model/query/new-kid-interpreter.d.ts.map +1 -1
- package/dist/Model/query/new-kid-interpreter.js +3 -3
- package/dist/Model/query.d.ts +1 -1
- package/dist/Model.d.ts +2 -1
- package/dist/Model.d.ts.map +1 -1
- package/dist/Model.js +2 -1
- package/dist/Operations.d.ts +6 -6
- package/dist/Operations.d.ts.map +1 -1
- package/dist/Operations.js +56 -59
- package/dist/OperationsRepo.d.ts +11 -29
- package/dist/OperationsRepo.d.ts.map +1 -1
- package/dist/OperationsRepo.js +3 -3
- package/dist/QueueMaker/SQLQueue.d.ts +5 -7
- package/dist/QueueMaker/SQLQueue.d.ts.map +1 -1
- package/dist/QueueMaker/SQLQueue.js +105 -114
- package/dist/QueueMaker/errors.d.ts +2 -2
- package/dist/QueueMaker/errors.d.ts.map +1 -1
- package/dist/QueueMaker/memQueue.d.ts +7 -4
- package/dist/QueueMaker/memQueue.d.ts.map +1 -1
- package/dist/QueueMaker/memQueue.js +51 -62
- package/dist/QueueMaker/sbqueue.d.ts +6 -3
- package/dist/QueueMaker/sbqueue.d.ts.map +1 -1
- package/dist/QueueMaker/sbqueue.js +37 -53
- package/dist/QueueMaker/service.d.ts +1 -1
- package/dist/RequestContext.d.ts +114 -26
- package/dist/RequestContext.d.ts.map +1 -1
- package/dist/RequestContext.js +7 -7
- package/dist/RequestFiberSet.d.ts +7 -7
- package/dist/RequestFiberSet.d.ts.map +1 -1
- package/dist/RequestFiberSet.js +5 -5
- package/dist/Store/ContextMapContainer.d.ts +19 -3
- package/dist/Store/ContextMapContainer.d.ts.map +1 -1
- package/dist/Store/ContextMapContainer.js +13 -3
- package/dist/Store/Cosmos/query.d.ts +1 -1
- package/dist/Store/Cosmos/query.d.ts.map +1 -1
- package/dist/Store/Cosmos/query.js +8 -10
- package/dist/Store/Cosmos.d.ts +1 -1
- package/dist/Store/Cosmos.d.ts.map +1 -1
- package/dist/Store/Cosmos.js +308 -242
- package/dist/Store/Disk.d.ts +2 -2
- package/dist/Store/Disk.d.ts.map +1 -1
- package/dist/Store/Disk.js +25 -22
- package/dist/Store/Memory.d.ts +4 -4
- package/dist/Store/Memory.d.ts.map +1 -1
- package/dist/Store/Memory.js +27 -22
- package/dist/Store/SQL/Pg.d.ts +4 -0
- package/dist/Store/SQL/Pg.d.ts.map +1 -0
- package/dist/Store/SQL/Pg.js +189 -0
- package/dist/Store/SQL/query.d.ts +38 -0
- package/dist/Store/SQL/query.d.ts.map +1 -0
- package/dist/Store/SQL/query.js +367 -0
- package/dist/Store/SQL.d.ts +20 -0
- package/dist/Store/SQL.d.ts.map +1 -0
- package/dist/Store/SQL.js +381 -0
- package/dist/Store/codeFilter.d.ts +1 -1
- package/dist/Store/codeFilter.d.ts.map +1 -1
- package/dist/Store/codeFilter.js +2 -1
- package/dist/Store/index.d.ts +5 -2
- package/dist/Store/index.d.ts.map +1 -1
- package/dist/Store/index.js +15 -3
- package/dist/Store/service.d.ts +17 -6
- package/dist/Store/service.d.ts.map +1 -1
- package/dist/Store/service.js +24 -6
- package/dist/Store/utils.d.ts +1 -1
- package/dist/Store/utils.d.ts.map +1 -1
- package/dist/Store/utils.js +3 -4
- package/dist/Store.d.ts +1 -1
- package/dist/adapters/SQL/Model.d.ts +28 -42
- package/dist/adapters/SQL/Model.d.ts.map +1 -1
- package/dist/adapters/SQL/Model.js +2 -2
- package/dist/adapters/SQL.d.ts +1 -1
- package/dist/adapters/ServiceBus.d.ts +9 -9
- package/dist/adapters/ServiceBus.d.ts.map +1 -1
- package/dist/adapters/ServiceBus.js +13 -15
- package/dist/adapters/cosmos-client.d.ts +3 -3
- package/dist/adapters/cosmos-client.d.ts.map +1 -1
- package/dist/adapters/cosmos-client.js +3 -3
- package/dist/adapters/index.d.ts +8 -2
- package/dist/adapters/index.d.ts.map +1 -1
- package/dist/adapters/index.js +8 -2
- package/dist/adapters/logger.d.ts +1 -1
- package/dist/adapters/logger.d.ts.map +1 -1
- package/dist/adapters/memQueue.d.ts +3 -3
- package/dist/adapters/memQueue.d.ts.map +1 -1
- package/dist/adapters/memQueue.js +3 -3
- package/dist/adapters/mongo-client.d.ts +3 -3
- package/dist/adapters/mongo-client.d.ts.map +1 -1
- package/dist/adapters/mongo-client.js +3 -3
- package/dist/adapters/redis-client.d.ts +3 -3
- package/dist/adapters/redis-client.d.ts.map +1 -1
- package/dist/adapters/redis-client.js +3 -3
- package/dist/api/ContextProvider.d.ts +7 -7
- package/dist/api/ContextProvider.d.ts.map +1 -1
- package/dist/api/ContextProvider.js +6 -6
- package/dist/api/codec.d.ts +1 -1
- package/dist/api/internal/RequestContextMiddleware.d.ts +2 -2
- package/dist/api/internal/RequestContextMiddleware.d.ts.map +1 -1
- package/dist/api/internal/RequestContextMiddleware.js +2 -2
- package/dist/api/internal/auth.d.ts +44 -6
- package/dist/api/internal/auth.d.ts.map +1 -1
- package/dist/api/internal/auth.js +160 -29
- package/dist/api/internal/events.d.ts +3 -3
- package/dist/api/internal/events.d.ts.map +1 -1
- package/dist/api/internal/events.js +9 -7
- package/dist/api/internal/health.d.ts +1 -1
- package/dist/api/layerUtils.d.ts +6 -6
- package/dist/api/layerUtils.d.ts.map +1 -1
- package/dist/api/layerUtils.js +5 -5
- package/dist/api/middlewares.d.ts +1 -1
- package/dist/api/reportError.d.ts +1 -1
- package/dist/api/routing/middleware/RouterMiddleware.d.ts +4 -4
- package/dist/api/routing/middleware/RouterMiddleware.d.ts.map +1 -1
- package/dist/api/routing/middleware/middleware.d.ts +39 -3
- package/dist/api/routing/middleware/middleware.d.ts.map +1 -1
- package/dist/api/routing/middleware/middleware.js +45 -14
- package/dist/api/routing/middleware.d.ts +1 -2
- package/dist/api/routing/middleware.d.ts.map +1 -1
- package/dist/api/routing/middleware.js +1 -2
- package/dist/api/routing/schema/jwt.d.ts +1 -1
- package/dist/api/routing/schema/jwt.d.ts.map +1 -1
- package/dist/api/routing/tsort.d.ts +1 -1
- package/dist/api/routing/tsort.d.ts.map +1 -1
- package/dist/api/routing/utils.d.ts +3 -3
- package/dist/api/routing/utils.d.ts.map +1 -1
- package/dist/api/routing.d.ts +12 -14
- package/dist/api/routing.d.ts.map +1 -1
- package/dist/api/routing.js +17 -6
- package/dist/api/setupRequest.d.ts +8 -5
- package/dist/api/setupRequest.d.ts.map +1 -1
- package/dist/api/setupRequest.js +12 -7
- package/dist/api/util.d.ts +1 -1
- package/dist/arbs.d.ts +1 -1
- package/dist/arbs.d.ts.map +1 -1
- package/dist/arbs.js +5 -3
- package/dist/errorReporter.d.ts +4 -4
- package/dist/errorReporter.d.ts.map +1 -1
- package/dist/errorReporter.js +16 -23
- package/dist/errors.d.ts +1 -1
- package/dist/fileUtil.d.ts +1 -1
- package/dist/fileUtil.d.ts.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/logger/jsonLogger.d.ts +1 -1
- package/dist/logger/logFmtLogger.d.ts +1 -1
- package/dist/logger/shared.d.ts +1 -1
- package/dist/logger/shared.js +2 -2
- package/dist/logger.d.ts +1 -1
- package/dist/logger.d.ts.map +1 -1
- package/dist/rateLimit.d.ts +9 -3
- package/dist/rateLimit.d.ts.map +1 -1
- package/dist/rateLimit.js +5 -11
- package/dist/test.d.ts +1 -1
- package/dist/test.d.ts.map +1 -1
- package/dist/vitest.d.ts +1 -1
- package/eslint.config.mjs +3 -3
- package/examples/query.ts +39 -35
- package/package.json +42 -28
- package/src/CUPS.ts +9 -11
- package/src/Emailer/Sendgrid.ts +17 -14
- package/src/Emailer/service.ts +8 -2
- package/src/MainFiberSet.ts +3 -3
- package/src/Model/Repository/Registry.ts +33 -0
- package/src/Model/Repository/ext.ts +93 -6
- package/src/Model/Repository/internal/internal.ts +97 -88
- package/src/Model/Repository/makeRepo.ts +12 -10
- package/src/Model/Repository/service.ts +31 -22
- package/src/Model/Repository/validation.ts +4 -4
- package/src/Model/Repository.ts +1 -0
- package/src/Model/dsl.ts +3 -3
- package/src/Model/query/new-kid-interpreter.ts +2 -2
- package/src/Model.ts +1 -0
- package/src/Operations.ts +78 -113
- package/src/OperationsRepo.ts +2 -2
- package/src/QueueMaker/SQLQueue.ts +121 -151
- package/src/QueueMaker/memQueue.ts +82 -103
- package/src/QueueMaker/sbqueue.ts +56 -86
- package/src/RequestContext.ts +8 -8
- package/src/RequestFiberSet.ts +4 -4
- package/src/Store/ContextMapContainer.ts +41 -2
- package/src/Store/Cosmos/query.ts +9 -11
- package/src/Store/Cosmos.ts +437 -343
- package/src/Store/Disk.ts +52 -49
- package/src/Store/Memory.ts +54 -48
- package/src/Store/SQL/Pg.ts +318 -0
- package/src/Store/SQL/query.ts +409 -0
- package/src/Store/SQL.ts +668 -0
- package/src/Store/codeFilter.ts +1 -0
- package/src/Store/index.ts +17 -2
- package/src/Store/service.ts +31 -7
- package/src/Store/utils.ts +23 -22
- package/src/adapters/SQL/Model.ts +10 -4
- package/src/adapters/ServiceBus.ts +111 -115
- package/src/adapters/cosmos-client.ts +2 -2
- package/src/adapters/index.ts +7 -0
- package/src/adapters/memQueue.ts +2 -2
- package/src/adapters/mongo-client.ts +2 -2
- package/src/adapters/redis-client.ts +2 -2
- package/src/api/ContextProvider.ts +11 -11
- package/src/api/internal/RequestContextMiddleware.ts +1 -1
- package/src/api/internal/auth.ts +246 -44
- package/src/api/internal/events.ts +12 -8
- package/src/api/layerUtils.ts +8 -8
- package/src/api/routing/middleware/RouterMiddleware.ts +4 -4
- package/src/api/routing/middleware/middleware.ts +52 -12
- package/src/api/routing/middleware.ts +0 -2
- package/src/api/routing.ts +21 -7
- package/src/api/setupRequest.ts +28 -8
- package/src/arbs.ts +4 -2
- package/src/errorReporter.ts +58 -72
- package/src/logger/shared.ts +1 -1
- package/src/rateLimit.ts +30 -22
- package/test/auth.test.ts +101 -0
- package/test/contextProvider.test.ts +11 -11
- package/test/controller.test.ts +18 -14
- package/test/dist/auth.test.d.ts.map +1 -0
- package/test/dist/contextProvider.test.d.ts.map +1 -1
- package/test/dist/controller.test.d.ts.map +1 -1
- package/test/dist/date-query.test.d.ts.map +1 -0
- package/test/dist/fixtures.d.ts +26 -12
- package/test/dist/fixtures.d.ts.map +1 -1
- package/test/dist/fixtures.js +12 -10
- package/test/dist/query.test.d.ts.map +1 -1
- package/test/dist/rawQuery.test.d.ts.map +1 -1
- package/test/dist/repository-ext.test.d.ts.map +1 -0
- package/test/dist/requires.test.d.ts.map +1 -1
- package/test/dist/router-generator.test.d.ts.map +1 -0
- package/test/dist/routing-interruptibility.test.d.ts.map +1 -0
- package/test/dist/rpc-multi-middleware.test.d.ts.map +1 -1
- package/test/dist/sql-store.test.d.ts.map +1 -0
- package/test/fixtures.ts +11 -9
- package/test/query.test.ts +216 -34
- package/test/rawQuery.test.ts +23 -19
- package/test/repository-ext.test.ts +60 -0
- package/test/requires.test.ts +6 -6
- package/test/router-generator.test.ts +180 -0
- package/test/routing-interruptibility.test.ts +63 -0
- package/test/rpc-multi-middleware.test.ts +78 -9
- package/test/sql-store.test.ts +1064 -0
- package/test/validateSample.test.ts +15 -12
- package/tsconfig.examples.json +1 -1
- package/tsconfig.json +0 -1
- package/tsconfig.json.bak +2 -2
- package/tsconfig.src.json +35 -35
- package/tsconfig.test.json +2 -2
package/src/api/internal/auth.ts
CHANGED
|
@@ -1,42 +1,244 @@
|
|
|
1
|
-
|
|
2
|
-
/* eslint-disable unused-imports/no-unused-vars */
|
|
3
|
-
import { Data, Effect } from "effect-app"
|
|
1
|
+
import { Data, Effect, Option } from "effect-app"
|
|
4
2
|
import { HttpHeaders, HttpMiddleware, HttpServerRequest, HttpServerResponse } from "effect-app/http"
|
|
5
|
-
import {
|
|
3
|
+
import { createRemoteJWKSet, jwtVerify } from "jose"
|
|
6
4
|
|
|
7
|
-
|
|
8
|
-
|
|
5
|
+
const getHeaders = (error: string, description: string, scopes?: ReadonlyArray<string>) => ({
|
|
6
|
+
"WWW-Authenticate": `Bearer realm="api", error="${error}", error_description="${description.replace(/"/g, "'")}"${
|
|
7
|
+
scopes ? `, scope="${scopes.join(" ")}"` : ""
|
|
8
|
+
}`
|
|
9
|
+
})
|
|
9
10
|
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
11
|
+
export class UnauthorizedError extends Error {
|
|
12
|
+
readonly status: number = 401
|
|
13
|
+
readonly statusCode: number = 401
|
|
14
|
+
headers = { "WWW-Authenticate": "Bearer realm=\"api\"" }
|
|
15
|
+
|
|
16
|
+
constructor(message = "Unauthorized") {
|
|
17
|
+
super(message)
|
|
18
|
+
this.name = this.constructor.name
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export class InvalidRequestError extends UnauthorizedError {
|
|
23
|
+
readonly code: string
|
|
24
|
+
override readonly status = 400
|
|
25
|
+
override readonly statusCode = 400
|
|
26
|
+
|
|
27
|
+
constructor(message = "Invalid Request", useErrorCode = true) {
|
|
28
|
+
super(message)
|
|
29
|
+
this.code = useErrorCode ? "invalid_request" : ""
|
|
30
|
+
if (useErrorCode) {
|
|
31
|
+
this.headers = getHeaders(this.code, this.message)
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export class InvalidTokenError extends UnauthorizedError {
|
|
37
|
+
readonly code = "invalid_token"
|
|
38
|
+
|
|
39
|
+
constructor(message = "Invalid Token") {
|
|
40
|
+
super(message)
|
|
41
|
+
this.headers = getHeaders(this.code, this.message)
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export class InsufficientScopeError extends UnauthorizedError {
|
|
46
|
+
readonly code = "insufficient_scope"
|
|
47
|
+
override readonly status = 403
|
|
48
|
+
override readonly statusCode = 403
|
|
49
|
+
|
|
50
|
+
constructor(scopes?: ReadonlyArray<string>, message = "Insufficient Scope") {
|
|
51
|
+
super(message)
|
|
52
|
+
this.headers = getHeaders(this.code, this.message, scopes)
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface JwtVerifierOptions {
|
|
57
|
+
readonly audience?: string | Array<string> | ReadonlyArray<string>
|
|
58
|
+
readonly clockTolerance?: number
|
|
59
|
+
readonly issuer?: string
|
|
60
|
+
readonly issuerBaseURL?: string
|
|
61
|
+
readonly jwksUri?: string
|
|
62
|
+
readonly maxTokenAge?: number
|
|
63
|
+
readonly secret?: string
|
|
64
|
+
readonly strict?: boolean
|
|
65
|
+
readonly tokenSigningAlg?: string
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export interface AuthOptions extends JwtVerifierOptions {
|
|
69
|
+
readonly authRequired?: boolean
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
type Config = AuthOptions
|
|
73
|
+
|
|
74
|
+
type JwtError = InsufficientScopeError | InvalidRequestError | InvalidTokenError | UnauthorizedError
|
|
75
|
+
|
|
76
|
+
type ResolvedConfigBase = {
|
|
77
|
+
readonly audience: string | Array<string> | undefined
|
|
78
|
+
readonly clockTolerance: number
|
|
79
|
+
readonly issuer: string | undefined
|
|
80
|
+
readonly maxTokenAge: number | undefined
|
|
81
|
+
readonly strict: boolean
|
|
82
|
+
readonly tokenSigningAlg: string | undefined
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
type ResolvedConfig =
|
|
86
|
+
& ResolvedConfigBase
|
|
87
|
+
& (
|
|
88
|
+
| {
|
|
89
|
+
readonly key: ReturnType<typeof createRemoteJWKSet>
|
|
90
|
+
readonly keyType: "jwks"
|
|
91
|
+
}
|
|
92
|
+
| {
|
|
93
|
+
readonly key: Uint8Array
|
|
94
|
+
readonly keyType: "secret"
|
|
95
|
+
}
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === "object" && value !== null
|
|
99
|
+
|
|
100
|
+
const getErrorMessage = (error: unknown) => error instanceof Error ? error.message : String(error)
|
|
101
|
+
|
|
102
|
+
const normalizeAudience = (audience: Config["audience"]): string | Array<string> | undefined =>
|
|
103
|
+
Array.isArray(audience) ? Array.from(audience) : audience as string | undefined
|
|
104
|
+
|
|
105
|
+
const buildDiscoveryUrl = (issuerBaseURL: string) => {
|
|
106
|
+
const url = new URL(issuerBaseURL)
|
|
107
|
+
if (!url.pathname.includes("/.well-known/")) {
|
|
108
|
+
url.pathname = url.pathname.endsWith("/")
|
|
109
|
+
? `${url.pathname}.well-known/openid-configuration`
|
|
110
|
+
: `${url.pathname}/.well-known/openid-configuration`
|
|
111
|
+
}
|
|
112
|
+
url.search = ""
|
|
113
|
+
url.hash = ""
|
|
114
|
+
return url
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const fetchDiscoveryDocumentPromise = async (issuerBaseURL: string) => {
|
|
118
|
+
const response = await fetch(buildDiscoveryUrl(issuerBaseURL))
|
|
119
|
+
if (!response.ok) {
|
|
120
|
+
throw new Error(`Failed to fetch authorization server metadata: ${response.status}`)
|
|
121
|
+
}
|
|
122
|
+
const json = await response.json()
|
|
123
|
+
if (!isRecord(json) || typeof json["issuer"] !== "string" || typeof json["jwks_uri"] !== "string") {
|
|
124
|
+
throw new Error("Invalid authorization server metadata")
|
|
125
|
+
}
|
|
126
|
+
return { issuer: json["issuer"], jwksUri: json["jwks_uri"] }
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const getAuthorizationToken = (headers: HttpHeaders.Headers, authRequired: boolean) => {
|
|
130
|
+
const authorization = HttpHeaders.get(headers, "authorization")
|
|
131
|
+
if (Option.isNone(authorization)) {
|
|
132
|
+
return authRequired ? Effect.fail(new UnauthorizedError()) : Effect.succeed(Option.none<string>())
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const [scheme, token] = authorization.value.split(" ")
|
|
136
|
+
if (!scheme || !token || scheme.toLowerCase() !== "bearer") {
|
|
137
|
+
return Effect.fail(new InvalidRequestError("", false))
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
return Effect.succeed(Option.some(token))
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const makeResolveConfig = (config: Config) => {
|
|
144
|
+
let cached: Promise<ResolvedConfig> | undefined
|
|
145
|
+
|
|
146
|
+
return Effect.tryPromise({
|
|
147
|
+
try: () => {
|
|
148
|
+
if (!cached) {
|
|
149
|
+
cached = (async (): Promise<ResolvedConfig> => {
|
|
150
|
+
const discovery = config.issuerBaseURL
|
|
151
|
+
? await fetchDiscoveryDocumentPromise(config.issuerBaseURL)
|
|
152
|
+
: undefined
|
|
153
|
+
|
|
154
|
+
const issuer = config.issuer ?? discovery?.issuer
|
|
155
|
+
const jwksUri = config.jwksUri ?? discovery?.jwksUri
|
|
156
|
+
const secret = config.secret
|
|
157
|
+
const base = {
|
|
158
|
+
audience: normalizeAudience(config.audience),
|
|
159
|
+
clockTolerance: config.clockTolerance ?? 5,
|
|
160
|
+
issuer,
|
|
161
|
+
maxTokenAge: config.maxTokenAge,
|
|
162
|
+
strict: config.strict ?? false,
|
|
163
|
+
tokenSigningAlg: config.tokenSigningAlg
|
|
164
|
+
} satisfies ResolvedConfigBase
|
|
165
|
+
|
|
166
|
+
if (!issuer && !secret) {
|
|
167
|
+
throw new InvalidRequestError("JWT config requires 'issuer', 'issuerBaseURL', or 'secret'")
|
|
29
168
|
}
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
169
|
+
|
|
170
|
+
if (!secret) {
|
|
171
|
+
if (!jwksUri) {
|
|
172
|
+
throw new InvalidRequestError("JWT config requires 'jwksUri', 'issuerBaseURL', or 'secret'")
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
return {
|
|
176
|
+
...base,
|
|
177
|
+
key: createRemoteJWKSet(new URL(jwksUri)),
|
|
178
|
+
keyType: "jwks"
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
return {
|
|
183
|
+
...base,
|
|
184
|
+
key: new TextEncoder().encode(secret),
|
|
185
|
+
keyType: "secret"
|
|
186
|
+
}
|
|
187
|
+
})()
|
|
38
188
|
}
|
|
189
|
+
|
|
190
|
+
return cached
|
|
191
|
+
},
|
|
192
|
+
catch: (error) =>
|
|
193
|
+
error instanceof InvalidRequestError || error instanceof InvalidTokenError
|
|
194
|
+
? error
|
|
195
|
+
: new InvalidTokenError(getErrorMessage(error))
|
|
196
|
+
})
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const verifyToken =
|
|
200
|
+
(resolveConfig: Effect.Effect<ResolvedConfig, InvalidRequestError | InvalidTokenError>) => (token: string) =>
|
|
201
|
+
resolveConfig.pipe(
|
|
202
|
+
Effect.flatMap((config) => {
|
|
203
|
+
const options = {
|
|
204
|
+
clockTolerance: config.clockTolerance,
|
|
205
|
+
...(config.tokenSigningAlg ? { algorithms: [config.tokenSigningAlg] } : {}),
|
|
206
|
+
...(config.audience !== undefined ? { audience: config.audience } : {}),
|
|
207
|
+
...(config.issuer !== undefined ? { issuer: config.issuer } : {}),
|
|
208
|
+
...(config.maxTokenAge !== undefined ? { maxTokenAge: config.maxTokenAge } : {})
|
|
209
|
+
}
|
|
210
|
+
const verified = config.keyType === "jwks"
|
|
211
|
+
? Effect.tryPromise({
|
|
212
|
+
try: () => jwtVerify(token, config.key, options).then(({ protectedHeader }) => ({ protectedHeader })),
|
|
213
|
+
catch: (error) => new InvalidTokenError(getErrorMessage(error))
|
|
214
|
+
})
|
|
215
|
+
: Effect.tryPromise({
|
|
216
|
+
try: () => jwtVerify(token, config.key, options).then(({ protectedHeader }) => ({ protectedHeader })),
|
|
217
|
+
catch: (error) => new InvalidTokenError(getErrorMessage(error))
|
|
218
|
+
})
|
|
219
|
+
|
|
220
|
+
return verified.pipe(
|
|
221
|
+
Effect.flatMap(({ protectedHeader }) => {
|
|
222
|
+
const typ = protectedHeader.typ?.toLowerCase().replace(/^application\//, "")
|
|
223
|
+
return config.strict && typ !== "at+jwt"
|
|
224
|
+
? Effect.fail(new InvalidTokenError("Unexpected 'typ' value"))
|
|
225
|
+
: Effect.void
|
|
226
|
+
})
|
|
227
|
+
)
|
|
228
|
+
})
|
|
39
229
|
)
|
|
230
|
+
|
|
231
|
+
export const checkJWTI = (config: Config) => {
|
|
232
|
+
const resolveConfig = makeResolveConfig(config)
|
|
233
|
+
const verify = verifyToken(resolveConfig)
|
|
234
|
+
|
|
235
|
+
return Effect.fnUntraced(function*(headers: HttpHeaders.Headers) {
|
|
236
|
+
const token = yield* getAuthorizationToken(headers, config.authRequired !== false)
|
|
237
|
+
if (Option.isNone(token)) {
|
|
238
|
+
return
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
yield* verify(token.value)
|
|
40
242
|
})
|
|
41
243
|
}
|
|
42
244
|
|
|
@@ -45,24 +247,24 @@ export const checkJwt = (config: Config) => {
|
|
|
45
247
|
return HttpMiddleware.make((app) =>
|
|
46
248
|
Effect.gen(function*() {
|
|
47
249
|
const req = yield* HttpServerRequest.HttpServerRequest
|
|
48
|
-
const response = yield* check(req.headers).pipe(
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
250
|
+
const response = yield* check(req.headers).pipe(
|
|
251
|
+
Effect.catch((error: JwtError) =>
|
|
252
|
+
HttpServerResponse.json({ message: error.message }, {
|
|
253
|
+
status: error.status,
|
|
254
|
+
headers: HttpHeaders.fromInput(error.headers)
|
|
255
|
+
})
|
|
256
|
+
)
|
|
257
|
+
)
|
|
258
|
+
|
|
54
259
|
if (response) {
|
|
55
260
|
return response
|
|
56
261
|
}
|
|
262
|
+
|
|
57
263
|
return yield* app
|
|
58
264
|
})
|
|
59
265
|
)
|
|
60
266
|
}
|
|
61
267
|
|
|
62
268
|
export class JWTError extends Data.TaggedClass("JWTError")<{
|
|
63
|
-
error:
|
|
64
|
-
| InsufficientScopeError
|
|
65
|
-
| InvalidRequestError
|
|
66
|
-
| InvalidTokenError
|
|
67
|
-
| UnauthorizedError
|
|
269
|
+
error: JwtError
|
|
68
270
|
}> {}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { Duration, Effect, pipe, S, Schedule, Stream } from "effect-app"
|
|
2
2
|
import { HttpHeaders, HttpServerResponse } from "effect-app/http"
|
|
3
3
|
import { reportError } from "../../errorReporter.js"
|
|
4
|
+
import { storeId } from "../../Store/Memory.js"
|
|
4
5
|
import { setupRequestContextFromCurrent } from "../setupRequest.js"
|
|
5
6
|
|
|
6
7
|
// Tell the client to retry every 10 seconds if connectivity is lost
|
|
@@ -9,29 +10,32 @@ const keepAlive = Stream.fromEffectSchedule(Effect.succeed(":keep-alive"), Sched
|
|
|
9
10
|
|
|
10
11
|
let connId = BigInt(0)
|
|
11
12
|
|
|
12
|
-
export const makeSSE = <A extends { id: any }, SI,
|
|
13
|
-
schema: S.Codec<A, SI,
|
|
13
|
+
export const makeSSE = <A extends { id: any }, SI, SRD, SRE>(
|
|
14
|
+
schema: S.Codec<A, SI, SRD, SRE>
|
|
14
15
|
) =>
|
|
15
16
|
<E, R>(events: Stream.Stream<{ evt: A; namespace: string }, E, R>) =>
|
|
16
17
|
Effect
|
|
17
18
|
.gen(function*() {
|
|
18
19
|
const id = connId++
|
|
19
|
-
const ctx = yield* Effect.
|
|
20
|
+
const ctx = yield* Effect.context<R | SRD | SRE>()
|
|
20
21
|
const res = HttpServerResponse.stream(
|
|
21
22
|
// workaround for different scoped behaviour for streams in Bun
|
|
22
23
|
// https://discord.com/channels/795981131316985866/1098177242598756412/1389646879675125861
|
|
23
24
|
Effect
|
|
24
25
|
.gen(function*() {
|
|
26
|
+
const ns = yield* storeId
|
|
25
27
|
yield* Effect.annotateCurrentSpan({ connectionId: id.toString() })
|
|
26
|
-
yield* Effect.logInfo("$ start listening to events, id: " + id.toString())
|
|
27
|
-
yield* Effect.addFinalizer(() =>
|
|
28
|
+
yield* Effect.logInfo("$ start listening to events, id: " + id.toString() + ", ns: " + ns)
|
|
29
|
+
yield* Effect.addFinalizer(() =>
|
|
30
|
+
Effect.logInfo("$ end listening to events, id: " + id.toString() + ", ns: " + ns)
|
|
31
|
+
)
|
|
28
32
|
|
|
29
33
|
const enc = new TextEncoder()
|
|
30
34
|
|
|
31
|
-
const encode = S.encodeEffect(S.fromJsonString(schema))
|
|
35
|
+
const encode = S.encodeEffect(S.fromJsonString(S.toCodecJson(schema)))
|
|
32
36
|
|
|
33
37
|
const eventStream = Stream.mapEffect(
|
|
34
|
-
events,
|
|
38
|
+
Stream.filter(events, (_) => _.namespace === ns),
|
|
35
39
|
(_) =>
|
|
36
40
|
encode(_.evt)
|
|
37
41
|
.pipe(Effect.map((data) => `id: ${_.evt.id}\ndata: ${data}`))
|
|
@@ -42,7 +46,7 @@ export const makeSSE = <A extends { id: any }, SI, SR>(
|
|
|
42
46
|
Stream.merge(keepAlive),
|
|
43
47
|
// Keep this unary so pipe receives a function, not a Stream value.
|
|
44
48
|
(self) => Stream.merge(self, eventStream, { haltStrategy: "either" }),
|
|
45
|
-
Stream.tapCause((cause) => Effect.logError("SSE error", cause)),
|
|
49
|
+
Stream.tapCause((cause) => Effect.logError("SSE error, id: " + id.toString() + ", ns: " + ns, cause)),
|
|
46
50
|
Stream.map((_) => enc.encode(_ + "\n\n"))
|
|
47
51
|
)
|
|
48
52
|
|
package/src/api/layerUtils.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
2
|
-
import { Effect, type Layer, type NonEmptyReadonlyArray, Option
|
|
2
|
+
import { Context, Effect, type Layer, type NonEmptyReadonlyArray, Option } from "effect-app"
|
|
3
3
|
import { InfraLogger } from "../logger.js"
|
|
4
4
|
|
|
5
5
|
// TODO: These LayerUtils are flaky, like in dependencies as a readonly array, it breaks when there are two entries
|
|
@@ -27,7 +27,7 @@ export namespace LayerUtils {
|
|
|
27
27
|
}
|
|
28
28
|
|
|
29
29
|
export type ContextTagWithDefault<Id, A, LayerE, LayerR> =
|
|
30
|
-
&
|
|
30
|
+
& Context.Service<Id, A>
|
|
31
31
|
& {
|
|
32
32
|
Default: Layer.Layer<Id, LayerE, LayerR>
|
|
33
33
|
}
|
|
@@ -36,29 +36,29 @@ export namespace ContextTagWithDefault {
|
|
|
36
36
|
export type Base<A> = ContextTagWithDefault<any, A, any, any>
|
|
37
37
|
}
|
|
38
38
|
|
|
39
|
-
export type GetContext<T> = T extends
|
|
39
|
+
export type GetContext<T> = T extends Context.Context<infer Y> ? Y : never
|
|
40
40
|
|
|
41
41
|
export const mergeContexts = Effect.fnUntraced(
|
|
42
42
|
function*<
|
|
43
43
|
T extends readonly {
|
|
44
44
|
maker: any
|
|
45
|
-
handle: Effect.Effect<
|
|
45
|
+
handle: Effect.Effect<Context.Context<any> | Option.Option<Context.Context<any>>>
|
|
46
46
|
}[]
|
|
47
47
|
>(
|
|
48
48
|
makers: T
|
|
49
49
|
) {
|
|
50
|
-
let context =
|
|
50
|
+
let context = Context.empty()
|
|
51
51
|
for (const mw of makers) {
|
|
52
52
|
const ctx = yield* mw.handle.pipe(Effect.provide(context))
|
|
53
|
-
const moreContext =
|
|
53
|
+
const moreContext = Context.isContext(ctx) ? Option.some(ctx) : ctx
|
|
54
54
|
yield* InfraLogger.logDebug(
|
|
55
55
|
"Built dynamic context for middleware" + (mw.maker.key ?? mw.maker),
|
|
56
56
|
Option.map(moreContext, (c) => (c as any).toJSON().services)
|
|
57
57
|
)
|
|
58
58
|
if (moreContext.value) {
|
|
59
|
-
context =
|
|
59
|
+
context = Context.merge(context, moreContext.value)
|
|
60
60
|
}
|
|
61
61
|
}
|
|
62
|
-
return context as
|
|
62
|
+
return context as Context.Context<Effect.Success<T[number]["handle"]>>
|
|
63
63
|
}
|
|
64
64
|
)
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
|
|
2
2
|
/* eslint-disable @typescript-eslint/no-unsafe-return */
|
|
3
3
|
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
4
|
-
import { type
|
|
4
|
+
import { type Context, type Layer } from "effect-app"
|
|
5
5
|
import { type GetContextConfig, type RpcContextMap } from "effect-app/rpc/RpcContextMap"
|
|
6
6
|
import { type RpcMiddlewareV4 } from "effect-app/rpc/RpcMiddleware"
|
|
7
7
|
// module:
|
|
8
8
|
//
|
|
9
9
|
|
|
10
|
-
// v4: middleware tags are
|
|
10
|
+
// v4: middleware tags are Context.Service (not Effect) — they carry the RpcMiddlewareV4 as their service Shape
|
|
11
11
|
export type RouterMiddleware<
|
|
12
12
|
Self,
|
|
13
13
|
RequestContextMap extends Record<string, RpcContextMap.Any>, // what services will the middlware provide dynamically to the next, or raise errors.
|
|
@@ -18,9 +18,9 @@ export type RouterMiddleware<
|
|
|
18
18
|
_ContextProviderR, // what the context provider requires
|
|
19
19
|
RequestContextId
|
|
20
20
|
> =
|
|
21
|
-
&
|
|
21
|
+
& Context.Service<Self, RpcMiddlewareV4<ContextProviderA, ContextProviderE, never>>
|
|
22
22
|
& {
|
|
23
23
|
readonly Default: Layer.Layer<Self, MakeMiddlewareE, MakeMiddlewareR>
|
|
24
|
-
readonly requestContext:
|
|
24
|
+
readonly requestContext: Context.Service<RequestContextId, GetContextConfig<RequestContextMap>>
|
|
25
25
|
readonly requestContextMap: RequestContextMap
|
|
26
26
|
}
|
|
@@ -1,10 +1,13 @@
|
|
|
1
1
|
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
2
2
|
import { Cause, Config, Effect, Layer, Schema } from "effect"
|
|
3
3
|
import { ConfigureInterruptibilityMiddleware, DevMode, DevModeMiddleware, LoggerMiddleware, RequestCacheMiddleware } from "effect-app/middleware"
|
|
4
|
+
import { RpcContextMap, type RpcMiddleware } from "effect-app/rpc"
|
|
4
5
|
import { pretty } from "effect-app/utils"
|
|
6
|
+
import * as Context from "effect/Context"
|
|
7
|
+
import { type Rpc } from "effect/unstable/rpc"
|
|
5
8
|
import { logError, reportError } from "../../../errorReporter.js"
|
|
6
9
|
import { InfraLogger } from "../../../logger.js"
|
|
7
|
-
import {
|
|
10
|
+
import { WithNsTransaction } from "../../../Store/SQL.js"
|
|
8
11
|
|
|
9
12
|
const logRequestError = logError("Request")
|
|
10
13
|
const reportRequestError = reportError("Request")
|
|
@@ -26,22 +29,20 @@ export const RequestCacheMiddlewareLive = Layer.succeed(
|
|
|
26
29
|
const isOptimisticConcurrencyException = (input: unknown) =>
|
|
27
30
|
typeof input === "object" && input !== null && "_tag" in input && input._tag === "OptimisticConcurrencyException"
|
|
28
31
|
|
|
32
|
+
export const RequestType = Context.Reference<"command" | "query">(
|
|
33
|
+
"@effect-app/infra/api/routing/RequestType",
|
|
34
|
+
{ defaultValue: () => "query" }
|
|
35
|
+
)
|
|
36
|
+
|
|
29
37
|
export const ConfigureInterruptibilityMiddlewareLive = Layer.effect(
|
|
30
38
|
ConfigureInterruptibilityMiddleware,
|
|
31
39
|
Effect.gen(function*() {
|
|
32
|
-
const cache = new Map()
|
|
33
|
-
const getCached = (key: string, schema: Schema.Top) => {
|
|
34
|
-
const existing = cache.get(key)
|
|
35
|
-
if (existing) return existing
|
|
36
|
-
const n = determineMethod(key, schema)
|
|
37
|
-
cache.set(key, n)
|
|
38
|
-
return n
|
|
39
|
-
}
|
|
40
40
|
return (effect, { rpc }) => {
|
|
41
|
-
const
|
|
41
|
+
const requestType = Context.get(rpc.annotations, RequestType)
|
|
42
|
+
const isCommand = requestType === "command"
|
|
42
43
|
|
|
43
|
-
effect = isCommand
|
|
44
|
-
? Effect.retry(
|
|
44
|
+
effect = isCommand
|
|
45
|
+
? Effect.retry(effect, { times: 1, while: isOptimisticConcurrencyException })
|
|
45
46
|
: Effect.interruptible(effect)
|
|
46
47
|
|
|
47
48
|
return effect
|
|
@@ -126,3 +127,42 @@ export const DefaultGenericMiddlewaresLive = Layer.mergeAll(
|
|
|
126
127
|
LoggerMiddlewareLive,
|
|
127
128
|
DevModeMiddlewareLive
|
|
128
129
|
)
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Config entry for `RequestContextMap` that controls per-RPC transaction wrapping.
|
|
133
|
+
* Defaults to `false` (no transaction). Set `requiresTransaction: true` on a route to enable.
|
|
134
|
+
*
|
|
135
|
+
* @example
|
|
136
|
+
* ```ts
|
|
137
|
+
* class RequestContextMap extends RpcContextMap.makeMap({
|
|
138
|
+
* requiresTransaction: requiresTransactionConfig,
|
|
139
|
+
* // ...
|
|
140
|
+
* }) {}
|
|
141
|
+
* ```
|
|
142
|
+
*/
|
|
143
|
+
export const requiresTransactionConfig = RpcContextMap.makeCustom()(Schema.Never, false)
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Creates the middleware Effect for SQL transaction wrapping.
|
|
147
|
+
* Requires `WithNsTransaction` service.
|
|
148
|
+
* Reads `requiresTransaction` from the RPC config; defaults to `false`.
|
|
149
|
+
*
|
|
150
|
+
* @example
|
|
151
|
+
* ```ts
|
|
152
|
+
* const SqlTransactionMiddlewareLive = Layer.effect(
|
|
153
|
+
* SqlTransactionMiddleware,
|
|
154
|
+
* makeSqlTransactionMiddleware(RequestContextMap)
|
|
155
|
+
* )
|
|
156
|
+
* ```
|
|
157
|
+
*/
|
|
158
|
+
export const makeSqlTransactionMiddleware = Effect.fnUntraced(function*(
|
|
159
|
+
rcm: { getConfig: (rpc: Rpc.AnyWithProps) => { readonly requiresTransaction?: boolean } }
|
|
160
|
+
) {
|
|
161
|
+
const withTx = yield* WithNsTransaction
|
|
162
|
+
const mw: RpcMiddleware.RpcMiddlewareV4<never, never, never> = (effect, { rpc }) => {
|
|
163
|
+
const { requiresTransaction } = rcm.getConfig(rpc)
|
|
164
|
+
if (requiresTransaction !== true) return effect
|
|
165
|
+
return withTx(effect)
|
|
166
|
+
}
|
|
167
|
+
return mw
|
|
168
|
+
})
|
package/src/api/routing.ts
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
/* eslint-disable @typescript-eslint/no-empty-object-type */
|
|
4
4
|
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
5
5
|
import { Config, Effect, Layer, type NonEmptyReadonlyArray, Predicate, S, type Scope } from "effect-app"
|
|
6
|
+
import { getMeta } from "effect-app/client"
|
|
6
7
|
import { type HttpHeaders } from "effect-app/http"
|
|
7
8
|
import { type GetEffectContext, type GetEffectError, type RpcContextMap } from "effect-app/rpc/RpcContextMap"
|
|
8
9
|
import { type TypeTestId } from "effect-app/TypeTest"
|
|
@@ -10,14 +11,20 @@ import { typedKeysOf, typedValuesOf } from "effect-app/utils"
|
|
|
10
11
|
import { type Yieldable } from "effect/Effect"
|
|
11
12
|
import { Rpc, RpcGroup, type RpcSerialization, RpcServer } from "effect/unstable/rpc"
|
|
12
13
|
import { type LayerUtils } from "./layerUtils.js"
|
|
13
|
-
import { type RouterMiddleware } from "./routing/middleware.js"
|
|
14
|
+
import { RequestType as RequestTypeAnnotation, type RouterMiddleware } from "./routing/middleware.js"
|
|
14
15
|
|
|
15
16
|
export * from "./routing/middleware.js"
|
|
16
17
|
|
|
18
|
+
export const applyRequestTypeInterruptibility = <A, E, R>(
|
|
19
|
+
requestType: "command" | "query",
|
|
20
|
+
effect: Effect.Effect<A, E, R>
|
|
21
|
+
) => requestType === "command" ? Rpc.uninterruptible(effect) : effect
|
|
22
|
+
|
|
17
23
|
// it's the result of extending S.Req setting success, config
|
|
18
24
|
// it's a schema plus some metadata
|
|
19
25
|
export type AnyRequestModule = S.Top & {
|
|
20
26
|
_tag: string // unique identifier for the request module
|
|
27
|
+
type: "command" | "query"
|
|
21
28
|
config: any // ?
|
|
22
29
|
success: S.Top // validates the success response
|
|
23
30
|
error: S.Top // validates the failure response
|
|
@@ -182,10 +189,9 @@ export const makeRouter = <
|
|
|
182
189
|
* if `check` is provided, the router will only be created if the effect succeeds with true
|
|
183
190
|
*/
|
|
184
191
|
function matchFor<
|
|
185
|
-
const ModuleName extends string,
|
|
186
192
|
const Resource extends Record<string, any>
|
|
187
193
|
>(
|
|
188
|
-
rsc: Resource
|
|
194
|
+
rsc: Resource,
|
|
189
195
|
options?: { check?: Effect.Effect<boolean> }
|
|
190
196
|
) {
|
|
191
197
|
type HandlerWithInputGen<
|
|
@@ -244,12 +250,12 @@ export const makeRouter = <
|
|
|
244
250
|
|
|
245
251
|
type AnyHandlers<Action extends AnyRequestModule> = HandlersRaw<Action> | HandlersDecoded<Action>
|
|
246
252
|
|
|
247
|
-
const
|
|
253
|
+
const meta = getMeta(rsc)
|
|
248
254
|
|
|
249
255
|
type RequestModules = FilterRequestModules<Resource>
|
|
250
256
|
const requestModules = typedKeysOf(rsc).reduce((acc, cur) => {
|
|
251
257
|
if (Predicate.isObjectKeyword(rsc[cur]) && rsc[cur]["success"]) {
|
|
252
|
-
acc[cur as keyof RequestModules] = rsc[cur]
|
|
258
|
+
acc[cur as keyof RequestModules] = rsc[cur]
|
|
253
259
|
}
|
|
254
260
|
return acc
|
|
255
261
|
}, {} as RequestModules)
|
|
@@ -261,12 +267,14 @@ export const makeRouter = <
|
|
|
261
267
|
if (handlerImpl[Symbol.toStringTag] === "GeneratorFunction") handlerImpl = Effect.fnUntraced(handlerImpl)
|
|
262
268
|
const stack = new Error().stack?.split("\n").slice(2).join("\n")
|
|
263
269
|
return Effect.isEffect(handlerImpl)
|
|
270
|
+
// oxlint-disable-next-line typescript/no-extraneous-class
|
|
264
271
|
? class {
|
|
265
272
|
static request = rsc[cur]
|
|
266
273
|
static stack = stack
|
|
267
274
|
static _tag = RequestTypes.DECODED
|
|
268
275
|
static handler = () => handlerImpl
|
|
269
276
|
}
|
|
277
|
+
// oxlint-disable-next-line typescript/no-extraneous-class
|
|
270
278
|
: class {
|
|
271
279
|
static request = rsc[cur]
|
|
272
280
|
static stack = stack
|
|
@@ -284,12 +292,14 @@ export const makeRouter = <
|
|
|
284
292
|
if (handlerImpl[Symbol.toStringTag] === "GeneratorFunction") handlerImpl = Effect.fnUntraced(handlerImpl)
|
|
285
293
|
const stack = new Error().stack?.split("\n").slice(2).join("\n")
|
|
286
294
|
return Effect.isEffect(handlerImpl)
|
|
295
|
+
// oxlint-disable-next-line typescript/no-extraneous-class
|
|
287
296
|
? class {
|
|
288
297
|
static request = rsc[cur]
|
|
289
298
|
static stack = stack
|
|
290
299
|
static _tag = RequestTypes.RAW
|
|
291
300
|
static handler = () => handlerImpl
|
|
292
301
|
}
|
|
302
|
+
// oxlint-disable-next-line typescript/no-extraneous-class
|
|
293
303
|
: class {
|
|
294
304
|
static request = rsc[cur]
|
|
295
305
|
static stack = stack
|
|
@@ -386,12 +396,15 @@ export const makeRouter = <
|
|
|
386
396
|
static success = S.toEncoded(resource.success)
|
|
387
397
|
} as any
|
|
388
398
|
: resource,
|
|
389
|
-
(payload: any, headers: any) =>
|
|
390
|
-
(handler.handler(payload, headers) as Effect.Effect<unknown, unknown, unknown>).pipe(
|
|
399
|
+
(payload: any, headers: any) => {
|
|
400
|
+
const effect = (handler.handler(payload, headers) as Effect.Effect<unknown, unknown, unknown>).pipe(
|
|
391
401
|
Effect.withSpan(`Request.${meta.moduleName}.${resource._tag}`, {}, {
|
|
392
402
|
captureStackTrace: () => handler.stack // capturing the handler stack is the main reason why we are doing the span here
|
|
393
403
|
})
|
|
394
404
|
)
|
|
405
|
+
|
|
406
|
+
return applyRequestTypeInterruptibility(resource.type, effect)
|
|
407
|
+
}
|
|
395
408
|
] as const
|
|
396
409
|
return acc
|
|
397
410
|
}, {} as any) as {
|
|
@@ -418,6 +431,7 @@ export const makeRouter = <
|
|
|
418
431
|
return Rpc
|
|
419
432
|
.make(resource._tag, { payload: resource, success: resource.success, error: resource.error })
|
|
420
433
|
.annotate(middleware.requestContext, resource.config ?? {})
|
|
434
|
+
.annotate(RequestTypeAnnotation, resource.type)
|
|
421
435
|
})
|
|
422
436
|
)
|
|
423
437
|
.prefix(`${meta.moduleName}.`)
|