aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/library/lux/world/net/http/client.lux
blob: f3851016adb4270ecf6140763e8040a6140789f7 (plain)
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
(.require
 [library
  [lux (.except)
   ["[0]" ffi]
   [abstract
    ["[0]" monad (.only do)]]
   [control
    ["[0]" pipe]
    ["[0]" io (.only IO)]
    ["[0]" maybe (.use "[1]#[0]" functor)]
    ["[0]" try (.only Try)]
    [concurrency
     ["[0]" async (.only Async)]]]
   [data
    ["[0]" binary (.only Binary)]
    ["[0]" text]
    [collection
     ["[0]" dictionary]]]
   [math
    [number
     ["n" nat]
     ["i" int]]]
   [meta
    ["@" target]
    ["[0]" code (.only)
     ["<[1]>" \\parser]]
    [macro
     [syntax (.only syntax)]
     ["[0]" template]]]]]
 ["[0]" // (.only)
  [response (.only Response)]
  ["[0]" header (.only Headers)]
  [// (.only URL)]])

(type .public (Client !)
  (Interface
   (is (-> //.Method URL Headers (Maybe Binary)
           (! (Try (Response !))))
       request)))

(def method_function
  (syntax (_ [[_ name] <code>.symbol])
    (in (list (code.local (text.replaced "#" "" (text.lower_cased name)))))))

(with_template [<method>]
  [(with_expansions [<name> (method_function <method>)]
     (def .public (<name> url headers data client)
       (All (_ !)
         (-> URL Headers (Maybe Binary) (Client !)
             (! (Try (Response !)))))
       (at client request {<method>} url headers data)))]

  [//.#Post]
  [//.#Get]
  [//.#Put]
  [//.#Patch]
  [//.#Delete]
  [//.#Head]
  [//.#Connect]
  [//.#Options]
  [//.#Trace]
  )

(def default_buffer_size
  (n.* 1,024 1,024))

(def empty_body
  [Nat Binary]
  [0 (binary.empty 0)])

(def (body_of data)
  (-> Binary [Nat Binary])
  [(binary.size data) data])

(with_expansions [<jvm> (these (ffi.import java/lang/String
                                 "[1]::[0]")

                               (ffi.import java/lang/AutoCloseable
                                 "[1]::[0]"
                                 (close [] "io" "try" void))

                               (ffi.import java/io/InputStream
                                 "[1]::[0]")

                               (ffi.import java/io/OutputStream
                                 "[1]::[0]"
                                 (flush [] "io" "try" void)
                                 (write [[byte]] "io" "try" void))

                               (ffi.import java/net/URLConnection
                                 "[1]::[0]"
                                 (setDoOutput [boolean] "io" "try" void)
                                 (setRequestProperty [java/lang/String java/lang/String] "io" "try" void)
                                 (getInputStream [] "io" "try" java/io/InputStream)
                                 (getOutputStream [] "io" "try" java/io/OutputStream)
                                 (getHeaderFieldKey [int] "io" "try" "?" java/lang/String)
                                 (getHeaderField [int] "io" "try" "?" java/lang/String))

                               (ffi.import java/net/HttpURLConnection
                                 "[1]::[0]"
                                 (setRequestMethod [java/lang/String] "io" "try" void)
                                 (getResponseCode [] "io" "try" int))

                               (ffi.import java/net/URL
                                 "[1]::[0]"
                                 (new [java/lang/String])
                                 (openConnection [] "io" "try" java/net/URLConnection))

                               (ffi.import java/io/BufferedInputStream
                                 "[1]::[0]"
                                 (new [java/io/InputStream])
                                 (read [[byte] int int] "io" "try" int))

                               (def jvm_method
                                 (-> //.Method Text)
                                 (|>> (pipe.when
                                        {//.#Post} "POST"
                                        {//.#Get} "GET"
                                        {//.#Put} "PUT"
                                        {//.#Patch} "PATCH"
                                        {//.#Delete} "DELETE"
                                        {//.#Head} "HEAD"
                                        {//.#Connect} "CONNECT"
                                        {//.#Options} "OPTIONS"
                                        {//.#Trace} "TRACE")))

                               (def (default_body input)
                                 (-> java/io/BufferedInputStream (//.Body IO))
                                 (|>> (maybe#each (|>> [true]))
                                      (maybe.else [false ..default_buffer_size])
                                      (pipe.when
                                        [_ 0]
                                        (do (try.with io.monad)
                                          [_ (java/lang/AutoCloseable::close input)]
                                          (in ..empty_body))

                                        [partial? buffer_size]
                                        (let [buffer (binary.empty buffer_size)]
                                          (if partial?
                                            (loop (again [so_far +0])
                                              (do [! (try.with io.monad)]
                                                [.let [remaining (i.- so_far (.int buffer_size))]
                                                 bytes_read (at ! each (|>> ffi.of_int)
                                                                (java/io/BufferedInputStream::read buffer (ffi.as_int so_far) (ffi.as_int remaining) input))]
                                                (when bytes_read
                                                  -1 (do !
                                                       [_ (java/lang/AutoCloseable::close input)]
                                                       (in [(.nat so_far) buffer]))
                                                  +0 (again so_far)
                                                  _ (if (i.= remaining bytes_read)
                                                      (in [buffer_size buffer])
                                                      (again (i.+ bytes_read so_far))))))
                                            (loop (again [so_far +0
                                                          output (at binary.monoid identity)])
                                              (do [! (try.with io.monad)]
                                                [.let [remaining (i.- so_far (.int buffer_size))]
                                                 bytes_read (at ! each (|>> ffi.of_int)
                                                                (java/io/BufferedInputStream::read buffer (ffi.as_int so_far) (ffi.as_int remaining) input))]
                                                (when bytes_read
                                                  -1 (do !
                                                       [_ (java/lang/AutoCloseable::close input)]
                                                       (when so_far
                                                         +0 (in (..body_of output))
                                                         _ (|> buffer
                                                               (binary.slice 0 (.nat so_far))
                                                               (at try.functor each
                                                                   (|>> (at binary.monoid composite output)
                                                                        ..body_of))
                                                               (at io.monad in))))
                                                  +0 (again so_far output)
                                                  _ (if (i.= remaining bytes_read)
                                                      (again +0
                                                             (at binary.monoid composite output buffer))
                                                      (again (i.+ bytes_read so_far)
                                                             output))))))))))

                               (def (default_headers connection)
                                 (-> java/net/HttpURLConnection (IO (Try Headers)))
                                 (loop (again [index +0
                                               headers header.empty])
                                   (do [! (try.with io.monad)]
                                     [?name (java/net/URLConnection::getHeaderFieldKey (ffi.as_int index) connection)]
                                     (when ?name
                                       {.#Some name}
                                       (do !
                                         [?value (java/net/URLConnection::getHeaderField (ffi.as_int index) connection)]
                                         (again (++ index)
                                                (dictionary.has (ffi.of_string name) (maybe.else "" (maybe#each (|>> ffi.of_string) ?value)) headers)))

                                       {.#None}
                                       (in headers)))))

                               (def .public default
                                 (Client IO)
                                 (implementation
                                  (def (request method url headers data)
                                    (is (IO (Try (Response IO)))
                                        (do [! (try.with io.monad)]
                                          [connection (|> url ffi.as_string java/net/URL::new java/net/URL::openConnection)
                                           .let [connection (as java/net/HttpURLConnection connection)]
                                           _ (java/net/HttpURLConnection::setRequestMethod (ffi.as_string (..jvm_method method)) connection)
                                           _ (monad.each ! (function (_ [name value])
                                                             (java/net/URLConnection::setRequestProperty (ffi.as_string name) (ffi.as_string value) connection))
                                                         (dictionary.entries headers))
                                           _ (when data
                                               {.#Some data}
                                               (do !
                                                 [_ (java/net/URLConnection::setDoOutput true connection)
                                                  stream (java/net/URLConnection::getOutputStream connection)
                                                  _ (java/io/OutputStream::write data stream)
                                                  _ (java/io/OutputStream::flush stream)
                                                  _ (java/lang/AutoCloseable::close stream)]
                                                 (in []))
                                               
                                               {.#None}
                                               (in []))
                                           status (java/net/HttpURLConnection::getResponseCode connection)
                                           headers (..default_headers connection)
                                           input (|> connection
                                                     java/net/URLConnection::getInputStream
                                                     (at ! each (|>> java/io/BufferedInputStream::new)))]
                                          (in [(.nat (ffi.of_int status))
                                               [//.#headers headers
                                                //.#body (..default_body input)]])))))))]
  (for @.old (these <jvm>)
       @.jvm (these <jvm>)
       (these)))

(def .public (async client)
  (-> (Client IO) (Client Async))
  (implementation
   (def (request method url headers data)
     (|> (at client request method url headers data)
         async.future
         (at async.monad each
             (|>> (pipe.when
                    {try.#Success [status message]}
                    {try.#Success [status (revised //.#body (is (-> (//.Body IO) (//.Body Async))
                                                                (function (_ body)
                                                                  (|>> body async.future)))
                                                   message)]}
                    
                    {try.#Failure error}
                    {try.#Failure error})))))))

(def .public headers
  (-> (List [Text Text]) Headers)
  (dictionary.of_list text.hash))