-
Notifications
You must be signed in to change notification settings - Fork 60
Expand file tree
/
Copy pathProvider.OpenApiClient.fs
More file actions
165 lines (132 loc) · 7.93 KB
/
Provider.OpenApiClient.fs
File metadata and controls
165 lines (132 loc) · 7.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
namespace SwaggerProvider
open System
open System.Reflection
open Microsoft.OpenApi.Reader
open ProviderImplementation.ProvidedTypes
open Microsoft.FSharp.Core.CompilerServices
open Microsoft.FSharp.Quotations
open Microsoft.FSharp.Reflection
open Swagger
open SwaggerProvider.Internal
open SwaggerProvider.Internal.v3.Compilers
module OpenApiCache =
let providedTypes = Caching.createInMemoryCache(TimeSpan.FromMinutes 5.0)
/// The Open API Provider.
[<TypeProvider>]
type public OpenApiClientTypeProvider(cfg: TypeProviderConfig) as this =
inherit
TypeProviderForNamespaces(
cfg,
assemblyReplacementMap = [ ("SwaggerProvider.DesignTime", "SwaggerProvider.Runtime") ],
addDefaultProbingLocation = true
)
let ns = "SwaggerProvider"
let asm = Assembly.GetExecutingAssembly()
// check we contain a copy of runtime files, and are not referencing the runtime DLL
do assert (typeof<ProvidedApiClientBase>.Assembly.GetName().Name = asm.GetName().Name)
let buildStringListExpr(items: string list) : Expr =
let cases = FSharpType.GetUnionCases typeof<string list>
let nilCase = cases |> Array.find(fun c -> c.Name = "Empty")
let consCase = cases |> Array.find(fun c -> c.Name = "Cons")
let nil = Expr.NewUnionCase(nilCase, [])
List.foldBack (fun (s: string) acc -> Expr.NewUnionCase(consCase, [ Expr.Value(s, typeof<string>); acc ])) items nil
let myParamType =
let t =
ProvidedTypeDefinition(asm, ns, "OpenApiClientProvider", Some typeof<obj>, isErased = false)
let staticParams =
[ ProvidedStaticParameter("Schema", typeof<string>)
ProvidedStaticParameter("IgnoreOperationId", typeof<bool>, false)
ProvidedStaticParameter("IgnoreControllerPrefix", typeof<bool>, true)
ProvidedStaticParameter("PreferNullable", typeof<bool>, false)
ProvidedStaticParameter("PreferAsync", typeof<bool>, false)
ProvidedStaticParameter("SsrfProtection", typeof<bool>, true)
ProvidedStaticParameter("IgnoreParseErrors", typeof<bool>, false) ]
t.AddXmlDoc
"""<summary>Statically typed OpenAPI provider.</summary>
<param name='Schema'>Url or Path to OpenAPI schema file.</param>
<param name='IgnoreOperationId'>Do not use `operationsId` and generate method names using `path` only. Default value `false`.</param>
<param name='IgnoreControllerPrefix'>Do not parse `operationsId` as `<controllerName>_<methodName>` and generate one client class for all operations. Default value `true`.</param>
<param name='PreferNullable'>Provide `Nullable<_>` for not required properties, instead of `Option<_>`. Defaults value `false`.</param>
<param name='PreferAsync'>Generate async actions of type `Async<'T>` instead of `Task<'T>`. Defaults value `false`.</param>
<param name='SsrfProtection'>Enable SSRF protection (blocks HTTP and localhost). Set to false for development/testing. Default value `true`.</param>
<param name='IgnoreParseErrors'>Continue generating the provider even when the OpenAPI parser reports validation errors (e.g. vendor extensions or non-strictly-compliant schemas). Warnings are printed to stderr. Default value `false`.</param>"""
t.DefineStaticParameters(
staticParams,
fun typeName args ->
let schemaPathRaw = unbox<string> args.[0]
let ignoreOperationId = unbox<bool> args.[1]
let ignoreControllerPrefix = unbox<bool> args.[2]
let preferNullable = unbox<bool> args.[3]
let preferAsync = unbox<bool> args.[4]
let ssrfProtection = unbox<bool> args.[5]
let ignoreParseErrors = unbox<bool> args.[6]
// Cache key includes cfg.RuntimeAssembly, cfg.ResolutionFolder, and cfg.SystemRuntimeAssemblyVersion
// to differentiate between different TFM builds (same approach as FSharp.Data)
// See: https://github.com/fsprojects/FSharp.Data/blob/main/src/FSharp.Data.DesignTime/CommonProviderImplementation/Helpers.fs
let cacheKey =
(schemaPathRaw,
ignoreOperationId,
ignoreControllerPrefix,
preferNullable,
preferAsync,
ssrfProtection,
ignoreParseErrors,
cfg.RuntimeAssembly,
cfg.ResolutionFolder,
cfg.SystemRuntimeAssemblyVersion)
|> sprintf "%A"
let addCache() =
lazy
let schemaData =
SchemaReader.readSchemaPath (not ssrfProtection) "" cfg.ResolutionFolder schemaPathRaw
|> Async.RunSynchronously
let settings = OpenApiReaderSettings()
settings.AddYamlReader()
let readResult =
Microsoft.OpenApi.OpenApiDocument.Parse(schemaData, settings = settings)
let schema, diagnostic = (readResult.Document, readResult.Diagnostic)
if diagnostic.Errors.Count > 0 then
if ignoreParseErrors then
diagnostic.Errors
|> Seq.iter(fun e -> eprintfn "SwaggerProvider warning: %s @ %s" e.Message e.Pointer)
else
failwithf
"Schema parse errors:\n%s"
(diagnostic.Errors
|> Seq.map(fun e -> $"%s{e.Message} @ %s{e.Pointer}")
|> String.concat "\n")
let parseErrors =
diagnostic.Errors
|> Seq.map(fun e -> $"%s{e.Message} @ %s{e.Pointer}")
|> Seq.toList
let useDateOnly = cfg.SystemRuntimeAssemblyVersion.Major >= 6
let defCompiler = DefinitionCompiler(schema, preferNullable, useDateOnly)
let opCompiler =
OperationCompiler(schema, defCompiler, ignoreControllerPrefix, ignoreOperationId, preferAsync)
opCompiler.CompileProvidedClients(defCompiler.Namespace)
let tys = defCompiler.Namespace.GetProvidedTypes()
let tempAsm = ProvidedAssembly()
let ty =
ProvidedTypeDefinition(tempAsm, ns, typeName, Some typeof<obj>, isErased = false, hideObjectMethods = true)
ty.AddXmlDoc("OpenAPI Provider for " + schemaPathRaw)
ty.AddMembers tys
let errProp =
ProvidedProperty(
"SchemaReaderErrors",
typeof<string list>,
isStatic = true,
getterCode = fun _ -> buildStringListExpr parseErrors
)
errProp.AddXmlDoc
"List of OpenAPI parse errors tolerated by this provider instance. Non-empty only when IgnoreParseErrors=true and the schema has validation issues."
ty.AddMember errProp
tempAsm.AddTypes [ ty ]
ty
try
OpenApiCache.providedTypes.GetOrAdd(cacheKey, addCache).Value
with _ ->
OpenApiCache.providedTypes.Remove(cacheKey) |> ignore
OpenApiCache.providedTypes.GetOrAdd(cacheKey, addCache).Value
)
t
do this.AddNamespace(ns, [ myParamType ])