Skip to content

Commit

Permalink
get rid of 'sprintf'
Browse files Browse the repository at this point in the history
  • Loading branch information
ademar committed Sep 7, 2019
1 parent 00399ce commit a84ac8b
Show file tree
Hide file tree
Showing 18 changed files with 94 additions and 107 deletions.
5 changes: 3 additions & 2 deletions src/Suave/Authentication.fs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ let authenticateBasicAsync f protectedPart ctx =
| Choice2Of2 _ ->
challenge ctx

let authenticateBasic f protectedPart ctx =
let authenticateBasic f protectedPart ctx =
authenticateBasicAsync (f >> async.Return) protectedPart ctx

module internal Utils =
Expand Down Expand Up @@ -99,9 +99,10 @@ let authenticate relativeExpiry secure
cookieState state missingCookie decryptionFailure fSuccess)

let authenticateWithLogin relativeExpiry loginPage fSuccess : WebPart =
let decryptionFailure = (fun s -> s.ToString()) >> RequestErrors.BAD_REQUEST >> Choice2Of2
authenticate relativeExpiry false
(fun () -> Choice2Of2(Redirection.FOUND loginPage))
(sprintf "%A" >> RequestErrors.BAD_REQUEST >> Choice2Of2)
decryptionFailure
fSuccess

