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
|
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE ExplicitNamespaces #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE OverloadedLists #-}
-- Implementation of the API. This module is the main point of the program.
module Server (application) where
import Conduit (MonadTrans (lift), ResourceT)
import Control.Concurrent.STM
import Control.Monad (when)
import Control.Monad.Extra (whenM, maybeM)
import Control.Monad.IO.Class (MonadIO (liftIO))
import Control.Monad.Logger.CallStack (NoLoggingT)
import Control.Monad.Reader (forM)
import Control.Monad.Trans.Maybe (MaybeT (..))
import Data.Aeson (FromJSON (parseJSON),
ToJSON (toJSON), ToJSONKey,
genericParseJSON,
genericToJSON)
import qualified Data.Aeson as A
import Data.Coerce (coerce)
import Data.Functor ((<&>))
import Data.Map (Map)
import qualified Data.Map as M
import Data.Pool (Pool)
import Data.Proxy (Proxy (Proxy))
import Data.Swagger hiding (get)
import Data.Text (Text)
import Data.Time (NominalDiffTime,
UTCTime (utctDay), addUTCTime,
dayOfWeek, diffUTCTime,
getCurrentTime, nominalDay)
import Data.UUID (UUID)
import qualified Data.UUID as UUID
import qualified Data.UUID.V4 as UUID
import Data.Vector (Vector)
import qualified Data.Vector as V
import Database.Persist
import Database.Persist.Postgresql
import GHC.Generics (Generic)
import GTFS
import Servant (Application,
FromHttpApiData (parseUrlPiece),
Server, err401, err404, serve,
throwError)
import Servant.API (Capture, FromHttpApiData, Get,
JSON, Post, ReqBody,
type (:<|>) ((:<|>)))
import Servant.Docs (DocCapture (..),
DocQueryParam (..),
ParamKind (..), ToCapture (..),
ToParam (..))
import Servant.Server (Handler)
import Servant.Swagger (toSwagger)
import Web.PathPieces (PathPiece)
import Text.ProtocolBuffers (defaultValue)
import qualified Data.Sequence as Seq
import Data.Time.Clock.POSIX (getPOSIXTime)
import Data.Time.Clock.System (SystemTime(systemSeconds), getSystemTime)
import Text.ProtocolBuffers.WireMessage (zzEncode64)
import GTFS.Realtime.FeedMessage (FeedMessage(..))
import GTFS.Realtime.FeedEntity ( FeedEntity(FeedEntity) )
import GTFS.Realtime.FeedHeader (FeedHeader(FeedHeader))
import GTFS.Realtime.FeedHeader.Incrementality (Incrementality(FULL_DATASET))
import API
import Persist
import GTFS.Realtime.Alert (Alert(Alert))
import GTFS.Realtime.Alert.SeverityLevel (SeverityLevel(WARNING))
import GTFS.Realtime.Alert.Cause (Cause(CONSTRUCTION))
import GTFS.Realtime.Alert.Effect (Effect(DETOUR))
import GTFS.Realtime.TranslatedString (TranslatedString(TranslatedString))
import GTFS.Realtime.TranslatedString.Translation (Translation(Translation))
import GTFS.Realtime.TimeRange (TimeRange(TimeRange))
import GTFS.Realtime.EntitySelector (EntitySelector(EntitySelector))
application :: GTFS -> Pool SqlBackend -> IO Application
application gtfs dbpool = do
doMigration dbpool
pure $ serve (Proxy @CompleteAPI) $ server gtfs dbpool
-- databaseMigration :: ConnectionString -> IO ()
doMigration pool = runSql pool $
-- TODO: before that, check if the uuid module is enabled
-- in sql: check if SELECT * FROM pg_extension WHERE extname = 'uuid-ossp';
-- returns an empty list
runMigration migrateAll
server :: GTFS -> Pool SqlBackend -> Server CompleteAPI
server gtfs@GTFS{..} dbpool = handleDebugAPI :<|> handleStations :<|> handleTimetable :<|> handleTrip
:<|> handleRegister :<|> handleTripPing :<|> handleDebugState :<|> gtfsRealtimeServer
where handleStations = pure stations
handleTimetable station maybeDay = do
-- TODO: resolve "overlay" trips (perhaps just additional CalendarDates?)
day <- liftIO $ maybeM (getCurrentTime <&> utctDay) pure (pure maybeDay)
pure
-- don't send stations ending at this station
. M.filter ((==) station . stationId . stopStation . V.last . tripStops)
$ tripsOnDay gtfs day
handleTrip trip = case M.lookup trip trips of
Just res -> pure res
Nothing -> throwError err404
handleRegister tripID = do
expires <- liftIO $ getCurrentTime <&> addUTCTime validityPeriod
RunningTripKey token <- runSql dbpool $ insert (RunningTrip expires False tripID)
pure token
handleTripPing ping = do
checkTokenValid dbpool (coerce $ tripPingToken ping)
-- TODO: are these always inserted in order?
runSql dbpool $ insert ping
pure ()
handleDebugState = do
now <- liftIO getCurrentTime
runSql dbpool $ do
running <- selectList [RunningTripBlocked ==. False, RunningTripExpires >=. now] []
pairs <- forM running $ \(Entity token@(RunningTripKey uuid) _) -> do
entities <- selectList [TripPingToken ==. token] []
pure (uuid, fmap entityVal entities)
pure (M.fromList pairs)
handleDebugAPI = pure $ toSwagger (Proxy @API)
gtfsRealtimeServer :: Server GtfsRealtimeAPI
gtfsRealtimeServer = handleServiceAlerts :<|> handleDummy :<|> handleDummy
where handleDummy = do
pure $ FeedEntity
"1234"
Nothing
Nothing
Nothing
Nothing
Nothing
defaultValue
handleServiceAlerts = do
now <- liftIO getSystemTime <&> systemSeconds
pure $ FeedMessage
(FeedHeader "2.0" (Just FULL_DATASET) (Just $ fromIntegral now) defaultValue)
(Seq.fromList
[FeedEntity
"0"
Nothing
Nothing
Nothing
(Just $ Alert
[TimeRange (Just $ fromIntegral (now - 1000)) Nothing defaultValue]
[EntitySelector Nothing (Just "Passau - Freyung") Nothing Nothing Nothing Nothing defaultValue]
(Just CONSTRUCTION)
(Just DETOUR)
(lang "de" "https://ilztalbahn.eu")
(lang "de" "Da liegt ein Baum auf der Strecke")
(lang "de" "Leider liegt ein Baum auf der Strecke. Solange fährt hier nix.")
Nothing
Nothing
(Just WARNING)
Nothing
Nothing
defaultValue
)
Nothing
defaultValue
])
defaultValue
lang code msg = Just $ TranslatedString [Translation msg (Just code) defaultValue] defaultValue
-- TODO: proper debug logging for expired tokens
checkTokenValid :: Pool SqlBackend -> Token -> Handler ()
checkTokenValid dbpool token = do
trip <- try $ runSql dbpool $ get (coerce token)
when (runningTripBlocked trip)
$ throwError err401
whenM (hasExpired (runningTripExpires trip))
$ throwError err401
where try m = m >>= \case
Just a -> pure a
Nothing -> throwError err404
hasExpired :: MonadIO m => UTCTime -> m Bool
hasExpired limit = do
now <- liftIO getCurrentTime
pure (now > limit)
validityPeriod :: NominalDiffTime
validityPeriod = nominalDay
|