-
Notifications
You must be signed in to change notification settings - Fork 33
/
simple-twitter.nix
453 lines (365 loc) · 14.7 KB
/
simple-twitter.nix
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
let
region = "us-west-1";
accessKeyId = "default";
in
{ machine = { config, pkgs, resources, ... }: {
deployment = {
targetEnv = "ec2";
ec2 = {
inherit accessKeyId region;
instanceType = "t2.nano";
keyPair = resources.ec2KeyPairs.my-key-pair;
securityGroups = [
resources.ec2SecurityGroups."http"
resources.ec2SecurityGroups."ssh"
];
};
};
networking.firewall.allowedTCPPorts = [ 80 ];
services.postgresql = {
enable = true;
authentication = ''
local all all ident map=mapping
'';
identMap = ''
mapping root postgres
mapping postgres postgres
'';
package = pkgs.postgresql_11;
initialScript = pkgs.writeText "initialScript.sql" ''
CREATE TABLE "user" (
name text NOT NULL,
PRIMARY KEY (name)
);
CREATE TABLE tweet (
id integer GENERATED ALWAYS AS IDENTITY,
contents text NOT NULL,
time TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
author text NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY ("author") REFERENCES "user" (name) ON DELETE CASCADE
);
CREATE TABLE follows (
follower text NOT NULL,
followed text NOT NULL,
PRIMARY KEY (follower, followed),
FOREIGN KEY (follower) REFERENCES "user" (name) ON DELETE CASCADE,
FOREIGN KEY (followed) REFERENCES "user" (name) ON DELETE CASCADE
);
'';
};
systemd.services.simple-twitter = {
wantedBy = [ "multi-user.target" ];
after = [ "postgresql.service" ];
script =
let
ghc =
pkgs.haskellPackages.ghcWithPackages (pkgs: [
pkgs.blaze-html
pkgs.blaze-markup
pkgs.exceptions
pkgs.http-api-data
pkgs.optparse-generic
pkgs.postgresql-simple
pkgs.servant
pkgs.servant-blaze
pkgs.servant-server
pkgs.text
pkgs.transformers
pkgs.warp
]
);
code = pkgs.writeText "Main.hs" ''
{-# LINE 90 "Main.hs" #-}
{-# LANGUAGE BlockArguments #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeOperators #-}
module Main where
import Control.Exception (SomeException)
import Control.Monad.IO.Class (MonadIO(..))
import Data.Foldable (traverse_)
import Data.Text (Text)
import Data.Proxy (Proxy(..))
import Data.Word (Word16)
import GHC.Generics (Generic)
import Options.Generic (ParseRecord)
import Prelude hiding (id)
import Database.PostgreSQL.Simple (FromRow, Only(..), Query, ToRow, (:.)(..))
import Database.PostgreSQL.Simple.SqlQQ (sql)
import Servant.HTML.Blaze (HTML)
import Servant.Server (Handler)
import Text.Blaze (Markup, (!))
import Text.Blaze.Html5 (AttributeValue)
import Web.HttpApiData (FromHttpApiData)
import Web.FormUrlEncoded (FromForm)
import Servant.API
( FormUrlEncoded
, Get
, Post
, QueryParam'
, ReqBody
, Required
, Strict
, (:>)
, (:<|>)(..)
)
import qualified Control.Exception as Exception
import qualified Control.Monad as Monad
import qualified Control.Monad.Catch as Catch
import qualified Database.PostgreSQL.Simple as PostgreSQL
import qualified Network.Wai.Handler.Warp as Warp
import qualified Options.Generic as Options
import qualified Servant.Server as Server
import qualified Text.Blaze.Html5 as Html
import qualified Text.Blaze.Html5.Attributes as Attr
newtype Options = Options { connectPort :: Word16 }
deriving stock (Generic)
deriving anyclass (ParseRecord)
newtype User = User { name :: Text }
deriving stock (Generic)
deriving anyclass (FromForm, FromRow, ToRow)
deriving newtype (FromHttpApiData)
data Follow = Follow { follower :: Text, followed :: Text }
deriving stock (Generic)
deriving anyclass (FromForm, ToRow)
data Tweet = Tweet { name :: Text, contents :: Text }
deriving stock (Generic)
deriving anyclass (FromForm, FromRow)
type API =
Get '[HTML] Markup
:<|> "user" :> ReqBody '[FormUrlEncoded] User :> Post '[HTML] Markup
:<|> "user" :> QueryParam' '[Required, Strict] "name" User :> Get '[HTML] Markup
:<|> "user" :> "delete" :> ReqBody '[FormUrlEncoded] User :> Post '[HTML] Markup
:<|> "users" :> Get '[HTML] Markup
:<|> "tweet" :> ReqBody '[FormUrlEncoded] Tweet :> Post '[HTML] Markup
:<|> "follow" :> ReqBody '[FormUrlEncoded] Follow :> Post '[HTML] Markup
main :: IO ()
main = do
Options {..} <- Options.getRecord "Simple Twitter"
let connectInfo =
PostgreSQL.defaultConnectInfo
{ PostgreSQL.connectPort = connectPort
, PostgreSQL.connectHost = ""
}
let open = PostgreSQL.connect connectInfo
let close = PostgreSQL.close
Exception.bracket open close \connection -> do
let execute :: (MonadIO io, ToRow input) => input -> Query -> io ()
execute input q = liftIO do
_ <- PostgreSQL.execute connection q input
return ()
let query
:: (MonadIO io, ToRow input, FromRow output)
=> input -> Query -> io [output]
query input q = liftIO (PostgreSQL.query connection q input)
let query_
:: (MonadIO io, FromRow output)
=> Query -> io [output]
query_ q = liftIO (PostgreSQL.query_ connection q)
let submit label =
Html.button
! Attr.type_ "submit"
! Attr.class_ "btn btn-primary btn-sm"
$ label
let field :: AttributeValue -> Markup
field name = do
Html.div ! Attr.class_ "form-group" $ do
Html.input
! Attr.type_ "text"
! Attr.class_ "form-control form-control-sm"
! Attr.name name
! Attr.placeholder name
let form action method html =
Html.div ! Attr.class_ "col-md-4" $ do
Html.form
! Attr.action action
! Attr.method method
! Attr.class_ "border m-3 p-2 bg-light"
$ html
let forms :: Markup
forms = do
Html.div ! Attr.class_ "row" $ do
form "/" "get" do
submit "Global timeline"
Html.div ! Attr.class_ "row" $ do
form "/user" "post" do
field "name"
submit "Create user"
form "/user/delete" "post" do
field "name"
submit "Delete user"
form "/users" "get" do
submit "Get users"
Html.div ! Attr.class_ "row" $ do
form "/tweet" "post" do
field "name"
field "contents"
submit "Create tweet"
form "/follow" "post" do
field "follower"
field "followed"
submit "Follow"
form "/user" "get" do
field "name"
submit "Get user"
let ul html = Html.ul ! Attr.class_ "list-group" $ html
let li html = Html.li ! Attr.class_ "list-group-item" $ html
let wrap :: Markup -> Markup
wrap body =
Html.html do
Html.head do
Html.title "Simple Twitter"
Html.link
! Attr.rel "stylesheet"
! Attr.href "https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
Html.body do
Html.h1
! Attr.class_ "display-4 text-center"
$ "Simple Twitter"
Html.div ! Attr.class_ "container" $ do
Html.div ! Attr.class_ "row" $ do
Html.div ! Attr.class_ "col-md-6" $ forms
Html.div ! Attr.class_ "col-md-6" $ body
let failWith :: Text -> Handler Markup -> Handler Markup
failWith message handler = do
let fallback :: SomeException -> Handler Markup
fallback _ = return (wrap (Html.toHtml message))
Catch.handle fallback handler
let index :: Handler Markup
index = do
tweets <- query_ [sql|
SELECT tweet.author, tweet.contents
FROM tweet
ORDER BY tweet.time DESC
|]
let renderTweet (Tweet {..}) =
li (Html.toHtml (name <> ": " <> contents))
return do
wrap (ul (traverse_ renderTweet tweets))
let getUsers :: Handler Markup
getUsers = do
users <- query_ [sql|SELECT name FROM "user"|]
let renderUser (User {..}) = li (Html.toHtml name)
return (wrap (ul (traverse_ renderUser users)))
let createUser :: User -> Handler Markup
createUser user@User{..} = do
let message =
"A user named '" <> name <> "' already exists"
failWith message do
execute user [sql|INSERT INTO "user" (name) VALUES (?)|]
getUsers
let getUser :: User -> Handler Markup
getUser user@User{..} = do
let message =
"No user named '" <> name <> "' exists"
failWith message do
followeds <- query user [sql|
SELECT follows.followed
FROM follows
WHERE follows.follower = ?
|]
history <- query user [sql|
SELECT tweet.author, tweet.contents
FROM tweet
WHERE tweet.author = ?
ORDER BY tweet.time DESC
|]
timeline <- query user [sql|
SELECT follows.followed, tweet.contents
FROM follows
INNER JOIN tweet ON follows.followed = tweet.author
WHERE follows.follower = ?
ORDER BY tweet.time DESC
|]
let renderHistory (Tweet { contents }) =
li (Html.toHtml contents)
let renderTimeline (Tweet { name = followed, ..}) =
li (Html.toHtml (followed <> ": " <> contents))
let renderUser (User { name = followed }) =
li (Html.toHtml followed)
return do
wrap do
Html.h2 (Html.toHtml name)
Html.hr
Monad.when (not (null history)) do
Html.h3 "History"
ul (traverse_ renderHistory history)
Monad.when (not (null timeline)) do
Html.h3 "Timeline"
ul (traverse_ renderTimeline timeline)
Monad.when (not (null followeds)) do
Html.h3 "Follows"
ul (traverse_ renderUser followeds)
let deleteUser :: User -> Handler Markup
deleteUser user@User{..}= do
let message =
"No user named '" <> name <> "' exists"
failWith message do
execute user [sql|DELETE FROM "user" WHERE name = ?|]
getUsers
let createTweet :: Tweet -> Handler Markup
createTweet (Tweet {..}) = do
rows <- query (Only contents) [sql|
INSERT INTO tweet (contents) VALUES (?) RETURNING (id)
|]
id <- case rows of
[ (id :: Only Integer) ] -> return id
_ -> Catch.throwM Server.err500
getUser (User {..})
let follow :: Follow -> Handler Markup
follow f@Follow{..} = do
let message =
"'" <> follower <> "' already follows '" <> followed <> "'"
failWith message do
execute f [sql|
INSERT INTO follows (follower, followed) VALUES (?, ?)
|]
getUser (User { name = follower })
let server = index
:<|> createUser
:<|> getUser
:<|> deleteUser
:<|> getUsers
:<|> createTweet
:<|> follow
let application = Server.serve @API Proxy server
Warp.run 80 application
'';
simple-twitter = pkgs.runCommand "simple-twitter" {} ''
${ghc}/bin/ghc -O -Wall -Werror ${code} -o $out
'';
in
''
${simple-twitter} --connectPort ${toString config.services.postgresql.port}
'';
};
};
resources = {
ec2KeyPairs.my-key-pair = { inherit region accessKeyId; };
ec2SecurityGroups = {
"http" = {
inherit accessKeyId region;
rules = [
{ fromPort = 80; toPort = 80; sourceIp = "0.0.0.0/0"; }
];
};
"ssh" = {
inherit accessKeyId region;
rules = [
{ fromPort = 22; toPort = 22; sourceIp = "0.0.0.0/0"; }
];
};
};
};
}