let authenticated relativeExpiry secure : WebPart =
Expand Down
63 changes: 30 additions & 33 deletions src/Suave/Combinators.fs
Original file line number Diff line number Diff line change
Expand Up @@ -171,23 +171,21 @@ module Redirection =
setHeader "Location" url
>=> setHeader "Content-Type" "text/html; charset=utf-8"
>=> response HTTP_302 (
UTF8.bytes(sprintf "<html>
UTF8.bytes("<html>
<body>
<a href=\"%s\">%s</a>
<a href=\"" + url + "\">" + HTTP_302.message + "</a>
</body>
</html>"
url HTTP_302.message))
</html>"))

let see_other url =
setHeader "Location" url
>=> setHeader "Content-Type" "text/html; charset=utf-8"
>=> response HTTP_303 (
UTF8.bytes(sprintf "<html>
UTF8.bytes("<html>
<body>
<a href=\"%s\">%s</a>
<a href=\"" + url + "\">" + HTTP_303.message + "</a>
</body>
</html>"
url HTTP_303.message))
</html>"))

let not_modified : WebPart =
fun ctx -> { ctx with response = {status = HTTP_304.status; headers = []; content = Bytes [||]; writePreamble = true }} |> succeed
Expand Down Expand Up @@ -353,19 +351,18 @@ module Filters =
let dash = function | "" | null -> "-" | x -> x
let ci = Globalization.CultureInfo("en-US")
let processId = System.Diagnostics.Process.GetCurrentProcess().Id.ToString()
sprintf "%O %s %s [%s] \"%s %s %s\" %d %d"
ctx.clientIpTrustProxy
processId //TODO: obtain connection owner via Ident protocol
// Authentication.UserNameKey
(match Map.tryFind "userName" ctx.userState with Some x -> x :?> string | None -> "-")
(DateTime.UtcNow.ToString("dd/MMM/yyyy:hh:mm:ss %K", ci))
(string ctx.request.``method``)
ctx.request.url.AbsolutePath
ctx.request.httpVersion
ctx.response.status.code
(match ctx.response.content with
| Bytes bs -> bs.Length
| _ -> 0)
ctx.clientIpTrustProxy.ToString() + " " +
processId + " " + //TODO: obtain connection owner via Ident protocol
// Authentication.UserNameKey
(match Map.tryFind "userName" ctx.userState with Some x -> x :?> string | None -> "-") + " [" +
(DateTime.UtcNow.ToString("dd/MMM/yyyy:hh:mm:ss %K", ci)) + "] \"" +
(string ctx.request.``method``) + " " +
ctx.request.url.AbsolutePath + " " +
ctx.request.httpVersion + "\" " +
ctx.response.status.code.ToString() + " " +
(match ctx.response.content with
| Bytes bs -> bs.Length.ToString()
| _ -> "0")

let logFormatStructured (ctx : HttpContext) =
let fieldList : (string*obj) list = [
Expand Down Expand Up @@ -426,13 +423,13 @@ module Filters =
| None ->
fail
F

let pathScanCi (format : PrintfFormat<_,_,_,_,'t>) (handler : 't -> WebPart) : WebPart =
let scan path =
try
let extract = sscanfci format path
Some extract
with _ ->
with _ ->
None

let part (context:HttpContext) =
Expand Down Expand Up @@ -502,10 +499,10 @@ module ServeResource =
sendIt value.name value.compression ctx
| None ->
let ext = getExtension key
log (sprintf "failed to find matching mime for ext '%s'" ext)
log ("failed to find matching mime for ext '" + ext + "'")
fail
else
log (sprintf "failed to find resource by key '%s'" key)
log ("failed to find resource by key '" + key + "'")
fail

module ContentRange =
Expand All @@ -519,7 +516,7 @@ module ContentRange =
let start = int64 rangeArray.[0]
let finish = if Int64.TryParse (rangeArray.[1], ref 0L) then Some <| int64 rangeArray.[1] else None
start, finish

let (|ContentRange|_|) (context:HttpContext) =
match context.request.header "range" with
| Choice1Of2 rangeValue -> Some <| parseContentRange rangeValue
Expand Down Expand Up @@ -561,16 +558,16 @@ module Files =
try
match encoding with
| Some n ->
let! (_,conn) = asyncWriteLn (sprintf "Content-Range: bytes %d-%d/*" start finish) conn
let! (_,conn) = asyncWriteLn ("Content-Range: bytes " + start.ToString() + "-" + finish.ToString() + "/*") conn
let! (_,conn) = asyncWriteLn (String.Concat [| "Content-Encoding: "; n.ToString() |]) conn
let! (_,conn) = asyncWriteLn (sprintf "Content-Length: %d\r\n" (fs : Stream).Length) conn
let! (_,conn) = asyncWriteLn ("Content-Length: " + (fs : Stream).Length.ToString() + "\r\n") conn
let! conn = flush conn
if ctx.request.``method`` <> HttpMethod.HEAD && fs.Length > 0L then
do! transferStream conn fs
return conn
| None ->
let! (_,conn) = asyncWriteLn (sprintf "Content-Range: bytes %d-%d/%d" start finish total) conn
let! (_,conn) = asyncWriteLn (sprintf "Content-Length: %d\r\n" (fs : Stream).Length) conn
let! (_,conn) = asyncWriteLn ("Content-Range: bytes " + start.ToString() + "-" + finish.ToString() + "/" + total.ToString()) conn
let! (_,conn) = asyncWriteLn ("Content-Length: " + (fs : Stream).Length.ToString() + "\r\n") conn
let! conn = flush conn
if ctx.request.``method`` <> HttpMethod.HEAD && fs.Length > 0L then
do! transferStream conn fs
Expand Down Expand Up @@ -688,14 +685,14 @@ module Embedded =
match encoding with
| Some n ->
let! (_,conn) = asyncWriteLn (String.Concat [| "Content-Encoding: "; n.ToString() |]) conn
let! (_,conn) = asyncWriteLn (sprintf "Content-Length: %d\r\n" (fs: Stream).Length) conn
let! (_,conn) = asyncWriteLn ("Content-Length: " + (fs: Stream).Length.ToString() + "\r\n") conn
let! conn = flush conn
if ctx.request.``method`` <> HttpMethod.HEAD && fs.Length > 0L then
do! transferStream conn fs
fs.Dispose()
return conn
| None ->
let! (_,conn) = asyncWriteLn (sprintf "Content-Length: %d\r\n" (fs: Stream).Length) conn
let! (_,conn) = asyncWriteLn ("Content-Length: " + (fs: Stream).Length.ToString() + "\r\n") conn
let! conn = flush conn
if ctx.request.``method`` <> HttpMethod.HEAD && fs.Length > 0L then
do! transferStream conn fs
Expand Down Expand Up @@ -956,7 +953,7 @@ module CORS =
| InclusiveOption.Some (m :: ms) ->
let exists = m.ToString() = value || List.exists (fun m -> m.ToString() = value) ms
if exists then
let header = sprintf "%s,%s" (m.ToString()) (ms |> Seq.map (fun i -> i.ToString()) |> String.concat( ", "))
let header = (m.ToString()) + "," + (ms |> Seq.map (fun i -> i.ToString()) |> String.concat( ", "))
Writers.setHeader AccessControlAllowMethods header
else
succeed
Expand Down
8 changes: 3 additions & 5 deletions src/Suave/Cookie.fs
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ module Cookie =


succeed { ctx with response = { ctx.response with headers = headers' } }


let unsetCookie (cookieName : string) =
let startEpoch = DateTimeOffset(1970, 1, 1, 0, 0, 1, TimeSpan.Zero) |> Some
Expand Down Expand Up @@ -239,9 +239,7 @@ module Cookie =
: WebPart =
context (fun ctx ->
let debug message =
ctx.runtime.logger.debug (
eventX message
>> setSingleName "Suave.Cookie.cookieState")
ctx.runtime.logger.debug (eventX message >> setSingleName "Suave.Cookie.cookieState")

let setCookies plainText =
let httpCookie, clientCookie =
Expand Down Expand Up @@ -270,7 +268,7 @@ module Cookie =
wp_kont

| Choice2Of2 (DecryptionError err) ->
debug (sprintf "decryption error: %A" err)
debug ("decryption error: " + err.ToString())
match decryptionFailure err with
| Choice1Of2 plainText ->
debug "Existing, broken cookie, setting cookie text anew"
Expand Down
4 changes: 2 additions & 2 deletions src/Suave/Headers.fs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ module Headers =
match System.Decimal.TryParse(s, System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture) with
| true, d -> Some d
| _ -> None

/// Parse a culture info as given in the 'Accept-Language' Header field.
let parseCultureInfo =
let cultureNames =
Expand Down Expand Up @@ -104,5 +104,5 @@ module Headers =
/// Headers are lowercased, so can use string.Equals
let getAll (target : NameValueList) (key : string) =
match target |> List.choose (fun (a, b) -> if a.Equals key then Some b else None) with
| [] -> Choice2Of2 (sprintf "Couldn't find key '%s' in NameValueList" key)
| [] -> Choice2Of2 ("Couldn't find key '" + key + "' in NameValueList")
| l -> Choice1Of2 l
12 changes: 6 additions & 6 deletions src/Suave/Http.fs
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ module Http =
| HTTP_505 -> "Cannot fulfill request."

member x.describe () =
sprintf "%d %s: %s" x.code x.reason x.message
x.code.ToString() + " " + x.reason + ": " + x.message

member x.status = { code = x.code; reason = x.reason }

Expand All @@ -207,7 +207,7 @@ module Http =
Choice1Of2 x

| None ->
Choice2Of2 (sprintf "Couldn't convert %i to HttpCode. Please send a PR to https://github.com/suaveio/suave if you want it" code)
Choice2Of2 ("Couldn't convert " + code.ToString() + " to HttpCode. Please send a PR to https://github.com/suaveio/suave if you want it")

and private HttpCodeStatics() =
static member val mapCases : Lazy<Map<string,HttpCode>> =
Expand Down Expand Up @@ -516,18 +516,18 @@ module Http =
static member writePreamble_ = Property<HttpResult,_> (fun x -> x.writePreamble) (fun v x -> { x with writePreamble = v })

type ServerKey = byte []

[<CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)>]
module ServerKey =

let validate (key : ServerKey) =
if key.Length <> int Crypto.KeyLength then
failwithf "Invalid server key length - should be %i, but was %i" Crypto.KeyLength key.Length
key

let fromBase64 =
Convert.FromBase64String >> validate

type IPAddress with
static member tryParseC str =
match IPAddress.TryParse str with
Expand Down
8 changes: 4 additions & 4 deletions src/Suave/Model.fs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ module SyntacticSugar =
let (>>.) a f = Choice.bind f a

type ChoiceBuilder() =

member x.Bind (v, f) = Choice.bind f v
member x.Return v = Choice1Of2 v
member x.ReturnFrom o = o
Expand Down Expand Up @@ -39,15 +39,15 @@ module Binding =

let header key f (req : HttpRequest) =
req.header key
|> Choice.mapSnd (fun _ -> sprintf "Missing header '%s'" key)
|> Choice.mapSnd (fun _ -> "Missing header '" + key + "'")
|> Choice.bind f

let form formKey f (req : HttpRequest) =
req.formData formKey
|> Choice.mapSnd (fun _ -> sprintf "Missing form field '%s'" formKey)
|> Choice.mapSnd (fun _ -> "Missing form field '" + formKey + "'")
|> Choice.bind f

let query queryKey f (req : HttpRequest) =
req.queryParam queryKey
|> Choice.mapSnd (fun _ -> sprintf "Missing query string key '%s'" queryKey)
|> Choice.mapSnd (fun _ -> "Missing query string key '" + queryKey + "'")
|> Choice.bind f
6 changes: 3 additions & 3 deletions src/Suave/Owin.fs
Original file line number Diff line number Diff line change
Expand Up @@ -341,7 +341,7 @@ module OwinApp =
| "https" ->
HTTPS null
| _ ->
invalidOp (sprintf "Invalid scheme: '%s'" v)})
invalidOp ("Invalid scheme: '" + v + "'")})

let uriAbsolutePath : Property<_, _> =
(fun (uri : Uri) -> uri.AbsolutePath),
Expand Down Expand Up @@ -500,9 +500,9 @@ module OwinApp =
OwinConstants.CommonKeys.clientCertificate, constant Unchecked.defaultof<Security.Cryptography.X509Certificates.X509Certificate>
OwinConstants.CommonKeys.onSendingHeaders, onSendingHeadersLens <--> untyped
OwinConstants.CommonKeys.isLocal, HttpContext.isLocal_ <--> untyped
OwinConstants.CommonKeys.localIpAddress, HttpContext.runtime_ >--> HttpRuntime.matchedBinding_ >--> HttpBinding.socketBinding_ >--> SocketBinding.ip_ <--> stringlyTyped (sprintf "%O") IPAddress.Parse <--> untyped
OwinConstants.CommonKeys.localIpAddress, HttpContext.runtime_ >--> HttpRuntime.matchedBinding_ >--> HttpBinding.socketBinding_ >--> SocketBinding.ip_ <--> stringlyTyped (fun s -> s.ToString()) IPAddress.Parse <--> untyped
OwinConstants.CommonKeys.localPort, HttpContext.runtime_ >--> HttpRuntime.matchedBinding_ >--> HttpBinding.socketBinding_ >--> SocketBinding.port_ <--> stringlyTyped string uint16 <--> untyped
OwinConstants.CommonKeys.remoteIpAddress, HttpContext.clientIp_ <--> stringlyTyped (sprintf "%O") IPAddress.Parse <--> untyped
OwinConstants.CommonKeys.remoteIpAddress, HttpContext.clientIp_ <--> stringlyTyped (fun s -> s.ToString()) IPAddress.Parse <--> untyped
OwinConstants.CommonKeys.remotePort, HttpContext.clientPort_ <--> stringlyTyped string uint16 <--> untyped
OwinConstants.CommonKeys.traceOutput, HttpContext.runtime_ >--> HttpRuntime.logger_ >--> ((fun x -> textWriter x), (fun v x -> x)) <--> untyped

Expand Down
4 changes: 2 additions & 2 deletions src/Suave/State.fs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ module CookieStateStore =
>> setSingleName "Suave.State.CookieStateStore.stateful")

