-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathProjects.hs
More file actions
1169 lines (970 loc) · 42.6 KB
/
Copy pathProjects.hs
File metadata and controls
1169 lines (970 loc) · 42.6 KB
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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
module Models.Projects.Projects (
-- Users
User (..),
UserId (..),
createUser,
userIdByEmail,
createUserId,
insertUser,
userById,
userByEmail,
createEmptyUser,
-- Projects
Project (..),
Project' (..),
ProjectId,
CreateProject (..),
OnboardingStep (..),
ProjectS3Bucket (..),
insertProject,
projectIdFromText,
usersByProjectId,
usersByIds,
selectProjectsForUser,
getProjectByPhoneNumber,
activeProjects,
activeNonOnboardingProjectIds,
recentlyActiveProjectIds,
newProjectsSince,
updateProject,
patchProjectSettings,
deleteProject,
updateProjectPricing,
updateProjectBilling,
projectById,
projectByOrderId,
projectByCustomerId,
projectBySubId,
updateSubItemIdBySubId,
projectCacheById,
projectCacheByIdIO,
updateProjectReportNotif,
ProjectCache (..),
defaultProjectCache,
updateProjectS3Bucket,
QueryLibItemId,
QueryLibType (..),
QueryLibItem (..),
queryLibHistoryForUser,
queryLibInsert,
queryLibTitleEdit,
queryLibItemDelete,
-- Billing
BillingProvider (..),
billingProvider,
LemonSub (..),
LemonSubId (..),
addSubscription,
getTotalUsage,
getDailyUsageBreakdown,
-- Usage report submissions (chunked provider submissions)
UsageSubmission (..),
SubmissionOutcome (..),
ChunkQuantity,
mkChunkQuantity,
chunkQuantityInt,
splitUsageIntoChunks,
pendingUsageSubmissions,
recordUsageWindow,
UsageTotals (..),
markUsageSubmissionSucceeded,
markUsageSubmissionFailed,
upgradeToPaid,
downgradeToFree,
downgradeToFreeBySubId,
setPlanBySubId,
updateStripeProjectBilling,
-- Sessions
PersistentSessionId (..),
PersistentSession (..),
Session (..),
sessionAndProject,
craftSessionCookie,
SessionData (..),
PSUser (..),
PSProjects (..),
addCookie,
emptySessionCookie,
getSession,
insertSession,
getPersistentSession,
newPersistentSessionId,
-- Audit Log
AuditEvent (..),
logAudit,
logAuditS,
)
where
import Data.Aeson qualified as AE
import Data.CaseInsensitive qualified as CI
import Data.Char (isDigit)
import Data.Default
import Data.Effectful.Hasql qualified as EHasql
import Data.Effectful.UUID (UUIDEff, genUUID)
import Data.Effectful.UUID qualified as UUID
import Data.Text qualified as T
import Data.Text.Display
import Data.Time (Day, UTCTime, ZonedTime)
import Data.UUID qualified as UUID
import Data.Vector qualified as V
import Database.PostgreSQL.Entity.Types
import Database.PostgreSQL.Simple (FromRow, ToRow)
import Database.PostgreSQL.Simple.FromField (FromField)
import Database.PostgreSQL.Simple.Newtypes
import Database.PostgreSQL.Simple.ToField (ToField)
import Deriving.Aeson qualified as DAE
import Effectful
import Effectful.Error.Static (throwError)
import Effectful.Error.Static qualified as EffError
import Effectful.Reader.Static qualified as EffReader
import Effectful.Time (Time, currentTime, runTime)
import GHC.Records (HasField (getField))
import Hasql.Interpolate qualified as HI
import Hasql.Pool qualified as HPool
import Hasql.Statement (Statement)
import Hasql.Transaction qualified as Tx
import Hasql.Transaction.Sessions qualified as TxS
import Pkg.DeriveUtils (DB, UUIDId (..), WrappedEnumSC (..), idFromText, selectFrom)
import Pkg.Parser.Stats (Section)
import Relude
import Servant (FromHttpApiData, Header, Headers, ServerError, addHeader, err302, errHeaders, getResponse)
import Web.Cookie (SetCookie (setCookieHttpOnly, setCookieMaxAge, setCookieName, setCookiePath, setCookieSameSite, setCookieSecure, setCookieValue), defaultSetCookie, sameSiteLax)
import Web.FormUrlEncoded (FromForm)
import Web.HttpApiData (ToHttpApiData)
instance AE.FromJSON (CI.CI Text) where
parseJSON = fmap CI.mk . AE.parseJSON
instance AE.ToJSON (CI.CI Text) where
toJSON = AE.toJSON . CI.original
newtype UserId = UserId {getUserId :: UUID.UUID}
deriving stock (Eq, Generic, Show)
deriving newtype (NFData)
deriving anyclass (FromRow, HI.DecodeRow, ToRow)
deriving
(AE.FromJSON, AE.ToJSON, Default, FromField, FromHttpApiData, HI.DecodeValue, HI.EncodeValue, Ord, ToField)
via UUID.UUID
instance HasField "toText" UserId Text where
getField = UUID.toText . getUserId
data User = User
{ id :: UserId
, createdAt :: UTCTime
, updatedAt :: UTCTime
, deletedAt :: Maybe UTCTime
, active :: Bool
, firstName :: Text
, lastName :: Text
, displayImageUrl :: Text
, email :: CI.CI Text
, isSudo :: Bool
, phoneNumber :: Maybe Text
}
deriving stock (Generic, Show)
deriving anyclass (Default, FromRow, HI.DecodeRow, NFData, ToRow)
deriving
(Entity)
via (GenericEntity '[Schema "users", TableName "users", PrimaryKey "id", FieldModifiers '[CamelToSnake]] User)
deriving
(AE.FromJSON, AE.ToJSON)
via DAE.CustomJSON '[DAE.OmitNothingFields, DAE.FieldLabelModifier '[DAE.CamelToSnake]] User
createUserId :: UUIDEff :> es => Eff es UserId
createUserId = UserId <$> genUUID
createUser :: (Time :> es, UUIDEff :> es) => Text -> Text -> Text -> Text -> Eff es User
createUser firstName lastName picture email = do
uid <- createUserId
now <- currentTime
pure
$ User
{ id = uid
, createdAt = now
, updatedAt = now
, deletedAt = Nothing
, active = True
, firstName = firstName
, lastName = lastName
, displayImageUrl = picture
, email = CI.mk email
, phoneNumber = Nothing
, isSudo = False
}
insertUser :: DB es => User -> Eff es ()
insertUser u = do
let (uId, uCr, uUp, uDel, uAct, uFn, uLn, uImg, uEm, uPh, uSudo) =
(u.id, u.createdAt, u.updatedAt, u.deletedAt, u.active, u.firstName, u.lastName, u.displayImageUrl, u.email, u.phoneNumber, u.isSudo)
EHasql.interpExecute_ [HI.sql| INSERT INTO users.users (id, created_at, updated_at, deleted_at, active, first_name, last_name, display_image_url, email, phone_number, is_sudo) VALUES (#{uId}, #{uCr}, #{uUp}, #{uDel}, #{uAct}, #{uFn}, #{uLn}, #{uImg}, #{uEm}, #{uPh}, #{uSudo}) |]
userById :: DB es => UserId -> Eff es (Maybe User)
userById uid = EHasql.interpOne [HI.sql| SELECT * FROM users.users WHERE id = #{uid} |]
userByEmail :: DB es => Text -> Eff es (Maybe User)
userByEmail email = EHasql.interpOne [HI.sql| SELECT * FROM users.users WHERE email = #{email} |]
userIdByEmail :: DB es => Text -> Eff es (Maybe UserId)
userIdByEmail email = EHasql.interpOne [HI.sql|select id from users.users where email=#{email}|]
createEmptyUser :: DB es => Text -> Eff es (Maybe UserId)
createEmptyUser email = EHasql.interpOne [HI.sql| insert into users.users (email, active) values (#{email}, TRUE) on conflict do nothing returning id |]
---------------------------------
type ProjectId = UUIDId "project"
projectIdFromText :: Text -> Maybe ProjectId
projectIdFromText = idFromText
data OnboardingStep = Info | Survey | CreateMonitor | NotifChannel | Integration | Pricing | Complete
deriving stock (Eq, Generic, Read, Show)
deriving (AE.FromJSON, AE.ToJSON, FromField, NFData, ToField) via OnboardingStep
data Project = Project
{ id :: ProjectId
, createdAt :: UTCTime
, updatedAt :: UTCTime
, deletedAt :: Maybe UTCTime
, active :: Bool
, title :: Text
, description :: Text
, -- NOTE: We used to have hosts under project, but now hosts should be gotten from the endpoints.
-- NOTE: If there's heavy need and usage, we caould create a view. Otherwise, the project cache is best, if it meets our needs.
paymentPlan :: Text
, questions :: Maybe AE.Value
, dailyNotif :: Bool
, weeklyNotif :: Bool
, timeZone :: Text
, subId :: Maybe Text
, firstSubItemId :: Maybe Text
, orderId :: Maybe Text
, usageLastReported :: UTCTime
, billingDay :: Maybe UTCTime
, onboardingStepsCompleted :: V.Vector Text
, s3Bucket :: Maybe ProjectS3Bucket
, endpointAlerts :: Bool
, errorAlerts :: Bool
, customerId :: Maybe Text
}
deriving stock (Generic, Show)
deriving anyclass (FromRow, HI.DecodeRow, NFData)
deriving
(Entity)
via (GenericEntity '[Schema "projects", TableName "projects", PrimaryKey "id", FieldModifiers '[CamelToSnake]] Project)
deriving
(AE.FromJSON, AE.ToJSON)
via DAE.CustomJSON '[DAE.OmitNothingFields, DAE.FieldLabelModifier '[DAE.CamelToSnake]] Project
-- FIXME: Why was this record created? And not the regular projects record?
data Project' = Project'
{ id :: ProjectId
, createdAt :: UTCTime
, updatedAt :: UTCTime
, deletedAt :: Maybe UTCTime
, active :: Bool
, title :: Text
, description :: Text
, -- NOTE: We used to have hosts under project, but now hosts should be gotten from the endpoints.
-- NOTE: If there's heavy need and usage, we caould create a view. Otherwise, the project cache is best, if it meets our needs.
paymentPlan :: Text
, questions :: Maybe AE.Value
, dailyNotif :: Bool
, weeklyNotif :: Bool
, timeZone :: Text
, subId :: Maybe Text
, firstSubItemId :: Maybe Text
, orderId :: Maybe Text
, usageLastReported :: UTCTime
, billingDay :: Maybe UTCTime
, onboardingStepsCompleted :: V.Vector Text
, s3Bucket :: Maybe ProjectS3Bucket
, endpointAlerts :: Bool
, errorAlerts :: Bool
, customerId :: Maybe Text
, hasIntegrated :: Bool
, usersDisplayImages :: V.Vector Text
}
deriving stock (Generic, Show)
deriving anyclass (Default, FromRow, HI.DecodeRow, NFData)
data ProjectS3Bucket = ProjectS3Bucket
{ accessKey :: Text
, secretKey :: Text
, region :: Text
, bucket :: Text
, endpointUrl :: Text
}
deriving stock (Generic, Show)
deriving anyclass (AE.FromJSON, AE.ToJSON, FromForm, NFData)
deriving (FromField, ToField) via Aeson ProjectS3Bucket
deriving via Aeson ProjectS3Bucket instance HI.DecodeValue ProjectS3Bucket
deriving via Aeson ProjectS3Bucket instance HI.EncodeValue ProjectS3Bucket
data ProjectCache = ProjectCache
{ -- We need this hosts to mirror all the hosts in the endpoints table, and could use this for validation purposes to skip inserting endpoints just because of hosts
-- if endpoint exists but host is not in this list, then we have a query specifically for inserting hosts.
hosts :: V.Vector Text
, -- maybe we don't need this? See the next point.
endpointHashes :: V.Vector Text
, -- We check if every request is part of the redact list, so it's better if we don't need to hit the db for them with each request.
-- Since we have a need to redact fields by endpoint, we can simply have the fields paths be prepended by the endpoint hash.
-- [endpointHash]<>[field_category eg requestBody]<>[field_key_path]
-- Those redact fields that don't have endpoint or field_category attached, would be aplied to every endpoint and field category.
redactFieldslist :: V.Vector Text
, -- Daily count of events from otel_logs_and_spans table for the last 24 hours
dailyEventCount :: Int
, -- Daily count of metrics for the last 24 hours
dailyMetricCount :: Int
, paymentPlan :: Text
, -- Canonical URL path templates for matching at ingestion: "method|host|template_path"
canonicalPaths :: V.Vector Text
}
deriving stock (Generic, Show)
deriving anyclass (Default, FromRow, HI.DecodeRow, NFData)
defaultProjectCache :: ProjectCache
defaultProjectCache = def{paymentPlan = "Free"}
data CreateProject = CreateProject
{ id :: ProjectId
, title :: Text
, description :: Text
, paymentPlan :: Text
, timeZone :: Text
, subId :: Maybe Text
, firstSubItemId :: Maybe Text
, orderId :: Maybe Text
, dailyNotif :: Bool
, weeklyNotif :: Bool
, endpointAlerts :: Bool
, errorAlerts :: Bool
}
deriving stock (Generic, Show)
deriving anyclass (FromRow, ToRow)
deriving
(Entity)
via (GenericEntity '[Schema "projects", TableName "projects", PrimaryKey "id", FieldModifiers '[CamelToSnake]] CreateProject)
-- FIXME: We currently return an object with empty vectors when nothing was found.
projectCacheById :: (DB es, Time :> es) => ProjectId -> Eff es (Maybe ProjectCache)
projectCacheById pid = do
now <- currentTime
let pidText = pid.toText
EHasql.interpOne
[HI.sql|
select coalesce(ARRAY_AGG(DISTINCT hosts ORDER BY hosts ASC),'{}') hosts,
coalesce(ARRAY_AGG(DISTINCT endpoint_hashes ORDER BY endpoint_hashes ASC),'{}') endpoint_hashes,
coalesce(ARRAY_AGG(DISTINCT paths ORDER BY paths ASC),'{}') redacted_fields,
( SELECT count(*)::int FROM otel_logs_and_spans
WHERE project_id=#{pidText} AND timestamp > #{now}::timestamptz - INTERVAL '1' DAY
) daily_event_count,
( SELECT count(*)::int FROM telemetry.metrics
WHERE project_id=#{pid} AND timestamp > #{now}::timestamptz - INTERVAL '1' DAY
) daily_metric_count,
(SELECT COALESCE((SELECT payment_plan FROM projects.projects WHERE id = #{pid}),'Free')) payment_plan,
(SELECT COALESCE(ARRAY_AGG(DISTINCT method || '|' || host || '|' || canonical_path), '{}')
FROM apis.endpoints WHERE project_id = #{pid} AND canonical_path IS NOT NULL
) canonical_paths
from
-- field_category column was dropped by the 0090 cascade (apis.field_category
-- enum was the type). The redact-list format keeps the '<>' separators so
-- consumers that split on them still see three segments.
(select e.host hosts, e.hash endpoint_hashes, concat(rf.endpoint_hash,'<>','<>', rf.path) paths
from apis.endpoints e
left join projects.redacted_fields rf ON rf.project_id = e.project_id
where e.project_id = #{pid}
) enp; |]
projectCacheByIdIO :: HPool.Pool -> ProjectId -> IO (Maybe ProjectCache)
projectCacheByIdIO hpool pid = runEff $ EHasql.runHasqlPool hpool $ runTime $ projectCacheById pid
insertProject :: DB es => CreateProject -> Eff es ()
insertProject p = do
let (pId, pT, pD, pPP, pTZ, pSub, pFSI, pOrd, pDN, pWN, pEA, pErA) =
(p.id, p.title, p.description, p.paymentPlan, p.timeZone, p.subId, p.firstSubItemId, p.orderId, p.dailyNotif, p.weeklyNotif, p.endpointAlerts, p.errorAlerts)
EHasql.interpExecute_ [HI.sql| INSERT INTO projects.projects (id, title, description, payment_plan, time_zone, sub_id, first_sub_item_id, order_id, daily_notif, weekly_notif, endpoint_alerts, error_alerts) VALUES (#{pId}, #{pT}, #{pD}, #{pPP}, #{pTZ}, #{pSub}, #{pFSI}, #{pOrd}, #{pDN}, #{pWN}, #{pEA}, #{pErA}) |]
projectById :: DB es => ProjectId -> Eff es (Maybe Project)
projectById pid = EHasql.interpOne [HI.sql| select p.* from projects.projects p where id=#{pid}|]
projectByOrderId :: DB es => Text -> Eff es (Maybe Project)
projectByOrderId oid = EHasql.interpOne [HI.sql| select p.* from projects.projects p where order_id=#{oid}|]
projectByCustomerId :: DB es => Text -> Eff es (Maybe Project)
projectByCustomerId cid = EHasql.interpOne [HI.sql| select p.* from projects.projects p where customer_id=#{cid}|]
projectBySubId :: DB es => Text -> Eff es (Maybe Project)
projectBySubId subId = EHasql.interpOne [HI.sql| select p.* from projects.projects p where sub_id=#{subId}|]
updateSubItemIdBySubId :: DB es => Text -> Text -> Eff es Int64
updateSubItemIdBySubId newItemId subId =
EHasql.interpExecute [HI.sql| update projects.projects set first_sub_item_id=#{newItemId} where sub_id=#{subId}|]
getProjectByPhoneNumber :: DB es => Text -> Eff es (Maybe Project)
getProjectByPhoneNumber number =
EHasql.interpOne
[HI.sql| SELECT p.* FROM projects.projects p
JOIN projects.teams t ON t.project_id = p.id
WHERE t.is_everyone = TRUE AND t.deleted_at IS NULL
AND #{number} = ANY(t.phone_numbers)
LIMIT 1 |]
activeProjects :: DB es => Eff es [Project]
activeProjects = EHasql.interp [HI.sql|SELECT p.* FROM projects.projects p WHERE p.active = TRUE AND p.deleted_at IS NULL|]
activeNonOnboardingProjectIds :: DB es => Eff es (V.Vector ProjectId)
activeNonOnboardingProjectIds =
V.fromList <$> EHasql.interp [HI.sql|SELECT DISTINCT p.id FROM projects.projects p WHERE p.active = TRUE AND p.deleted_at IS NULL AND p.payment_plan != 'ONBOARDING'|]
recentlyActiveProjectIds :: DB es => UTCTime -> Eff es [ProjectId]
recentlyActiveProjectIds since =
EHasql.interp
[HI.sql|SELECT DISTINCT p.id FROM projects.projects p JOIN otel_logs_and_spans o ON o.project_id = p.id::text
WHERE p.active = TRUE AND p.deleted_at IS NULL AND p.payment_plan != 'ONBOARDING' AND o.timestamp > #{since}::timestamptz - interval '24 hours'|]
newProjectsSince :: DB es => UTCTime -> Eff es [Project]
newProjectsSince since =
EHasql.interp [HI.sql|SELECT p.* FROM projects.projects p WHERE p.created_at >= #{since}::timestamptz AND p.deleted_at IS NULL ORDER BY p.created_at DESC|]
selectProjectsForUser :: (DB es, Time :> es) => UserId -> Eff es [Project']
selectProjectsForUser uid = do
now <- currentTime
EHasql.interp
[HI.sql|
SELECT pp.*,
EXISTS (
SELECT 1 FROM otel_logs_and_spans ols
WHERE ols.project_id = pp.id::text
AND ols.timestamp >= #{now}::timestamptz - INTERVAL '30 days'
LIMIT 1
) as has_integrated,
ARRAY_AGG('/api/avatar/' || us.id::text) OVER (PARTITION BY pp.id)
FROM projects.projects AS pp
JOIN projects.project_members AS ppm ON (pp.id = ppm.project_id)
JOIN users.users AS us ON (us.id = ppm.user_id)
WHERE ppm.user_id = #{uid} AND pp.deleted_at IS NULL AND ppm.active = TRUE
ORDER BY updated_at DESC
|]
usersByProjectId :: DB es => ProjectId -> Eff es [User]
usersByProjectId pid =
EHasql.interp
[HI.sql| select u.id, u.created_at, u.updated_at, u.deleted_at, u.active, u.first_name, u.last_name, u.display_image_url, u.email, u.is_sudo, u.phone_number
from users.users u join projects.project_members pm on (pm.user_id=u.id) where project_id=#{pid} and u.active IS True and pm.active = TRUE;|]
usersByIds :: DB es => V.Vector UUID.UUID -> Eff es [User]
usersByIds uids
| V.null uids = pure []
| otherwise = EHasql.interp (selectFrom @User <> [HI.sql| WHERE id = ANY(#{uids}::uuid[]) |])
updateProject :: DB es => CreateProject -> Eff es Int64
updateProject cp = do
let (cT, cD, cPP, cSub, cFSI, cOrd, cTZ, cWN, cDN, cEA, cErA, cId) =
(cp.title, cp.description, cp.paymentPlan, cp.subId, cp.firstSubItemId, cp.orderId, cp.timeZone, cp.weeklyNotif, cp.dailyNotif, cp.endpointAlerts, cp.errorAlerts, cp.id)
EHasql.interpExecute
[HI.sql|
UPDATE projects.projects SET title=#{cT}, description=#{cD},
payment_plan=#{cPP}, sub_id=#{cSub}, first_sub_item_id=#{cFSI}, order_id=#{cOrd},
time_zone=#{cTZ}, weekly_notif=#{cWN}, daily_notif=#{cDN}, endpoint_alerts=#{cEA}, error_alerts=#{cErA} where id=#{cId};
|]
-- | Partial project update. Unspecified fields keep their current value (via COALESCE).
-- Returns the number of rows affected (0 ⇒ project not found).
patchProjectSettings
:: DB es
=> ProjectId
-> Maybe Text
-> Maybe Text
-> Maybe Text
-> Maybe Bool
-> Maybe Bool
-> Maybe Bool
-> Maybe Bool
-> UTCTime
-> Eff es Int64
patchProjectSettings pid title descr tz daily weekly endpointAlerts errorAlerts now =
EHasql.interpExecute
[HI.sql|
UPDATE projects.projects SET
title = COALESCE(#{title}, title),
description = COALESCE(#{descr}, description),
time_zone = COALESCE(#{tz}, time_zone),
daily_notif = COALESCE(#{daily}, daily_notif),
weekly_notif = COALESCE(#{weekly}, weekly_notif),
endpoint_alerts = COALESCE(#{endpointAlerts}, endpoint_alerts),
error_alerts = COALESCE(#{errorAlerts}, error_alerts),
updated_at = #{now}
WHERE id = #{pid}
|]
updateProjectPricing :: DB es => ProjectId -> Text -> Text -> Text -> Text -> V.Vector Text -> Eff es Int64
updateProjectPricing pid paymentPlan subId firstSubItemId orderId stepsCompleted =
EHasql.interpExecute [HI.sql| UPDATE projects.projects SET payment_plan=#{paymentPlan}, sub_id=#{subId}, first_sub_item_id=#{firstSubItemId}, order_id=#{orderId}, onboarding_steps_completed=#{stepsCompleted} where id=#{pid};|]
updateProjectBilling :: DB es => ProjectId -> Text -> Text -> Text -> Text -> Eff es Int64
updateProjectBilling pid paymentPlan subId firstSubItemId orderId =
EHasql.interpExecute [HI.sql| UPDATE projects.projects SET payment_plan=#{paymentPlan}, sub_id=#{subId}, first_sub_item_id=#{firstSubItemId}, order_id=#{orderId} WHERE id=#{pid} AND (first_sub_item_id IS NULL OR first_sub_item_id = '');|]
updateProjectReportNotif :: DB es => ProjectId -> Text -> Eff es Int64
updateProjectReportNotif pid report_type =
if report_type == "daily"
then EHasql.interpExecute [HI.sql| UPDATE projects.projects SET daily_notif=(not daily_notif) WHERE id=#{pid};|]
else EHasql.interpExecute [HI.sql| UPDATE projects.projects SET weekly_notif=(not weekly_notif) WHERE id=#{pid};|]
deleteProject :: (DB es, Time :> es) => ProjectId -> Eff es Int64
deleteProject pid = do
now <- currentTime
EHasql.interpExecute [HI.sql| UPDATE projects.projects SET deleted_at=#{now}, active=False where id=#{pid};|]
updateProjectS3Bucket :: DB es => ProjectId -> Maybe ProjectS3Bucket -> Eff es Int64
updateProjectS3Bucket pid bucket =
EHasql.interpExecute [HI.sql| UPDATE projects.projects SET s3_bucket=#{bucket} WHERE id=#{pid}|]
---------------------------------
type QueryLibItemId = UUIDId "querylib"
data QueryLibType = QLTHistory | QLTSaved
deriving (Eq, Generic, NFData, Read, Show)
deriving (AE.FromJSON, AE.ToJSON, FromField, HI.DecodeValue, HI.EncodeValue, ToField) via WrappedEnumSC "QLT" QueryLibType
data QueryLibItem = QueryLibItem
{ id :: QueryLibItemId
, projectId :: ProjectId
, createdAt :: UTCTime
, updatedAt :: UTCTime
, userId :: UserId
, queryType :: QueryLibType
, queryText :: Text
, queryAst :: AE.Value
, title :: Maybe Text
, byMe :: Bool
}
deriving (Eq, Generic, Show)
deriving anyclass (AE.FromJSON, AE.ToJSON, FromRow, HI.DecodeRow, NFData, ToRow)
queryLibHistoryForUser :: DB es => ProjectId -> UserId -> Eff es [QueryLibItem]
queryLibHistoryForUser pid uid =
EHasql.interp
[HI.sql|
(
SELECT id, project_id, created_at, updated_at, user_id, query_type, query_text, query_ast, title, user_id=#{uid}::uuid as byMe
FROM projects.query_library
WHERE user_id = #{uid}::uuid AND project_id = #{pid}::uuid AND query_type = 'history'
ORDER BY created_at DESC
LIMIT 50
)
UNION ALL
(
SELECT id, project_id, created_at, updated_at, user_id, query_type, query_text, query_ast, title, user_id=#{uid}::uuid as byMe
FROM projects.query_library
WHERE user_id = #{uid}::uuid AND project_id = #{pid}::uuid AND query_type = 'saved'
ORDER BY created_at DESC
LIMIT 50
)
UNION ALL
(
SELECT id, project_id, created_at, updated_at, user_id, query_type, query_text, query_ast,title, user_id=#{uid}::uuid as byMe
FROM projects.query_library
WHERE project_id = #{pid}::uuid AND user_id != #{uid}::uuid AND query_type = 'saved'
ORDER BY created_at DESC
LIMIT 50
);
|]
queryLibInsert :: DB es => QueryLibType -> ProjectId -> UserId -> Text -> [Section] -> Maybe Text -> Eff es ()
queryLibInsert qKind pid uid qt qast title = do
let qastJson = HI.AsJsonb qast
EHasql.interpExecute_
[HI.sql|
WITH removed_old AS (
DELETE FROM projects.query_library
WHERE id IN (
SELECT id
FROM projects.query_library
WHERE project_id = #{pid} AND user_id = #{uid} AND query_type = #{qKind}::projects.query_library_kind
ORDER BY created_at ASC
OFFSET 49
)
)
INSERT INTO projects.query_library (project_id, user_id, query_type, query_text, query_ast, title)
SELECT #{pid}, #{uid}, #{qKind}::projects.query_library_kind, #{qt}, #{qastJson}, #{title}
WHERE NOT EXISTS (
SELECT 1
FROM projects.query_library
WHERE project_id = #{pid} AND user_id = #{uid} AND query_type = #{qKind}::projects.query_library_kind
AND query_text = #{qt}
ORDER BY created_at DESC
LIMIT 1
)
ON CONFLICT DO NOTHING;
|]
queryLibTitleEdit :: DB es => ProjectId -> UserId -> Text -> Text -> Eff es ()
queryLibTitleEdit pid uid qId title = EHasql.interpExecute_ [HI.sql|UPDATE projects.query_library SET title=#{title} where project_id=#{pid} AND user_id=#{uid} AND id=#{qId}::uuid|]
queryLibItemDelete :: DB es => ProjectId -> UserId -> Text -> Eff es ()
queryLibItemDelete pid uid qId = EHasql.interpExecute_ [HI.sql|DELETE from projects.query_library where project_id=#{pid} AND user_id=#{uid} AND id=#{qId}::uuid|]
---------------------------------
-- LemonSqueezy subscription management
newtype LemonSubId = LemonSubId {lemonSubId :: UUID.UUID}
deriving stock (Generic, Show)
deriving newtype (AE.FromJSON, AE.ToJSON, Default, Eq, FromField, FromHttpApiData, HI.DecodeValue, HI.EncodeValue, NFData, Ord, ToField)
instance HasField "toText" LemonSubId Text where
getField = UUID.toText . lemonSubId
data LemonSub = LemonSub
{ id :: LemonSubId
, createdAt :: ZonedTime
, updatedAt :: ZonedTime
, projectId :: Text
, subscriptionId :: Int
, orderId :: Int
, firstSubId :: Int
, productName :: Text
, userEmail :: Text
}
deriving stock (Generic, Show)
deriving anyclass (FromRow, NFData, ToRow)
deriving (Entity) via (GenericEntity '[Schema "apis", TableName "subscriptions", PrimaryKey "id", FieldModifiers '[CamelToSnake]] LemonSub)
addSubscription :: DB es => LemonSub -> Eff es ()
addSubscription s = do
let (sId, sCr, sUp, sPid, sSub, sOrd, sFSub, sProd, sEmail) =
(s.id, s.createdAt, s.updatedAt, s.projectId, s.subscriptionId, s.orderId, s.firstSubId, s.productName, s.userEmail)
EHasql.interpExecute_
[HI.sql|
INSERT INTO apis.subscriptions (id, created_at, updated_at, project_id, subscription_id, order_id, first_sub_id, product_name, user_email)
VALUES (#{sId}, #{sCr}, #{sUp}, #{sPid}, #{sSub}, #{sOrd}, #{sFSub}, #{sProd}, #{sEmail})
ON CONFLICT (subscription_id) DO UPDATE SET
updated_at = now(),
order_id = EXCLUDED.order_id,
first_sub_id = EXCLUDED.first_sub_id,
product_name = EXCLUDED.product_name,
user_email = EXCLUDED.user_email,
project_id = COALESCE(NULLIF(EXCLUDED.project_id, ''), apis.subscriptions.project_id)
|]
-- | Sum of requests for the given project since `start`, using window_start
-- (when events occurred) rather than created_at (when the job ran). Pre-migration
-- rows without window_start are excluded from billing calculations.
-- | (totalRequests, totalBytes) since `start`, using window_start (when events
-- occurred) rather than created_at. Pre-migration rows without window_start
-- are excluded from billing calculations.
getTotalUsage :: DB es => ProjectId -> UTCTime -> Eff es (Int64, Int64)
getTotalUsage pid start =
fromMaybe (0, 0)
<$> EHasql.interpOne
[HI.sql|
SELECT COALESCE(SUM(total_requests), 0)::bigint,
COALESCE(SUM(total_event_bytes + total_metric_bytes), 0)::bigint
FROM apis.daily_usage
WHERE project_id = #{pid} AND window_start >= #{start}
|]
-- | Per-day usage breakdown since `start`, grouped by the day the events
-- occurred (window_start), newest first. Returns
-- (day, events, metrics, eventBytes, metricBytes).
getDailyUsageBreakdown :: DB es => ProjectId -> UTCTime -> Eff es [(Day, Int64, Int64, Int64, Int64)]
getDailyUsageBreakdown pid start =
EHasql.interp
[HI.sql|
SELECT (window_start AT TIME ZONE 'UTC')::date AS day,
SUM(total_requests)::bigint,
SUM(total_metrics)::bigint,
SUM(total_event_bytes)::bigint,
SUM(total_metric_bytes)::bigint
FROM apis.daily_usage
WHERE project_id = #{pid} AND window_start >= #{start}
GROUP BY day
ORDER BY day DESC
|]
-- | Quantity of events in one submission chunk. Invariant: 0 < n <= 900_000
-- (Lemon Squeezy rejects quantities > 1,000,000; 900k leaves headroom). The
-- smart constructor is the only public way in; splitUsageIntoChunks is the
-- only producer in the codebase.
newtype ChunkQuantity = ChunkQuantity Int
deriving stock (Eq, Generic)
deriving newtype (FromField, HI.DecodeValue, HI.EncodeValue, NFData, Show, ToField)
-- DecodeRow's role is nominal so newtype coercion doesn't deduce it; one-liner
-- mirrors the Int instance in Pkg.DeriveUtils.
instance HI.DecodeRow ChunkQuantity where
decodeRow = HI.getOneColumn <$> HI.decodeRow
-- | >>> mkChunkQuantity 0
-- Nothing
-- >>> mkChunkQuantity (-1)
-- Nothing
-- >>> mkChunkQuantity 1
-- Just 1
-- >>> mkChunkQuantity 900000
-- Just 900000
-- >>> mkChunkQuantity 900001
-- Nothing
mkChunkQuantity :: Int -> Maybe ChunkQuantity
mkChunkQuantity n
| n > 0 && n <= 900_000 = Just (ChunkQuantity n)
| otherwise = Nothing
chunkQuantityInt :: ChunkQuantity -> Int
chunkQuantityInt (ChunkQuantity n) = n
-- | State of a submission chunk. Collapses (status, submitted_at, last_error)
-- into one type so illegal combinations ("submitted" with a last_error,
-- "failed" without one) are unrepresentable. The DB CHECK constraints on
-- projects.usage_report_submissions enforce the same invariant at the write
-- boundary; this type guarantees it at the read boundary.
data SubmissionOutcome
= Pending
| Submitted !UTCTime
| Failed !Text
deriving stock (Eq, Generic, Show)
deriving anyclass (NFData)
-- | Per-chunk record of a usage submission to a billing provider. One window
-- may produce several rows. Bookkeeping (apis.daily_usage + usage_last_reported)
-- is committed atomically with 'Pending' rows BEFORE any provider HTTP call;
-- the outcome is then updated per submission. Non-'Submitted' rows are retried
-- on the next daily ReportUsage tick for the same project.
data UsageSubmission = UsageSubmission
{ id :: UUID.UUID
, projectId :: ProjectId
, windowStart :: UTCTime
, windowEnd :: UTCTime
, quantity :: ChunkQuantity
, outcome :: SubmissionOutcome
, createdAt :: UTCTime
}
deriving stock (Generic, Show)
deriving anyclass (NFData)
-- Manual DecodeRow: collapses the 3 DB columns (status, submitted_at, last_error)
-- into one SubmissionOutcome. Safe because DB CHECK constraints guarantee the
-- triples that can reach us — see migration 0084.
instance HI.DecodeRow UsageSubmission where
decodeRow = do
id_ <- HI.decodeRow
projectId <- HI.decodeRow
windowStart <- HI.decodeRow
windowEnd <- HI.decodeRow
quantity <- HI.decodeRow
status <- HI.decodeRow @Text
submittedAt <- HI.decodeRow @(Maybe UTCTime)
lastError <- HI.decodeRow @(Maybe Text)
createdAt <- HI.decodeRow
let outcome = case (status, submittedAt, lastError) of
("submitted", Just t, _) -> Submitted t
("failed", _, Just e) -> Failed e
_ -> Pending
pure UsageSubmission{id = id_, ..}
-- | >>> splitUsageIntoChunks 0
-- []
-- >>> splitUsageIntoChunks 500
-- [500]
-- >>> splitUsageIntoChunks 900000
-- [900000]
-- >>> splitUsageIntoChunks 900001
-- [900000,1]
-- >>> splitUsageIntoChunks 2700000
-- [900000,900000,900000]
-- >>> splitUsageIntoChunks 2700001
-- [900000,900000,900000,1]
splitUsageIntoChunks :: Int -> [ChunkQuantity]
splitUsageIntoChunks total
| total <= 0 = []
| otherwise =
let cap = 900_000 :: Int
(fulls, rem_) = total `divMod` cap
in replicate fulls (ChunkQuantity cap) <> [ChunkQuantity rem_ | rem_ > 0]
pendingUsageSubmissions :: DB es => ProjectId -> Eff es [UsageSubmission]
pendingUsageSubmissions pid =
EHasql.interp
[HI.sql|
SELECT id, project_id, window_start, window_end, quantity::int8, status, submitted_at, last_error, created_at
FROM projects.usage_report_submissions
WHERE project_id = #{pid} AND status <> 'submitted'
ORDER BY created_at ASC
|]
-- | Per-window usage totals: row counts split between events (logs+spans) and
-- metrics, plus the encoded-protobuf payload-byte sum for each. `total_requests`
-- (= events + metrics) drives existing pricing/chunking; the per-bucket fields
-- are visibility-only.
data UsageTotals = UsageTotals
{ events :: Int
, eventBytes :: Int64
, metrics :: Int
, metricBytes :: Int64
}
deriving stock (Eq, Show)
recordUsageWindow
:: (DB es, UUIDEff :> es)
=> ProjectId -> UTCTime -> UTCTime -> UsageTotals -> [ChunkQuantity] -> Eff es ()
recordUsageWindow pid wStart wEnd totals chunks = do
chunkIds <- replicateM (length chunks) genUUID
let exec :: HI.Sql -> Tx.Transaction ()
exec s = Tx.statement () (HI.interp True s :: Statement () HI.RowsAffected) $> ()
-- total_requests historically = events + metrics (drives splitUsageIntoChunks
-- and getTotalUsage). Preserve that invariant; new columns are additive.
totalUsage = totals.events + totals.metrics
mC = totals.metrics
eB = totals.eventBytes
mB = totals.metricBytes
EHasql.transaction TxS.ReadCommitted TxS.Write do
-- usage_last_reported always advances (even on zero-usage days); otherwise
-- the next tick re-scans an ever-growing window, which is the failure mode
-- that produced the original 15-month poison loop.
exec [HI.sql| UPDATE projects.projects SET usage_last_reported = #{wEnd} WHERE id = #{pid} |]
when (totalUsage > 0) do
exec
[HI.sql| INSERT INTO apis.daily_usage (project_id, total_requests, total_metrics, total_event_bytes, total_metric_bytes, window_start, window_end)
VALUES (#{pid}, #{totalUsage}, #{mC}, #{eB}, #{mB}, #{wStart}, #{wEnd}) |]
for_ (zip chunkIds chunks) \(cid, ChunkQuantity qty) ->
exec
[HI.sql| INSERT INTO projects.usage_report_submissions (id, project_id, window_start, window_end, quantity)
VALUES (#{cid}, #{pid}, #{wStart}, #{wEnd}, #{qty}) |]
markUsageSubmissionSucceeded :: DB es => UUID.UUID -> Eff es Int64
markUsageSubmissionSucceeded sid =
EHasql.interpExecute
[HI.sql|
UPDATE projects.usage_report_submissions
SET status = 'submitted', submitted_at = now(), last_error = NULL
WHERE id = #{sid}
|]
markUsageSubmissionFailed :: DB es => UUID.UUID -> Text -> Eff es Int64
markUsageSubmissionFailed sid err =
EHasql.interpExecute
[HI.sql|
UPDATE projects.usage_report_submissions
SET status = 'failed', last_error = #{err}
WHERE id = #{sid}
|]
-- Keep sub_id/order_id/first_sub_item_id intact on downgrade so resume/payment_success can re-upgrade without a new checkout.
downgradeToFree :: DB es => Int -> Int -> Int -> Eff es Int64
downgradeToFree orderId' _subId _subItemId = do
let oid = show orderId' :: Text
EHasql.interpExecute [HI.sql|UPDATE projects.projects SET payment_plan = 'Free' WHERE order_id = #{oid}|]
-- Match on sub_id when available (stable across plan/order changes), else fall back to order_id.
-- Using OR with both risks matching a stale preserved row on a different project after downgrade.
upgradeToPaid :: DB es => Int -> Int -> Int -> Text -> Eff es Int64
upgradeToPaid orderId' subId subItemId plan = do
let (sId, sItemId, oId) = (show subId :: Text, show subItemId :: Text, show orderId' :: Text)
EHasql.interpExecute
[HI.sql|
UPDATE projects.projects
SET payment_plan = #{plan}, sub_id = #{sId}, first_sub_item_id = #{sItemId}
WHERE sub_id = #{sId}
OR (sub_id IS NULL AND order_id = #{oId})
|]
-- | >>> billingProvider (Just "sub_abc123")
-- StripeProvider
-- >>> billingProvider (Just "12345")
-- LemonSqueezyProvider
-- >>> billingProvider Nothing
-- NoBillingProvider
-- >>> billingProvider (Just "")
-- NoBillingProvider
data BillingProvider = StripeProvider | LemonSqueezyProvider | NoBillingProvider
deriving stock (Eq, Show)
billingProvider :: Maybe Text -> BillingProvider
billingProvider = \case
Just sid
| "sub_" `T.isPrefixOf` sid -> StripeProvider
| not (T.null sid) && T.all isDigit sid -> LemonSqueezyProvider
_ -> NoBillingProvider
downgradeToFreeBySubId :: DB es => Text -> Eff es Int64
downgradeToFreeBySubId sid =
EHasql.interpExecute [HI.sql|UPDATE projects.projects SET payment_plan = 'Free' WHERE sub_id = #{sid}|]
-- Re-enable a previously-downgraded subscription (paused → active, past_due → active).
-- IDs were preserved by downgradeToFree* so we match by sub_id.
setPlanBySubId :: DB es => Text -> Text -> Text -> Eff es Int64
setPlanBySubId plan firstSubItemId sid =
EHasql.interpExecute [HI.sql|UPDATE projects.projects SET payment_plan = #{plan}, first_sub_item_id = #{firstSubItemId} WHERE sub_id = #{sid}|]
updateStripeProjectBilling :: DB es => ProjectId -> Text -> Text -> Text -> Text -> Eff es Int64
updateStripeProjectBilling pid plan subId firstSubItemId customerId =
-- Clear order_id so a late LemonSqueezy cancel webhook (from a prior LS→Stripe
-- switch) can't rematch this project by order_id and downgrade to Free.
EHasql.interpExecute [HI.sql|UPDATE projects.projects SET payment_plan = #{plan}, sub_id = #{subId}, first_sub_item_id = #{firstSubItemId}, customer_id = #{customerId}, order_id = NULL WHERE id = #{pid}|]
-- Sessions
newtype PersistentSessionId = PersistentSessionId {getPersistentSessionId :: UUID.UUID}
deriving newtype (NFData)
deriving (Display) via ShowInstance UUID.UUID
deriving
(Default, Eq, FromField, FromHttpApiData, HI.DecodeValue, HI.EncodeValue, Show, ToField, ToHttpApiData)
via UUID.UUID
newtype SessionData = SessionData {getSessionData :: Map Text Text}
deriving stock (Eq, Generic, Show)
deriving newtype (NFData)
deriving anyclass (Default)
deriving