2 Module : Gargantext.API.Ngrams
3 Description : Server API
4 Copyright : (c) CNRS, 2017-Present
5 License : AGPL + CECILL v3
6 Maintainer : team@gargantext.org
7 Stability : experimental
13 get ngrams filtered by NgramsType
18 {-# OPTIONS_GHC -fno-warn-unused-top-binds #-}
20 {-# LANGUAGE ConstraintKinds #-}
21 {-# LANGUAGE ScopedTypeVariables #-}
22 {-# LANGUAGE TypeOperators #-}
23 {-# LANGUAGE TypeFamilies #-}
25 {-# LANGUAGE IncoherentInstances #-}
26 module Gargantext.API.Ngrams
33 --, rmListNgrams TODO fix before exporting
34 , apiNgramsTableCorpus
55 , NgramsRepoElement(..)
72 , VersionedWithCount(..)
74 , listNgramsChangedSince
75 , MinSize, MaxSize, OrderBy, NgramsTable
76 , UpdateTableNgramsCharts
80 import Control.Concurrent
81 import Control.Lens ((.~), view, (^.), (^..), (+~), (%~), (.~), sumOf, at, _Just, Each(..), (%%~), mapped, ifolded, withIndex)
82 import Control.Monad.Reader
83 import Data.Aeson hiding ((.=))
84 import Data.Either (Either(..))
86 import Data.Map.Strict (Map)
87 import Data.Maybe (fromMaybe)
89 import Data.Ord (Down(..))
90 import Data.Patch.Class (Action(act), Transformable(..), ours)
91 import Data.Swagger hiding (version, patch)
92 import Data.Text (Text, isInfixOf, unpack, pack)
93 import Data.Text.Lazy.IO as DTL
94 import Formatting (hprint, int, (%))
95 import GHC.Generics (Generic)
96 import Gargantext.API.Admin.Orchestrator.Types (JobLog(..), AsyncJobs)
97 import Gargantext.API.Admin.Types (HasSettings)
98 import Gargantext.API.Job
99 import Gargantext.API.Ngrams.Types
100 import Gargantext.API.Prelude
101 import Gargantext.Core.NodeStory
102 import Gargantext.Core.Mail.Types (HasMail)
103 import Gargantext.Core.Types (ListType(..), NodeId, ListId, DocId, Limit, Offset, TODO, assertValid, HasInvalidError)
104 import Gargantext.API.Ngrams.Tools
105 import Gargantext.Database.Action.Flow.Types
106 import Gargantext.Database.Action.Metrics.NgramsByContext (getOccByNgramsOnlyFast')
107 import Gargantext.Database.Admin.Config (userMaster)
108 import Gargantext.Database.Admin.Types.Node (NodeType(..))
109 import Gargantext.Database.Prelude (HasConnectionPool(..), HasConfig)
110 import Gargantext.Database.Query.Table.Ngrams hiding (NgramsType(..), ngramsType, ngrams_terms)
111 import Gargantext.Database.Query.Table.Node (getNode)
112 import Gargantext.Database.Query.Table.Node.Error (HasNodeError)
113 import Gargantext.Database.Query.Table.Node.Select
114 import Gargantext.Database.Schema.Node (node_id, node_parent_id, node_user_id)
115 import Gargantext.Prelude hiding (log)
116 import Gargantext.Prelude.Clock (hasTime, getTime)
117 import Prelude (error)
118 import Servant hiding (Patch)
119 import Servant.Job.Async (JobFunction(..), serveJobsAPI)
120 import System.IO (stderr)
121 import Test.QuickCheck (elements)
122 import Test.QuickCheck.Arbitrary (Arbitrary, arbitrary)
123 import qualified Data.Aeson.Text as DAT
124 import qualified Data.List as List
125 import qualified Data.Map.Strict as Map
126 import qualified Data.Map.Strict.Patch as PM
127 import qualified Data.Set as S
128 import qualified Data.Set as Set
129 import qualified Gargantext.API.Metrics as Metrics
130 import qualified Gargantext.Database.Query.Table.Ngrams as TableNgrams
133 -- TODO sequences of modifications (Patchs)
134 type NgramsIdPatch = Patch NgramsId NgramsPatch
136 ngramsPatch :: Int -> NgramsPatch
137 ngramsPatch n = NgramsPatch (DM.fromList [(1, StopTerm)]) (Set.fromList [n]) Set.empty
139 toEdit :: NgramsId -> NgramsPatch -> Edit NgramsId NgramsPatch
140 toEdit n p = Edit n p
141 ngramsIdPatch :: Patch NgramsId NgramsPatch
142 ngramsIdPatch = fromList $ catMaybes $ reverse [ replace (1::NgramsId) (Just $ ngramsPatch 1) Nothing
143 , replace (1::NgramsId) Nothing (Just $ ngramsPatch 2)
144 , replace (2::NgramsId) Nothing (Just $ ngramsPatch 2)
147 -- applyPatchBack :: Patch -> IO Patch
148 -- isEmptyPatch = Map.all (\x -> Set.isEmpty (add_children x) && Set.isEmpty ... )
150 ------------------------------------------------------------------------
151 ------------------------------------------------------------------------
152 ------------------------------------------------------------------------
155 -- TODO: Replace.old is ignored which means that if the current list
156 -- `MapTerm` and that the patch is `Replace CandidateTerm StopTerm` then
157 -- the list is going to be `StopTerm` while it should keep `MapTerm`.
158 -- However this should not happen in non conflicting situations.
159 mkListsUpdate :: NgramsType -> NgramsTablePatch -> [(NgramsTypeId, NgramsTerm, ListTypeId)]
160 mkListsUpdate nt patches =
161 [ (ngramsTypeId nt, ng, listTypeId lt)
162 | (ng, patch) <- patches ^.. ntp_ngrams_patches . ifolded . withIndex
163 , lt <- patch ^.. patch_list . new
166 mkChildrenGroups :: (PatchSet NgramsTerm -> Set NgramsTerm)
169 -> [(NgramsTypeId, NgramsParent, NgramsChild)]
170 mkChildrenGroups addOrRem nt patches =
171 [ (ngramsTypeId nt, parent, child)
172 | (parent, patch) <- patches ^.. ntp_ngrams_patches . ifolded . withIndex
173 , child <- patch ^.. patch_children . to addOrRem . folded
177 ------------------------------------------------------------------------
179 saveNodeStory :: ( MonadReader env m, MonadBase IO m, HasNodeStorySaver env )
181 saveNodeStory = liftBase =<< view hasNodeStorySaver
184 listTypeConflictResolution :: ListType -> ListType -> ListType
185 listTypeConflictResolution _ _ = undefined -- TODO Use Map User ListType
188 ngramsStatePatchConflictResolution
189 :: TableNgrams.NgramsType
191 -> ConflictResolutionNgramsPatch
192 ngramsStatePatchConflictResolution _ngramsType _ngramsTerm
193 = (ours, (const ours, ours), (False, False))
194 -- (False, False) mean here that Mod has always priority.
195 -- (True, False) <- would mean priority to the left (same as ours).
196 -- undefined {- TODO think this through -}, listTypeConflictResolution)
202 -- Insertions are not considered as patches,
203 -- they do not extend history,
204 -- they do not bump version.
205 insertNewOnly :: a -> Maybe b -> a
206 insertNewOnly m = maybe m (const $ error "insertNewOnly: impossible")
207 -- TODO error handling
210 -- TODO refactor with putListNgrams
211 copyListNgrams :: RepoCmdM env err m
212 => NodeId -> NodeId -> NgramsType
214 copyListNgrams srcListId dstListId ngramsType = do
216 liftBase $ modifyMVar_ var $
217 pure . (r_state . at ngramsType %~ (Just . f . something))
220 f :: Map NodeId NgramsTableMap -> Map NodeId NgramsTableMap
221 f m = m & at dstListId %~ insertNewOnly (m ^. at srcListId)
223 -- TODO refactor with putListNgrams
224 -- The list must be non-empty!
225 -- The added ngrams must be non-existent!
226 addListNgrams :: RepoCmdM env err m
227 => NodeId -> NgramsType
228 -> [NgramsElement] -> m ()
229 addListNgrams listId ngramsType nes = do
231 liftBase $ modifyMVar_ var $
232 pure . (r_state . at ngramsType . _Just . at listId . _Just <>~ m)
235 m = Map.fromList $ (\n -> (n ^. ne_ngrams, n)) <$> nes
238 -- | TODO: incr the Version number
239 -- && should use patch
242 setListNgrams :: HasNodeStory env err m
244 -> TableNgrams.NgramsType
245 -> Map NgramsTerm NgramsRepoElement
247 setListNgrams listId ngramsType ns = do
248 -- printDebug "[setListNgrams]" (listId, ngramsType)
249 getter <- view hasNodeStory
250 var <- liftBase $ (getter ^. nse_getter) [listId]
251 liftBase $ modifyMVar_ var $
261 currentVersion :: HasNodeStory env err m
262 => ListId -> m Version
263 currentVersion listId = do
264 --nls <- getRepo [listId]
265 pool <- view connPool
266 nls <- liftBase $ getNodeStory pool listId
267 pure $ nls ^. unNodeStory . at listId . _Just . a_version
270 newNgramsFromNgramsStatePatch :: NgramsStatePatch' -> [Ngrams]
271 newNgramsFromNgramsStatePatch p =
272 [ text2ngrams (unNgramsTerm n)
273 | (n,np) <- p ^.. _PatchMap
274 -- . each . _PatchMap
275 . each . _NgramsTablePatch
276 . _PatchMap . ifolded . withIndex
277 , _ <- np ^.. patch_new . _Just
283 commitStatePatch :: (HasNodeStory env err m, HasMail env)
285 -> Versioned NgramsStatePatch'
286 -> m (Versioned NgramsStatePatch')
287 commitStatePatch listId (Versioned _p_version p) = do
288 -- printDebug "[commitStatePatch]" listId
289 var <- getNodeStoryVar [listId]
290 vq' <- liftBase $ modifyMVar var $ \ns -> do
292 a = ns ^. unNodeStory . at listId . _Just
293 -- apply patches from version p_version to a ^. a_version
295 --q = mconcat $ take (a ^. a_version - p_version) (a ^. a_history)
296 q = mconcat $ a ^. a_history
297 (p', q') = transformWith ngramsStatePatchConflictResolution p q
298 a' = a & a_version +~ 1
300 & a_history %~ (p' :)
303 -- Ideally we would like to check these properties. However:
304 -- * They should be checked only to debug the code. The client data
305 -- should be able to trigger these.
306 -- * What kind of error should they throw (we are in IO here)?
307 -- * Should we keep modifyMVar?
308 -- * Should we throw the validation in an Exception, catch it around
309 -- modifyMVar and throw it back as an Error?
310 assertValid $ transformable p q
311 assertValid $ applicable p' (r ^. r_state)
313 printDebug "[commitStatePatch] a version" (a ^. a_version)
314 printDebug "[commitStatePatch] a' version" (a' ^. a_version)
315 pure ( ns & unNodeStory . at listId .~ (Just a')
316 , Versioned (a' ^. a_version) q'
320 _ <- insertNgrams (newNgramsFromNgramsStatePatch p)
326 -- This is a special case of tableNgramsPut where the input patch is empty.
327 tableNgramsPull :: HasNodeStory env err m
329 -> TableNgrams.NgramsType
331 -> m (Versioned NgramsTablePatch)
332 tableNgramsPull listId ngramsType p_version = do
333 printDebug "[tableNgramsPull]" (listId, ngramsType)
334 var <- getNodeStoryVar [listId]
335 r <- liftBase $ readMVar var
338 a = r ^. unNodeStory . at listId . _Just
339 q = mconcat $ take (a ^. a_version - p_version) (a ^. a_history)
340 q_table = q ^. _PatchMap . at ngramsType . _Just
342 pure (Versioned (a ^. a_version) q_table)
347 -- tableNgramsPut :: (HasInvalidError err, RepoCmdM env err m)
348 -- Apply the given patch to the DB and returns the patch to be applied on the
351 tableNgramsPut :: ( HasNodeStory env err m
352 , HasInvalidError err
358 -> Versioned NgramsTablePatch
359 -> m (Versioned NgramsTablePatch)
360 tableNgramsPut tabType listId (Versioned p_version p_table)
361 | p_table == mempty = do
362 printDebug "[tableNgramsPut]" ("TableEmpty" :: Text)
363 let ngramsType = ngramsTypeFromTabType tabType
364 tableNgramsPull listId ngramsType p_version
367 printDebug "[tableNgramsPut]" ("TableNonEmpty" :: Text)
368 let ngramsType = ngramsTypeFromTabType tabType
369 (p, p_validity) = PM.singleton ngramsType p_table
371 assertValid p_validity
373 ret <- commitStatePatch listId (Versioned p_version p)
374 <&> v_data %~ (view (_PatchMap . at ngramsType . _Just))
380 tableNgramsPostChartsAsync :: ( HasNodeStory env err m
385 => UpdateTableNgramsCharts
388 tableNgramsPostChartsAsync utn logStatus = do
389 let tabType = utn ^. utn_tab_type
390 let listId = utn ^. utn_list_id
392 node <- getNode listId
393 let nId = node ^. node_id
394 _uId = node ^. node_user_id
395 mCId = node ^. node_parent_id
397 -- printDebug "[tableNgramsPostChartsAsync] tabType" tabType
398 -- printDebug "[tableNgramsPostChartsAsync] listId" listId
402 printDebug "[tableNgramsPostChartsAsync] can't update charts, no parent, nId" nId
403 pure $ jobLogFail $ jobLogInit 1
407 -- printDebug "[tableNgramsPostChartsAsync] Authors, updating Pie, cId" cId
408 (logRef, logRefSuccess, getRef) <- runJobLog 1 logStatus
410 _ <- Metrics.updatePie cId (Just listId) tabType Nothing
415 -- printDebug "[tableNgramsPostChartsAsync] Institutes, updating Tree, cId" cId
416 -- printDebug "[tableNgramsPostChartsAsync] updating tree StopTerm, cId" cId
417 (logRef, logRefSuccess, getRef) <- runJobLog 3 logStatus
419 _ <- Metrics.updateTree cId (Just listId) tabType StopTerm
420 -- printDebug "[tableNgramsPostChartsAsync] updating tree CandidateTerm, cId" cId
422 _ <- Metrics.updateTree cId (Just listId) tabType CandidateTerm
423 -- printDebug "[tableNgramsPostChartsAsync] updating tree MapTerm, cId" cId
425 _ <- Metrics.updateTree cId (Just listId) tabType MapTerm
430 -- printDebug "[tableNgramsPostChartsAsync] Sources, updating chart, cId" cId
431 (logRef, logRefSuccess, getRef) <- runJobLog 1 logStatus
433 _ <- Metrics.updatePie cId (Just listId) tabType Nothing
438 -- printDebug "[tableNgramsPostChartsAsync] Terms, updating Metrics (Histo), cId" cId
439 (logRef, logRefSuccess, getRef) <- runJobLog 6 logStatus
442 _ <- Metrics.updateChart cId (Just listId) tabType Nothing
444 _ <- Metrics.updatePie cId (Just listId) tabType Nothing
446 _ <- Metrics.updateScatter cId (Just listId) tabType Nothing
448 _ <- Metrics.updateTree cId (Just listId) tabType StopTerm
450 _ <- Metrics.updateTree cId (Just listId) tabType CandidateTerm
452 _ <- Metrics.updateTree cId (Just listId) tabType MapTerm
458 printDebug "[tableNgramsPostChartsAsync] no update for tabType = " tabType
459 pure $ jobLogFail $ jobLogInit 1
462 { _ne_list :: ListType
463 If we merge the parents/children we can potentially create cycles!
464 , _ne_parent :: Maybe NgramsTerm
465 , _ne_children :: MSet NgramsTerm
469 getNgramsTableMap :: HasNodeStory env err m
471 -> TableNgrams.NgramsType
472 -> m (Versioned NgramsTableMap)
473 getNgramsTableMap nodeId ngramsType = do
474 v <- getNodeStoryVar [nodeId]
475 repo <- liftBase $ readMVar v
476 pure $ Versioned (repo ^. unNodeStory . at nodeId . _Just . a_version)
477 (repo ^. unNodeStory . at nodeId . _Just . a_state . at ngramsType . _Just)
480 dumpJsonTableMap :: HasNodeStory env err m
483 -> TableNgrams.NgramsType
485 dumpJsonTableMap fpath nodeId ngramsType = do
486 m <- getNgramsTableMap nodeId ngramsType
487 liftBase $ DTL.writeFile (unpack fpath) (DAT.encodeToLazyText m)
494 -- | TODO Errors management
495 -- TODO: polymorphic for Annuaire or Corpus or ...
496 -- | Table of Ngrams is a ListNgrams formatted (sorted and/or cut).
497 -- TODO: should take only one ListId
500 getTableNgrams :: forall env err m.
501 (HasNodeStory env err m, HasNodeError err, HasConnectionPool env, HasConfig env, HasMail env)
502 => NodeType -> NodeId -> TabType
503 -> ListId -> Limit -> Maybe Offset
505 -> Maybe MinSize -> Maybe MaxSize
507 -> (NgramsTerm -> Bool)
508 -> m (VersionedWithCount NgramsTable)
509 getTableNgrams _nType nId tabType listId limit_ offset
510 listType minSize maxSize orderBy searchQuery = do
513 -- lIds <- selectNodesWithUsername NodeList userMaster
515 ngramsType = ngramsTypeFromTabType tabType
516 offset' = maybe 0 identity offset
517 listType' = maybe (const True) (==) listType
518 minSize' = maybe (const True) (<=) minSize
519 maxSize' = maybe (const True) (>=) maxSize
521 selected_node n = minSize' s
523 && searchQuery (n ^. ne_ngrams)
524 && listType' (n ^. ne_list)
528 selected_inner roots n = maybe False (`Set.member` roots) (n ^. ne_root)
530 ---------------------------------------
531 sortOnOrder Nothing = sortOnOrder (Just ScoreDesc)
532 sortOnOrder (Just TermAsc) = List.sortOn $ view ne_ngrams
533 sortOnOrder (Just TermDesc) = List.sortOn $ Down . view ne_ngrams
534 sortOnOrder (Just ScoreAsc) = List.sortOn $ view ne_occurrences
535 sortOnOrder (Just ScoreDesc) = List.sortOn $ Down . view ne_occurrences
537 ---------------------------------------
538 filteredNodes :: Map NgramsTerm NgramsElement -> [NgramsElement]
539 filteredNodes tableMap = rootOf <$> list & filter selected_node
541 rootOf ne = maybe ne (\r -> fromMaybe (panic "getTableNgrams: invalid root")
545 list = tableMap ^.. each
547 ---------------------------------------
548 selectAndPaginate :: Map NgramsTerm NgramsElement -> [NgramsElement]
549 selectAndPaginate tableMap = roots <> inners
551 list = tableMap ^.. each
552 rootOf ne = maybe ne (\r -> fromMaybe (panic "getTableNgrams: invalid root")
556 selected_nodes = list & take limit_
558 . filter selected_node
559 . sortOnOrder orderBy
560 roots = rootOf <$> selected_nodes
561 rootsSet = Set.fromList (_ne_ngrams <$> roots)
562 inners = list & filter (selected_inner rootsSet)
564 ---------------------------------------
565 setScores :: forall t. Each t t NgramsElement NgramsElement => Bool -> t -> m t
566 setScores False table = pure table
567 setScores True table = do
568 let ngrams_terms = table ^.. each . ne_ngrams
569 -- printDebug "ngrams_terms" ngrams_terms
571 occurrences <- getOccByNgramsOnlyFast' nId
575 --printDebug "occurrences" occurrences
577 liftBase $ hprint stderr
578 ("getTableNgrams/setScores #ngrams=" % int % " time=" % hasTime % "\n")
579 (length ngrams_terms) t1 t2
581 setOcc ne = ne & ne_occurrences .~ sumOf (at (ne ^. ne_ngrams) . _Just) occurrences
583 pure $ table & each %~ setOcc
584 ---------------------------------------
586 -- lists <- catMaybes <$> listsWith userMaster
587 -- trace (show lists) $
588 -- getNgramsTableMap ({-lists <>-} listIds) ngramsType
591 let scoresNeeded = needsScores orderBy
592 tableMap1 <- getNgramsTableMap listId ngramsType
595 tableMap2 <- tableMap1 & v_data %%~ setScores scoresNeeded
596 . Map.mapWithKey ngramsElementFromRepo
598 fltr <- tableMap2 & v_data %%~ fmap NgramsTable . setScores (not scoresNeeded)
601 let fltrCount = length $ fltr ^. v_data . _NgramsTable
604 tableMap3 <- tableMap2 & v_data %%~ fmap NgramsTable
605 . setScores (not scoresNeeded)
608 liftBase $ hprint stderr
609 ("getTableNgrams total=" % hasTime
613 % " sql=" % (if scoresNeeded then "map2" else "map3")
615 ) t0 t3 t0 t1 t1 t2 t2 t3
616 pure $ toVersionedWithCount fltrCount tableMap3
620 scoresRecomputeTableNgrams :: forall env err m.
621 (HasNodeStory env err m, HasNodeError err, HasConnectionPool env, HasConfig env, HasMail env)
622 => NodeId -> TabType -> ListId -> m Int
623 scoresRecomputeTableNgrams nId tabType listId = do
624 tableMap <- getNgramsTableMap listId ngramsType
625 _ <- tableMap & v_data %%~ setScores
626 . Map.mapWithKey ngramsElementFromRepo
630 ngramsType = ngramsTypeFromTabType tabType
632 setScores :: forall t. Each t t NgramsElement NgramsElement => t -> m t
634 let ngrams_terms = table ^.. each . ne_ngrams
635 occurrences <- getOccByNgramsOnlyFast' nId
640 setOcc ne = ne & ne_occurrences .~ sumOf (at (ne ^. ne_ngrams) . _Just) occurrences
642 pure $ table & each %~ setOcc
649 -- TODO: find a better place for the code above, All APIs stay here
651 data OrderBy = TermAsc | TermDesc | ScoreAsc | ScoreDesc
652 deriving (Generic, Enum, Bounded, Read, Show)
654 instance FromHttpApiData OrderBy
656 parseUrlPiece "TermAsc" = pure TermAsc
657 parseUrlPiece "TermDesc" = pure TermDesc
658 parseUrlPiece "ScoreAsc" = pure ScoreAsc
659 parseUrlPiece "ScoreDesc" = pure ScoreDesc
660 parseUrlPiece _ = Left "Unexpected value of OrderBy"
662 instance ToHttpApiData OrderBy where
663 toUrlPiece = pack . show
665 instance ToParamSchema OrderBy
666 instance FromJSON OrderBy
667 instance ToJSON OrderBy
668 instance ToSchema OrderBy
669 instance Arbitrary OrderBy
671 arbitrary = elements [minBound..maxBound]
673 needsScores :: Maybe OrderBy -> Bool
674 needsScores (Just ScoreAsc) = True
675 needsScores (Just ScoreDesc) = True
676 needsScores _ = False
678 type TableNgramsApiGet = Summary " Table Ngrams API Get"
679 :> QueryParamR "ngramsType" TabType
680 :> QueryParamR "list" ListId
681 :> QueryParamR "limit" Limit
682 :> QueryParam "offset" Offset
683 :> QueryParam "listType" ListType
684 :> QueryParam "minTermSize" MinSize
685 :> QueryParam "maxTermSize" MaxSize
686 :> QueryParam "orderBy" OrderBy
687 :> QueryParam "search" Text
688 :> Get '[JSON] (VersionedWithCount NgramsTable)
690 type TableNgramsApiPut = Summary " Table Ngrams API Change"
691 :> QueryParamR "ngramsType" TabType
692 :> QueryParamR "list" ListId
693 :> ReqBody '[JSON] (Versioned NgramsTablePatch)
694 :> Put '[JSON] (Versioned NgramsTablePatch)
696 type RecomputeScoresNgramsApiGet = Summary " Recompute scores for ngrams table"
697 :> QueryParamR "ngramsType" TabType
698 :> QueryParamR "list" ListId
699 :> "recompute" :> Post '[JSON] Int
701 type TableNgramsApiGetVersion = Summary " Table Ngrams API Get Version"
702 :> QueryParamR "ngramsType" TabType
703 :> QueryParamR "list" ListId
704 :> Get '[JSON] Version
706 type TableNgramsApi = TableNgramsApiGet
707 :<|> TableNgramsApiPut
708 :<|> RecomputeScoresNgramsApiGet
709 :<|> "version" :> TableNgramsApiGetVersion
710 :<|> TableNgramsAsyncApi
712 type TableNgramsAsyncApi = Summary "Table Ngrams Async API"
716 :> AsyncJobs JobLog '[JSON] UpdateTableNgramsCharts JobLog
718 getTableNgramsCorpus :: (HasNodeStory env err m, HasNodeError err, HasConnectionPool env, HasConfig env, HasMail env)
725 -> Maybe MinSize -> Maybe MaxSize
727 -> Maybe Text -- full text search
728 -> m (VersionedWithCount NgramsTable)
729 getTableNgramsCorpus nId tabType listId limit_ offset listType minSize maxSize orderBy mt =
730 getTableNgrams NodeCorpus nId tabType listId limit_ offset listType minSize maxSize orderBy searchQuery
732 searchQuery (NgramsTerm nt) = maybe (const True) isInfixOf mt nt
736 getTableNgramsVersion :: (HasNodeStory env err m, HasNodeError err, HasConnectionPool env, HasConfig env)
741 getTableNgramsVersion _nId _tabType listId = currentVersion listId
746 -- Versioned { _v_version = v } <- getTableNgramsCorpus nId tabType listId 100000 Nothing Nothing Nothing Nothing Nothing Nothing
747 -- This line above looks like a waste of computation to finally get only the version.
748 -- See the comment about listNgramsChangedSince.
751 -- | Text search is deactivated for now for ngrams by doc only
752 getTableNgramsDoc :: (HasNodeStory env err m, HasNodeError err, HasConnectionPool env, HasConfig env, HasMail env)
754 -> ListId -> Limit -> Maybe Offset
756 -> Maybe MinSize -> Maybe MaxSize
758 -> Maybe Text -- full text search
759 -> m (VersionedWithCount NgramsTable)
760 getTableNgramsDoc dId tabType listId limit_ offset listType minSize maxSize orderBy _mt = do
761 ns <- selectNodesWithUsername NodeList userMaster
762 let ngramsType = ngramsTypeFromTabType tabType
763 ngs <- selectNgramsByDoc (ns <> [listId]) dId ngramsType
764 let searchQuery (NgramsTerm nt) = flip S.member (S.fromList ngs) nt
765 getTableNgrams NodeDocument dId tabType listId limit_ offset listType minSize maxSize orderBy searchQuery
769 apiNgramsTableCorpus :: ( GargServerC env err m
771 => NodeId -> ServerT TableNgramsApi m
772 apiNgramsTableCorpus cId = getTableNgramsCorpus cId
774 :<|> scoresRecomputeTableNgrams cId
775 :<|> getTableNgramsVersion cId
776 :<|> apiNgramsAsync cId
778 apiNgramsTableDoc :: ( GargServerC env err m
780 => DocId -> ServerT TableNgramsApi m
781 apiNgramsTableDoc dId = getTableNgramsDoc dId
783 :<|> scoresRecomputeTableNgrams dId
784 :<|> getTableNgramsVersion dId
785 :<|> apiNgramsAsync dId
787 apiNgramsAsync :: NodeId -> GargServer TableNgramsAsyncApi
788 apiNgramsAsync _dId =
790 JobFunction $ \i log ->
793 printDebug "tableNgramsPostChartsAsync" x
795 in tableNgramsPostChartsAsync i log'
797 -- Did the given list of ngrams changed since the given version?
798 -- The returned value is versioned boolean value, meaning that one always retrieve the
800 -- If the given version is negative then one simply receive the latest version and True.
801 -- Using this function is more precise than simply comparing the latest version number
802 -- with the local version number. Indeed there might be no change to this particular list
803 -- and still the version number has changed because of other lists.
805 -- Here the added value is to make a compromise between precision, computation, and bandwidth:
806 -- * currentVersion: good computation, good bandwidth, bad precision.
807 -- * listNgramsChangedSince: good precision, good bandwidth, bad computation.
808 -- * tableNgramsPull: good precision, good bandwidth (if you use the received data!), bad computation.
809 listNgramsChangedSince :: HasNodeStory env err m
810 => ListId -> TableNgrams.NgramsType -> Version -> m (Versioned Bool)
811 listNgramsChangedSince listId ngramsType version
813 Versioned <$> currentVersion listId <*> pure True
815 tableNgramsPull listId ngramsType version & mapped . v_data %~ (== mempty)