let cipherTextCorrupt =
sprintf "%A" >> RequestErrors.BAD_REQUEST >> Choice2Of2
(fun s -> s.ToString()) >> RequestErrors.BAD_REQUEST >> Choice2Of2

let setExpiry : WebPart =
Writers.setUserData (StateStoreType + "-expiry") relativeExpiry
Expand All @@ -93,7 +93,7 @@ module CookieStateStore =
let private createStateStore (serialiser : CookieSerialiser) (userState : Map<string, obj>) (ss : obj) =
{ new StateStore with
member x.get key =
ss
ss
:?> byte []
|> serialiser.deserialise
|> Map.tryFind key
Expand Down
4 changes: 1 addition & 3 deletions src/Suave/Tcp.fs
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,7 @@ type StartedData =
member x.GetStartedListeningElapsedMilliseconds() =
((x.socketBoundUtc |> Option.fold (fun _ t -> t) x.startCalledUtc) - x.startCalledUtc).TotalMilliseconds
override x.ToString() =
sprintf "%.3f ms with binding %O:%d"
(x.GetStartedListeningElapsedMilliseconds())
x.binding.ip x.binding.port
(x.GetStartedListeningElapsedMilliseconds()).ToString() + " ms with binding " + x.binding.ip.ToString() + ":" + x.binding.port.ToString()

/// Stop the TCP listener server
let stopTcp reason (socket : Socket) =
Expand Down
2 changes: 1 addition & 1 deletion src/Suave/Utils/Choice.fs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ let parser (parse : string -> bool * 'a) (err : string) =
fun original ->
match parse original with
| true, res -> Choice1Of2 res
| _, _ -> Choice2Of2 (sprintf "%s. Input value \"%O\"" err original)
| _, _ -> Choice2Of2 (err + ". Input value '" + original + "'" )

module Operators =

Expand Down
8 changes: 4 additions & 4 deletions src/Suave/Utils/Collections.fs
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,17 @@ type IDictionary<'b,'a> with
member dict.TryLookup key =
match dict.TryGetValue key with
| true, v -> Choice1Of2 v
| false, _ -> Choice2Of2 (sprintf "Key %A was not present" key)
| false, _ -> Choice2Of2 ("Key " + (key.ToString()) + " was not present")

let getFirst (target : NameValueList) (key : string) =
match target |> List.tryPick (fun (a, b) -> if a.Equals key then Some b else None) with
| Some b -> Choice1Of2 b
| None -> Choice2Of2 (sprintf "Couldn't find key '%s' in NameValueList" key)
| None -> Choice2Of2 ("Couldn't find key '" + key + "' in NameValueList")

let getFirstCaseInsensitive (target : NameValueList) (key : string) =
match target |> List.tryPick (fun (a, b) -> if String.equalsCaseInsensitive a key then Some b else None) with
| Some b -> Choice1Of2 b
| None -> Choice2Of2 (sprintf "Couldn't find key '%s' in NameValueList" key)
| None -> Choice2Of2 ("Couldn't find key '" + key + "' in NameValueList")

[<System.Obsolete("Use getFirstCaseInsensitive with an i")>]
let getFirstCaseInsensitve (target : NameValueList) (key : string) =
Expand All @@ -33,7 +33,7 @@ let getFirstCaseInsensitve (target : NameValueList) (key : string) =
let getFirstOpt (target : NameOptionValueList) (key : string) =
match target |> List.tryPick (fun (a,b) -> if a.Equals key then b else None) with
| Some b -> Choice1Of2 b
| None -> Choice2Of2 (sprintf "Couldn't find key '%s' in NameOptionValueList" key)
| None -> Choice2Of2 ("Couldn't find key '" + key + "' in NameOptionValueList")

let tryGetChoice1 f x =
match f x with
Expand Down
6 changes: 2 additions & 4 deletions src/Suave/Utils/Crypto.fs
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ let private secretboxInit key iv =

let secretbox (key : byte []) (msg : byte []) =
if key.Length <> int KeyLength then
Choice2Of2 (InvalidKeyLength (sprintf "key should be %d bytes but was %d bytes" KeyLength (key.Length)))
Choice2Of2 (InvalidKeyLength ("key should be " + (KeyLength.ToString()) + " bytes but was " + (key.Length.ToString()) + " bytes" ))
elif msg.Length = 0 then
Choice2Of2 EmptyMessageGiven
else
Expand Down Expand Up @@ -140,9 +140,7 @@ let secretboxOpen (key : byte []) (cipherText : byte []) =

if cipherText.Length < int (HMACLength + IVLength) then
Choice2Of2 (
TruncatedMessage (
sprintf "cipher text length was %d but expected >= %d"
cipherText.Length (HMACLength + IVLength)))
TruncatedMessage ("cipher text length was " + (cipherText.Length.ToString()) + " but expected >= " + (HMACLength + IVLength).ToString()))
elif not (Bytes.equalsConstantTime hmacCalc hmacGiven) then
Choice2Of2 (AlteredOrCorruptMessage "calculated HMAC does not match expected/given")
else
Expand Down
Loading

0 comments on commit a84ac8b

Please sign in to comment.