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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
|
namespace FundLab.Api
open System
open System.Globalization
open System.IO
open System.Text.Json
open Giraffe
open Microsoft.AspNetCore.Http
type EmptyPortfolioResponse =
{
status: string
message: string
}
type FundApiResponse =
{
id: Guid
name: string
currency: string
initialCash: string
initialUnitNav: string
isSynthetic: bool
availableCash: string
status: string
}
type ApiErrorResponse =
{
error: string
message: string
}
type MarketDataInstrumentApiResponse =
{
code: string
name: string
fundType: string option
}
type MarketDataSearchApiResponse =
{
source: string
sourceRevision: string
collectedAt: string
instruments: MarketDataInstrumentApiResponse list
}
type MarketDataObservationApiResponse =
{
code: string
navDate: string
publishedAt: string option
nav: string
accumulatedNav: string option
dailyReturn: string option
source: string
sourceRevision: string
sourceCollectedAt: string
sourcePayloadHash: string
firstSeenAt: string
lastSeenAt: string
}
type MarketDataNavApiResponse =
{
code: string
observations: MarketDataObservationApiResponse list
}
module App =
let private invariant = CultureInfo.InvariantCulture
let private cashText (value: decimal) = value.ToString("0.00", invariant)
let private unitNavText (value: decimal) = value.ToString("0.00000000", invariant)
let private decimalText (value: decimal) = value.ToString("0.00000000", invariant)
let private dateText (value: DateOnly) = value.ToString("yyyy-MM-dd", invariant)
let private timestampText (value: DateTimeOffset) = value.ToString("O", invariant)
let private fundResponse (fund: FundRecord) : FundApiResponse =
{
id = fund.Id
name = fund.Name
currency = fund.Currency
initialCash = cashText fund.InitialCash
initialUnitNav = unitNavText fund.InitialUnitNav
isSynthetic = fund.IsSynthetic
availableCash = cashText fund.AvailableCash
status = fund.Status
}
let private errorResponse status error message : HttpHandler =
setStatusCode status
>=> json ({
error = error
message = message
} : ApiErrorResponse)
let private tryStringProperty (root: JsonElement) (name: string) =
let mutable property = Unchecked.defaultof<JsonElement>
if root.TryGetProperty(name, &property) && property.ValueKind = JsonValueKind.String then
property.GetString() |> Option.ofObj
else
None
let private tryBoolProperty (root: JsonElement) (name: string) =
let mutable property = Unchecked.defaultof<JsonElement>
if root.TryGetProperty(name, &property) then
match property.ValueKind with
| JsonValueKind.True -> Some true
| JsonValueKind.False -> Some false
| _ -> None
else
None
let private tryDecimal (label: string) (text: string) =
if String.IsNullOrWhiteSpace text then
Error(sprintf "%s must be a decimal string" label)
else
match Decimal.TryParse(text, NumberStyles.AllowLeadingSign ||| NumberStyles.AllowDecimalPoint, invariant) with
| true, value -> Ok value
| false, _ -> Error(sprintf "%s must be a decimal string" label)
let private parseFundCommand (body: string) =
try
use document = JsonDocument.Parse(body)
let root = document.RootElement
if root.ValueKind <> JsonValueKind.Object then
Error "request body must be a JSON object"
else
match tryStringProperty root "name", tryStringProperty root "initialCash", tryStringProperty root "initialUnitNav", tryBoolProperty root "isSynthetic" with
| Some name, Some initialCashText, Some initialUnitNavText, Some isSynthetic ->
match tryDecimal "initialCash" initialCashText, tryDecimal "initialUnitNav" initialUnitNavText with
| Ok initialCash, Ok initialUnitNav ->
Ok {
Name = name
InitialCash = initialCash
InitialUnitNav = initialUnitNav
IsSynthetic = isSynthetic
}
| Error message, _
| _, Error message -> Error message
| _ ->
Error "name, initialCash, initialUnitNav and isSynthetic are required"
with
| :? JsonException -> Error "request body must be valid JSON"
let private invokeHandler handler next ctx = handler next ctx
let private unauthorized : HttpHandler =
setStatusCode 401
>=> setHttpHeader "WWW-Authenticate" "Bearer"
>=> text "Unauthorized"
let private requireBearer (next: HttpFunc) (ctx: HttpContext) =
let expectedToken =
Environment.GetEnvironmentVariable("FUND_LAB_AUTH_TOKEN")
|> Option.ofObj
|> Option.defaultValue ""
let authorizationHeader = ctx.Request.Headers.Authorization.ToString()
match Authentication.authorize expectedToken authorizationHeader with
| AuthDecision.Authorized -> next ctx
| AuthDecision.Unauthorized -> unauthorized next ctx
let private health : HttpHandler =
json ({
service = "fund-lab-api"
status = "ok"
} : HealthResponse)
let private emptyPortfolio : HttpHandler =
json ({
status = "empty"
message = "尚未创建基金/尚未选择投资"
} : EmptyPortfolioResponse)
let private createFund (repository: FundRepository) : HttpHandler =
fun next ctx ->
task {
use reader = new StreamReader(ctx.Request.Body)
let! body = reader.ReadToEndAsync()
let idempotencyKey = ctx.Request.Headers["Idempotency-Key"].ToString()
match parseFundCommand body with
| Error message ->
return! invokeHandler (errorResponse 400 "INVALID_FUND_REQUEST" message) next ctx
| Ok command ->
try
match repository.CreateFund(idempotencyKey, command) with
| FundWriteResult.Created fund ->
return! invokeHandler (setStatusCode 201 >=> json (fundResponse fund)) next ctx
| FundWriteResult.Replayed fund ->
return! invokeHandler (json (fundResponse fund)) next ctx
| FundWriteResult.IdempotencyConflict ->
return! invokeHandler (errorResponse 409 "IDEMPOTENCY_CONFLICT" "idempotency key was used with a different request") next ctx
| FundWriteResult.Invalid message ->
return! invokeHandler (errorResponse 400 "INVALID_FUND_REQUEST" message) next ctx
with _ ->
return! invokeHandler (errorResponse 500 "PERSISTENCE_ERROR" "fund persistence failed") next ctx
}
let private getFund (repository: FundRepository) (fundIdText: string) : HttpHandler =
fun next ctx ->
match Guid.TryParse fundIdText with
| false, _ -> errorResponse 400 "INVALID_FUND_ID" "fund id must be a UUID" next ctx
| true, fundId ->
try
match repository.GetFund fundId with
| Some fund -> json (fundResponse fund) next ctx
| None -> errorResponse 404 "FUND_NOT_FOUND" "fund was not found" next ctx
with _ ->
errorResponse 500 "PERSISTENCE_ERROR" "fund persistence failed" next ctx
let private marketDataError (failure: MarketDataFailure) : HttpHandler =
let status, error, message =
match failure with
| InvalidMarketDataRequest message -> 400, "INVALID_MARKET_DATA_REQUEST", message
| MarketDataCollectorUnavailable message -> 503, "MARKET_DATA_UNAVAILABLE", message
| InvalidMarketDataPayload message -> 502, "INVALID_MARKET_DATA_PAYLOAD", message
| MarketDataPersistenceFailure _ -> 500, "PERSISTENCE_ERROR", "market data persistence failed"
errorResponse status error message
let private marketDataInstrumentResponse (instrument: MarketDataInstrument) =
{
code = instrument.Code
name = instrument.Name
fundType = instrument.FundType
}
let private marketDataSearchResponse (payload: MarketDataSearchPayload) =
{
source = payload.Source
sourceRevision = payload.SourceRevision
collectedAt = timestampText payload.CollectedAt
instruments = payload.Instruments |> List.map marketDataInstrumentResponse
}
let private marketDataObservationResponse (observation: MarketDataNavRecord) =
{
code = observation.Code
navDate = dateText observation.NavDate
publishedAt = observation.PublishedAt |> Option.map timestampText
nav = decimalText observation.Nav
accumulatedNav = observation.AccumulatedNav |> Option.map decimalText
dailyReturn = observation.DailyReturn |> Option.map decimalText
source = observation.Source
sourceRevision = observation.SourceRevision
sourceCollectedAt = timestampText observation.SourceCollectedAt
sourcePayloadHash = observation.SourcePayloadHash
firstSeenAt = timestampText observation.FirstSeenAt
lastSeenAt = timestampText observation.LastSeenAt
}
let private marketDataNavResponse code observations =
{
code = code
observations = observations |> List.map marketDataObservationResponse
}
let private searchInstruments (marketData: IMarketDataService) : HttpHandler =
fun next ctx ->
match marketData.Search(ctx.Request.Query["q"].ToString()) with
| Ok payload -> json (marketDataSearchResponse payload) next ctx
| Error failure -> marketDataError failure next ctx
let private refreshNav (marketData: IMarketDataService) (code: string) : HttpHandler =
fun next ctx ->
match marketData.RefreshNav code with
| Ok observations -> json (marketDataNavResponse code observations) next ctx
| Error failure -> marketDataError failure next ctx
let private queryDate (name: string) (ctx: HttpContext) =
let value = ctx.Request.Query[name].ToString()
if String.IsNullOrWhiteSpace value then
Ok None
else
let mutable date = DateOnly.MinValue
if DateOnly.TryParseExact(value, "yyyy-MM-dd", invariant, DateTimeStyles.None, &date) then
Ok(Some date)
else
Error(sprintf "%s must be an ISO date" name)
let private getNav (marketData: IMarketDataService) (code: string) : HttpHandler =
fun next ctx ->
match queryDate "from" ctx, queryDate "to" ctx with
| Ok fromDate, Ok toDate ->
match marketData.GetNav(code, fromDate, toDate) with
| Ok observations -> json (marketDataNavResponse code observations) next ctx
| Error failure -> marketDataError failure next ctx
| Error message, _
| _, Error message ->
marketDataError (InvalidMarketDataRequest message) next ctx
let private marketDataRoutes (marketData: IMarketDataService) =
[
GET >=> route "/instruments/search" >=> searchInstruments marketData
POST >=> routef "/instruments/%s/nav/refresh" (refreshNav marketData)
GET >=> routef "/instruments/%s/nav" (getNav marketData)
]
let private createApplicationInternal (repository: FundRepository) (marketData: IMarketDataService option) : HttpHandler =
let apiRoutes =
[
GET >=> route "/portfolio/summary" >=> emptyPortfolio
POST >=> route "/funds" >=> createFund repository
GET >=> routef "/funds/%s" (getFund repository)
]
@ (marketData |> Option.map marketDataRoutes |> Option.defaultValue [])
choose [
GET >=> route "/health" >=> health
subRoute "/api" (
requireBearer
>=> choose apiRoutes
)
setStatusCode 404 >=> text "Not Found"
]
let createApplicationWithMarketData (repository: FundRepository) (marketData: IMarketDataService) : HttpHandler =
createApplicationInternal repository (Some marketData)
let createApplication (repository: FundRepository) : HttpHandler =
createApplicationInternal repository None
|