package_name
stringlengths
2
45
version
stringclasses
313 values
license
stringclasses
49 values
homepage
stringclasses
350 values
dev_repo
stringclasses
351 values
file_type
stringclasses
6 values
file_path
stringlengths
6
151
file_content
stringlengths
0
15.6M
sihl-email
3.0.5
Unknown
Unknown
Unknown
dune
sihl-3.0.5/dune
(data_only_dirs node_modules .devcontainer .git)
sihl-email
3.0.5
Unknown
Unknown
Unknown
opam
sihl-3.0.5/sihl-cache.opam
# This file is generated by dune, edit dune-project instead opam-version: "2.0" version: "3.0.5" synopsis: "Cache service implementations for Sihl" description: "A key-value store with support for PostgreSQL and MariaDB." maintainer: ["[email protected]"] authors: ["Josef Erben" "Aron Erben" "Miko Nieminen"] license: "MIT" homepage: "https://github.com/oxidizing/sihl" doc: "https://oxidizing.github.io/sihl/" bug-reports: "https://github.com/oxidizing/sihl/issues" depends: [ "dune" {>= "2.7"} "ocaml" {>= "4.08.0"} "sihl" {= version} "alcotest-lwt" {>= "1.4.0" & with-test} "caqti-driver-postgresql" {>= "1.8.0" & with-test} "caqti-driver-mariadb" {>= "1.8.0" & with-test} "odoc" {with-doc} ] build: [ ["dune" "subst"] {dev} [ "dune" "build" "-p" name "-j" jobs "@install" "@runtest" {with-test} "@doc" {with-doc} ] ] dev-repo: "git+https://github.com/oxidizing/sihl.git"
sihl-email
3.0.5
Unknown
Unknown
Unknown
dune
sihl-3.0.5/sihl-cache/src/dune
(library (name sihl_cache) (public_name sihl-cache) (libraries sihl) (preprocess (pps ppx_deriving_yojson lwt_ppx))) (documentation (package sihl-cache))
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl-cache/src/repo_sql.ml
module type Sig = sig val lifecycles : Sihl.Container.lifecycle list val register_migration : unit -> unit val register_cleaner : unit -> unit val find : ?ctx:(string * string) list -> string -> string option Lwt.t val insert : ?ctx:(string * string) list -> string * string -> unit Lwt.t val update : ?ctx:(string * string) list -> string * string -> unit Lwt.t val delete : ?ctx:(string * string) list -> string -> unit Lwt.t end (* Common functions that are shared by SQL implementations *) let find_request = let open Caqti_request.Infix in {sql| SELECT cache_value FROM cache WHERE cache.cache_key = ? |sql} |> Caqti_type.(string ->? string) ;; let find ?ctx key = Sihl.Database.find_opt ?ctx find_request key let insert_request = let open Caqti_request.Infix in {sql| INSERT INTO cache ( cache_key, cache_value ) VALUES ( ?, ? ) |sql} |> Caqti_type.(tup2 string string ->. unit) ;; let insert ?ctx key_value = Sihl.Database.exec ?ctx insert_request key_value let update_request = let open Caqti_request.Infix in {sql| UPDATE cache SET cache_value = $2 WHERE cache_key = $1 |sql} |> Caqti_type.(tup2 string string ->. unit) ;; let update ?ctx key_value = Sihl.Database.exec ?ctx update_request key_value let delete_request = let open Caqti_request.Infix in {sql| DELETE FROM cache WHERE cache.cache_key = ? |sql} |> Caqti_type.(string ->. unit) ;; let delete ?ctx key = Sihl.Database.exec ?ctx delete_request key let clean_request = let open Caqti_request.Infix in "TRUNCATE TABLE cache" |> Caqti_type.(unit ->. unit) ;; let clean ?ctx () = Sihl.Database.exec clean_request ?ctx () module MakeMariaDb (MigrationService : Sihl.Contract.Migration.Sig) : Sig = struct let lifecycles = [ Sihl.Database.lifecycle; MigrationService.lifecycle ] let find = find let insert = insert let update = update let delete = delete let clean = clean module Migration = struct let create_cache_table = Sihl.Database.Migration.create_step ~label:"create cache table" {sql| CREATE TABLE IF NOT EXISTS cache ( id serial, cache_key VARCHAR(64) NOT NULL, cache_value VARCHAR(1024) NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY(id), CONSTRAINT unique_key UNIQUE(cache_key) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci |sql} ;; let migration () = Sihl.Database.Migration.(empty "cache" |> add_step create_cache_table) ;; end let register_migration () = MigrationService.register_migration (Migration.migration ()) ;; let register_cleaner () = Sihl.Cleaner.register_cleaner clean end module MakePostgreSql (MigrationService : Sihl.Contract.Migration.Sig) : Sig = struct let lifecycles = [ Sihl.Database.lifecycle; MigrationService.lifecycle ] let find = find let insert = insert let update = update let delete = delete let clean = clean module Migration = struct let create_cache_table = Sihl.Database.Migration.create_step ~label:"create cache table" {sql| CREATE TABLE IF NOT EXISTS cache ( id serial, cache_key VARCHAR NOT NULL, cache_value TEXT NOT NULL, created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (id), UNIQUE (cache_key) ) |sql} ;; let remove_timezone = Sihl.Database.Migration.create_step ~label:"remove timezone info from timestamps" {sql| ALTER TABLE cache ALTER COLUMN created_at TYPE TIMESTAMP |sql} ;; let migration () = Sihl.Database.Migration.( empty "cache" |> add_step create_cache_table |> add_step remove_timezone) ;; end let register_migration () = MigrationService.register_migration (Migration.migration ()) ;; let register_cleaner () = Sihl.Cleaner.register_cleaner clean end
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl-cache/src/sihl_cache.ml
let log_src = Logs.Src.create ("sihl.service." ^ Sihl.Contract.Cache.name) module Logs = (val Logs.src_log log_src : Logs.LOG) module MakeSql (Repo : Repo_sql.Sig) : Sihl.Contract.Cache.Sig = struct let find = Repo.find let set ?ctx (k, v) = match v with | Some v -> (match%lwt find k with | Some _ -> Repo.update ?ctx (k, v) | None -> Repo.insert ?ctx (k, v)) | None -> (match%lwt find k with | Some _ -> Repo.delete ?ctx k | None -> (* nothing to do *) Lwt.return ()) ;; (* Lifecycle *) let start () = Lwt.return () let stop () = Lwt.return () let lifecycle = Sihl.Container.create_lifecycle Sihl.Contract.Cache.name ~dependencies:(fun () -> Repo.lifecycles) ~start ~stop ;; let register () = Repo.register_migration (); Repo.register_cleaner (); Sihl.Container.Service.create lifecycle ;; end module PostgreSql = MakeSql (Repo_sql.MakePostgreSql (Sihl.Database.Migration.PostgreSql)) module MariaDb = MakeSql (Repo_sql.MakeMariaDb (Sihl.Database.Migration.MariaDb))
sihl-email
3.0.5
Unknown
Unknown
Unknown
mli
sihl-3.0.5/sihl-cache/src/sihl_cache.mli
val log_src : Logs.src module MariaDb : sig include Sihl.Contract.Cache.Sig end module PostgreSql : sig include Sihl.Contract.Cache.Sig end
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl-cache/test/cache.ml
open Alcotest_lwt module Make (CacheService : Sihl.Contract.Cache.Sig) = struct let create_and_read_cache _ () = let%lwt () = Sihl.Cleaner.clean_all () in let%lwt () = CacheService.set ("foo", Some "bar") in let%lwt () = CacheService.set ("fooz", Some "baz") in let%lwt value = CacheService.find "foo" in Alcotest.(check (option string) "has value" (Some "bar") value); let%lwt value = CacheService.find "fooz" in Alcotest.(check (option string) "has value" (Some "baz") value); Lwt.return () ;; let update_cache _ () = let%lwt () = Sihl.Cleaner.clean_all () in let%lwt () = CacheService.set ("foo", Some "bar") in let%lwt () = CacheService.set ("fooz", Some "baz") in let%lwt value = CacheService.find "foo" in Alcotest.(check (option string) "has value" (Some "bar") value); let%lwt () = CacheService.set ("foo", Some "updated") in let%lwt value = CacheService.find "foo" in Alcotest.(check (option string) "has value" (Some "updated") value); let%lwt () = CacheService.set ("foo", None) in let%lwt value = CacheService.find "foo" in Alcotest.(check (option string) "has value" None value); (* Make sure setting value that is None to None works as well *) let%lwt () = CacheService.set ("foo", None) in let%lwt value = CacheService.find "foo" in Alcotest.(check (option string) "has value" None value); Lwt.return () ;; let suite = [ ( "cache" , [ test_case "create and read" `Quick create_and_read_cache ; test_case "update" `Quick update_cache ] ) ] ;; end
sihl-email
3.0.5
Unknown
Unknown
Unknown
dune
sihl-3.0.5/sihl-cache/test/dune
(executables (names mariadb postgresql) (libraries sihl sihl-cache alcotest-lwt caqti-driver-mariadb caqti-driver-postgresql) (preprocess (pps lwt_ppx)))
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl-cache/test/mariadb.ml
let services = [ Sihl.Database.register () ; Sihl.Database.Migration.MariaDb.register [] ; Sihl_cache.MariaDb.register () ] ;; module Test = Cache.Make (Sihl_cache.MariaDb) let () = Sihl.Configuration.read_string "DATABASE_URL_TEST_MARIADB" |> Option.value ~default:"mariadb://admin:[email protected]:3306/dev" |> Unix.putenv "DATABASE_URL"; Logs.set_level (Sihl.Log.get_log_level ()); Logs.set_reporter (Sihl.Log.cli_reporter ()); Lwt_main.run (let%lwt _ = Sihl.Container.start_services services in let%lwt () = Sihl.Database.Migration.MariaDb.run_all () in Alcotest_lwt.run "mariadb" Test.suite) ;;
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl-cache/test/postgresql.ml
let services = [ Sihl.Database.register () ; Sihl.Database.Migration.PostgreSql.register [] ; Sihl_cache.PostgreSql.register () ] ;; module Test = Cache.Make (Sihl_cache.PostgreSql) let () = Sihl.Configuration.read_string "DATABASE_URL_TEST_POSTGRESQL" |> Option.value ~default:"postgres://admin:[email protected]:5432/dev" |> Unix.putenv "DATABASE_URL"; Logs.set_level (Sihl.Log.get_log_level ()); Logs.set_reporter (Sihl.Log.cli_reporter ()); Lwt_main.run (let%lwt _ = Sihl.Container.start_services services in let%lwt () = Sihl.Database.Migration.PostgreSql.run_all () in Alcotest_lwt.run "postgresql" Test.suite) ;;
sihl-email
3.0.5
Unknown
Unknown
Unknown
opam
sihl-3.0.5/sihl-email.opam
# This file is generated by dune, edit dune-project instead opam-version: "2.0" version: "3.0.5" synopsis: "Email service implementations for Sihl" description: "Modules for sending emails using Lwt and SMTP or Sendgrid." maintainer: ["[email protected]"] authors: ["Josef Erben" "Aron Erben" "Miko Nieminen"] license: "MIT" homepage: "https://github.com/oxidizing/sihl" doc: "https://oxidizing.github.io/sihl/" bug-reports: "https://github.com/oxidizing/sihl/issues" depends: [ "dune" {>= "2.7"} "ocaml" {>= "4.08.0"} "letters" {>= "0.2.1"} "sihl" {= version} "cohttp-lwt-unix" {>= "2.5.4"} "alcotest-lwt" {>= "1.4.0" & with-test} "caqti-driver-postgresql" {>= "1.8.0" & with-test} "caqti-driver-mariadb" {>= "1.8.0" & with-test} "odoc" {with-doc} ] build: [ ["dune" "subst"] {dev} [ "dune" "build" "-p" name "-j" jobs "@install" "@runtest" {with-test} "@doc" {with-doc} ] ] dev-repo: "git+https://github.com/oxidizing/sihl.git"
sihl-email
3.0.5
Unknown
Unknown
Unknown
dune
sihl-3.0.5/sihl-email/src/dune
(library (name sihl_email) (public_name sihl-email) (libraries sihl cohttp cohttp-lwt-unix letters) (preprocess (pps ppx_deriving_yojson lwt_ppx))) (documentation (package sihl-email))
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl-email/src/sihl_email.ml
include Sihl.Contract.Email let log_src = Logs.Src.create ("sihl.service." ^ Sihl.Contract.Email.name) module Logs = (val Logs.src_log log_src : Logs.LOG) let dev_inbox : Sihl.Contract.Email.t list ref = ref [] module DevInbox = struct let inbox () = !dev_inbox let add_to_inbox email = dev_inbox := List.cons email !dev_inbox let clear_inbox () = dev_inbox := [] end let print email = let open Sihl.Contract.Email in Logs.info (fun m -> m {| ----------------------- Email sent by: %s Recipient: %s Subject: %s ----------------------- Text: %s ----------------------- Html: %s ----------------------- |} email.sender email.recipient email.subject email.text (Option.value ~default:"<None>" email.html)) ;; let should_intercept () = let is_production = Sihl.Configuration.is_production () in let bypass = Option.value ~default:false (Sihl.Configuration.read_bool "EMAIL_BYPASS_INTERCEPT") in match is_production, bypass with | false, true -> false | false, false -> true | true, _ -> false ;; let intercept sender email = let is_development = Sihl.Configuration.is_development () in let console = Option.value ~default:is_development (Sihl.Configuration.read_bool "EMAIL_CONSOLE") in let () = if console then print email else () in if should_intercept () then Lwt.return (DevInbox.add_to_inbox email) else sender email ;; type smtp_config = { sender : string ; username : string option ; password : string option ; hostname : string ; port : int option ; start_tls : bool ; ca_path : string option ; ca_cert : string option ; console : bool option } let smtp_config sender username password hostname port start_tls ca_path ca_cert console = { sender ; username ; password ; hostname ; port ; start_tls ; ca_path ; ca_cert ; console } ;; let smtp_schema = let open Conformist in make [ string "SMTP_SENDER" (* TODO wrap as pair as described in https://github.com/oxidizing/conformist/issues/11, once exists *) ; optional (string "SMTP_USERNAME") ; optional (string "SMTP_PASSWORD") ; string "SMTP_HOST" ; optional (int ~default:587 "SMTP_PORT") ; bool "SMTP_START_TLS" ; optional (string "SMTP_CA_PATH") ; optional (string "SMTP_CA_CERT") ; optional (bool ~default:false "EMAIL_CONSOLE") ] smtp_config ;; module type SmtpConfig = sig val fetch : unit -> smtp_config Lwt.t end module MakeSmtp (Config : SmtpConfig) : Sihl.Contract.Email.Sig = struct include DevInbox let send' (email : Sihl.Contract.Email.t) = let recipients = List.concat [ [ Letters.To email.recipient ] ; List.map (fun address -> Letters.Cc address) email.cc ; List.map (fun address -> Letters.Bcc address) email.bcc ] in let body = match email.html with | Some html -> Letters.Html html | None -> Letters.Plain email.text in let%lwt config = Config.fetch () in let sender = config.sender in let username = config.username |> CCOption.get_or ~default:"" in let password = config.password |> CCOption.get_or ~default:"" in let hostname = config.hostname in let port = config.port in let with_starttls = config.start_tls in let ca_path = config.ca_path in let ca_cert = config.ca_cert in let config = Letters.Config.make ~username ~password ~hostname ~with_starttls |> Letters.Config.set_port port |> fun conf -> match ca_cert, ca_path with | Some path, _ -> Letters.Config.set_ca_cert path conf | None, Some path -> Letters.Config.set_ca_path path conf | None, None -> conf in Letters.build_email ~from:email.sender ~recipients ~subject:email.subject ~body |> function | Ok message -> Letters.send ~config ~sender ~recipients ~message | Error msg -> raise (Sihl.Contract.Email.Exception msg) ;; let send ?ctx:_ email = intercept send' email let bulk_send ?ctx:_ _ = failwith "Bulk sending with the SMTP backend not supported, please use sihl-queue" ;; let start () = (* Make sure that configuration is valid *) if Sihl.Configuration.is_production () then Sihl.Configuration.require smtp_schema else (); (* If mail is intercepted, don't punish user for not providing SMTP credentials *) if should_intercept () then () else Sihl.Configuration.require smtp_schema; Lwt.return () ;; let stop () = Lwt.return () let lifecycle = Sihl.Container.create_lifecycle Sihl.Contract.Email.name ~start ~stop ;; let register () = let configuration = Sihl.Configuration.make ~schema:smtp_schema () in Sihl.Container.Service.create ~configuration lifecycle ;; end module EnvSmtpConfig = struct let fetch () = Lwt.return @@ Sihl.Configuration.read smtp_schema end module Smtp = MakeSmtp (EnvSmtpConfig) type sendgrid_config = { api_key : string ; console : bool option } let sendgrid_config api_key console = { api_key; console } let sendgrid_schema = let open Conformist in make [ string "SENDGRID_API_KEY" ; optional (bool ~default:false "EMAIL_CONSOLE") ] sendgrid_config ;; module type SendGridConfig = sig val fetch : unit -> sendgrid_config Lwt.t end module MakeSendGrid (Config : SendGridConfig) : Sihl.Contract.Email.Sig = struct include DevInbox let body ~recipient ~subject ~sender ~content = Printf.sprintf {| { "personalizations": [ { "to": [ { "email": "%s" } ], "subject": "%s" } ], "from": { "email": "%s" }, "content": [ { "type": "text/plain", "value": "%s" } ] } |} recipient subject sender content ;; let sendgrid_send_url = "https://api.sendgrid.com/v3/mail/send" |> Uri.of_string ;; let send' email = let open Sihl.Contract.Email in let%lwt config = Config.fetch () in let token = config.api_key in let headers = Cohttp.Header.of_list [ "authorization", "Bearer " ^ token ; "content-type", "application/json" ] in let sender = email.sender in let recipient = email.recipient in let subject = email.subject in let text_content = email.text in (* TODO support html content *) (* let html_content = Sihl.Email.text_content email in *) let req_body = body ~recipient ~subject ~sender ~content:text_content in let%lwt resp, resp_body = Cohttp_lwt_unix.Client.post ~body:(Cohttp_lwt.Body.of_string req_body) ~headers sendgrid_send_url in let status = Cohttp.Response.status resp |> Cohttp.Code.code_of_status in match status with | 200 | 202 -> Logs.info (fun m -> m "Successfully sent email using sendgrid"); Lwt.return () | _ -> let%lwt body = Cohttp_lwt.Body.to_string resp_body in Logs.err (fun m -> m "Sending email using sendgrid failed with http status %i and body %s" status body); raise (Sihl.Contract.Email.Exception "Failed to send email") ;; let send ?ctx:_ email = intercept send' email let bulk_send ?ctx:_ _ = failwith "bulk_send() with the Sendgrid backend is not supported, please use \ sihl-queue" ;; let start () = (* Make sure that configuration is valid *) if Sihl.Configuration.is_production () then Sihl.Configuration.require sendgrid_schema else (); (* If mail is intercepted, don't punish user for not providing SMTP credentials *) if should_intercept () then () else Sihl.Configuration.require sendgrid_schema; Lwt.return () ;; let stop () = Lwt.return () let lifecycle = Sihl.Container.create_lifecycle Sihl.Contract.Email.name ~start ~stop ;; let register () = let configuration = Sihl.Configuration.make ~schema:sendgrid_schema () in Sihl.Container.Service.create ~configuration lifecycle ;; end module EnvSendGridConfig = struct let fetch () = Lwt.return (Sihl.Configuration.read sendgrid_schema) end module SendGrid = MakeSendGrid (EnvSendGridConfig) (* This is useful if you need to answer a request quickly while sending the email in the background *) module Queued (QueueService : Sihl.Contract.Queue.Sig) (Email : Sihl.Contract.Email.Sig) : Sihl.Contract.Email.Sig = struct include DevInbox module Job = struct let input_to_string email = email |> Sihl.Contract.Email.to_yojson |> Yojson.Safe.to_string ;; let string_to_input email = let email = try Ok (Yojson.Safe.from_string email) with | _ -> Logs.err (fun m -> m "Serialized email string was NULL, can not deserialize email. \ Please fix the string manually and reset the job instance."); Error "Invalid serialized email string received" in Result.bind email (fun email -> email |> Sihl.Contract.Email.of_yojson |> Option.to_result ~none:"Failed to deserialize email") ;; let handle email = Lwt.catch (fun () -> Email.send email |> Lwt.map Result.ok) (fun exn -> let exn_string = Printexc.to_string exn in Lwt.return @@ Error exn_string) ;; let job = Sihl.Contract.Queue.create_job handle ~max_tries:10 ~retry_delay:(Sihl.Time.Span.hours 1) input_to_string string_to_input "send_email" ;; let dispatch email = QueueService.dispatch email job let dispatch_all emails = QueueService.dispatch_all emails job end let send ?ctx:_ email = Job.dispatch email let bulk_send ?ctx:_ emails = Job.dispatch_all emails let start () = QueueService.register_jobs [ Sihl.Contract.Queue.hide Job.job ] let stop () = Lwt.return () let lifecycle = Sihl.Container.create_lifecycle Sihl.Contract.Email.name ~start ~stop ~dependencies:(fun () -> [ Email.lifecycle; Sihl.Database.lifecycle; QueueService.lifecycle ]) ;; let register () = Sihl.Container.Service.create lifecycle end module Template = Template
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl-email/src/template.ml
include Sihl.Contract.Email_template let log_src = Logs.Src.create ("sihl.service." ^ Sihl.Contract.Email_template.name) ;; module Logs = (val Logs.src_log log_src : Logs.LOG) module Make (Repo : Template_repo_sql.Sig) : Sihl.Contract.Email_template.Sig = struct let get = Repo.get let get_by_label = Repo.get_by_label let create ?ctx ?id ?html ?language ~label text = let open Sihl.Contract.Email_template in let now = Ptime_clock.now () in let id = Option.value id ~default:(Uuidm.v `V4 |> Uuidm.to_string) in let template = { id; label; language; html; text; created_at = now; updated_at = now } in let%lwt () = Repo.insert ?ctx template in let%lwt created = Repo.get ?ctx id in match created with | None -> Logs.err (fun m -> m "Could not create template %a" Sihl.Contract.Email_template.pp template); raise (Sihl.Contract.Email.Exception "Could not create email template") | Some created -> Lwt.return created ;; let update ?ctx template = let%lwt () = Repo.update ?ctx template in let id = template.id in let%lwt created = Repo.get ?ctx id in match created with | None -> Logs.err (fun m -> m "Could not update template %a" Sihl.Contract.Email_template.pp template); raise (Sihl.Contract.Email.Exception "Could not create email template") | Some created -> Lwt.return created ;; let start () = Lwt.return () let stop () = Lwt.return () let lifecycle = Sihl.Container.create_lifecycle Sihl.Contract.Email_template.name ~dependencies:(fun () -> Repo.lifecycles) ~start ~stop ;; let register () = Repo.register_migration (); Repo.register_cleaner (); Sihl.Container.Service.create lifecycle ;; end module PostgreSql = Make (Template_repo_sql.MakePostgreSql (Sihl.Database.Migration.PostgreSql)) module MariaDb = Make (Template_repo_sql.MakeMariaDb (Sihl.Database.Migration.MariaDb))
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl-email/src/template_repo_sql.ml
module type Sig = sig val lifecycles : Sihl.Container.lifecycle list val register_migration : unit -> unit val register_cleaner : unit -> unit val get : ?ctx:(string * string) list -> string -> Sihl.Contract.Email_template.t option Lwt.t val get_by_label : ?ctx:(string * string) list -> ?language:string -> string -> Sihl.Contract.Email_template.t option Lwt.t val insert : ?ctx:(string * string) list -> Sihl.Contract.Email_template.t -> unit Lwt.t val update : ?ctx:(string * string) list -> Sihl.Contract.Email_template.t -> unit Lwt.t end let template = let open Sihl.Contract.Email_template in let encode m = Ok ( m.id , (m.label, (m.language, (m.text, (m.html, (m.created_at, m.updated_at))))) ) in let decode (id, (label, (language, (text, (html, (created_at, updated_at)))))) = Ok { id; label; language; text; html; created_at; updated_at } in Caqti_type.( custom ~encode ~decode (tup2 string (tup2 string (tup2 (option string) (tup2 string (tup2 (option string) (tup2 ptime ptime))))))) ;; module MakeMariaDb (MigrationService : Sihl.Contract.Migration.Sig) : Sig = struct let lifecycles = [ Sihl.Database.lifecycle; MigrationService.lifecycle ] module Sql = struct module Model = Sihl.Contract.Email_template let get_request = let open Caqti_request.Infix in {sql| SELECT LOWER(CONCAT( SUBSTR(HEX(uuid), 1, 8), '-', SUBSTR(HEX(uuid), 9, 4), '-', SUBSTR(HEX(uuid), 13, 4), '-', SUBSTR(HEX(uuid), 17, 4), '-', SUBSTR(HEX(uuid), 21) )), label, language, content_text, content_html, created_at, updated_at FROM email_templates WHERE email_templates.uuid = UNHEX(REPLACE(?, '-', '')) |sql} |> Caqti_type.(string ->? template) ;; let get ?ctx id = Sihl.Database.find_opt ?ctx get_request id let get_by_label_request ?(with_language = false) ctype = let open Caqti_request.Infix in {sql| SELECT LOWER(CONCAT( SUBSTR(HEX(uuid), 1, 8), '-', SUBSTR(HEX(uuid), 9, 4), '-', SUBSTR(HEX(uuid), 13, 4), '-', SUBSTR(HEX(uuid), 17, 4), '-', SUBSTR(HEX(uuid), 21) )), label, language, content_text, content_html, created_at, updated_at FROM email_templates WHERE email_templates.label = ? |sql} |> (fun sql -> if with_language then {sql| AND email_templates.language = ? |sql} |> Format.asprintf "%s\n%s" sql else sql) |> ctype ->? template ;; let get_by_label ?ctx ?language label = match language with | None -> Sihl.Database.find_opt ?ctx (get_by_label_request Caqti_type.string) label | Some language -> Sihl.Database.find_opt ?ctx (get_by_label_request ~with_language:true Caqti_type.(tup2 string string)) (label, language) ;; let insert_request = let open Caqti_request.Infix in {sql| INSERT INTO email_templates ( uuid, label, language, content_text, content_html, created_at, updated_at ) VALUES ( UNHEX(REPLACE(?, '-', '')), ?, ?, ?, ?, ?, ? ) |sql} |> template ->. Caqti_type.unit ;; let insert ?ctx template = Sihl.Database.exec ?ctx insert_request template let update_request = let open Caqti_request.Infix in {sql| UPDATE email_templates SET label = $2, language = $3, content_text = $4, content_html = $5, created_at = $6, updated_at = $7 WHERE email_templates.uuid = UNHEX(REPLACE($1, '-', '')) |sql} |> template ->. Caqti_type.unit ;; let update ?ctx template = Sihl.Database.exec ?ctx update_request template let clean_request = let open Caqti_request.Infix in "TRUNCATE TABLE email_templates" |> Caqti_type.(unit ->. unit) ;; let clean ?ctx () = Sihl.Database.exec ?ctx clean_request () end module Migration = struct let fix_collation = Sihl.Database.Migration.create_step ~label:"fix collation" "SET collation_server = 'utf8mb4_unicode_ci'" ;; let create_templates_table = Sihl.Database.Migration.create_step ~label:"create templates table" {sql| CREATE TABLE IF NOT EXISTS email_templates ( id BIGINT UNSIGNED AUTO_INCREMENT, uuid BINARY(16) NOT NULL, name VARCHAR(128) NOT NULL, content_text TEXT NOT NULL, content_html TEXT NOT NULL, created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (id), CONSTRAINT unique_uuid UNIQUE KEY (uuid), CONSTRAINT unique_name UNIQUE KEY (name) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci |sql} ;; let rename_name_column = Sihl.Database.Migration.create_step ~label:"rename name column" {sql| ALTER TABLE email_templates CHANGE COLUMN `name` label VARCHAR(128) NOT NULL |sql} ;; let add_updated_at_column = Sihl.Database.Migration.create_step ~label:"add updated_at column" {sql| ALTER TABLE email_templates ADD COLUMN updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP |sql} ;; let make_html_nullable = Sihl.Database.Migration.create_step ~label:"make html nullable" {sql| ALTER TABLE email_templates MODIFY content_html TEXT NULL |sql} ;; let add_language_column = Sihl.Database.Migration.create_step ~label:"add language column" {sql| ALTER TABLE email_templates ADD COLUMN language VARCHAR(128) NULL AFTER `label` |sql} ;; let remove_unique_label_constraint = Sihl.Database.Migration.create_step ~label:"remove unique label constraint" {sql| ALTER TABLE email_templates DROP CONSTRAINT unique_name |sql} ;; let make_label_language_combination_unique = Sihl.Database.Migration.create_step ~label:"make label language combination unique" {sql| ALTER TABLE email_templates ADD CONSTRAINT unique_label_language UNIQUE(label, language) |sql} ;; let migration () = Sihl.Database.Migration.( empty "email" |> add_step fix_collation |> add_step create_templates_table |> add_step rename_name_column |> add_step add_updated_at_column |> add_step make_html_nullable |> add_step add_language_column |> add_step remove_unique_label_constraint |> add_step make_label_language_combination_unique) ;; end let register_migration () = MigrationService.register_migration (Migration.migration ()) ;; let register_cleaner () = Sihl.Cleaner.register_cleaner Sql.clean let get = Sql.get let get_by_label = Sql.get_by_label let insert = Sql.insert let update = Sql.update end module MakePostgreSql (MigrationService : Sihl.Contract.Migration.Sig) : Sig = struct let lifecycles = [ Sihl.Database.lifecycle; MigrationService.lifecycle ] module Sql = struct module Model = Sihl.Contract.Email_template let get_request = let open Caqti_request.Infix in {sql| SELECT uuid, label, language, content_text, content_html, created_at, updated_at FROM email_templates WHERE email_templates.uuid = $1::uuid |sql} |> Caqti_type.string ->? template ;; let get ?ctx id = Sihl.Database.find_opt ?ctx get_request id let get_by_label_request ?(with_language = false) ctype = let open Caqti_request.Infix in {sql| SELECT uuid, label, language, content_text, content_html, created_at, updated_at FROM email_templates WHERE email_templates.label = ? |sql} |> (fun sql -> if with_language then {sql| AND email_templates.language = ? |sql} |> Format.asprintf "%s\n%s" sql else sql) |> ctype ->? template ;; let get_by_label ?ctx ?language label = match language with | None -> Sihl.Database.find_opt ?ctx (get_by_label_request Caqti_type.string) label | Some language -> Sihl.Database.find_opt ?ctx (get_by_label_request ~with_language:true Caqti_type.(tup2 string string)) (label, language) ;; let insert_request = let open Caqti_request.Infix in {sql| INSERT INTO email_templates ( uuid, label, language, content_text, content_html, created_at, updated_at ) VALUES ( $1::uuid, $2, $3, $4, $5, $6 AT TIME ZONE 'UTC', $7 AT TIME ZONE 'UTC' ) |sql} |> template ->. Caqti_type.unit ;; let insert ?ctx template = Sihl.Database.exec ?ctx insert_request template let update_request = let open Caqti_request.Infix in {sql| UPDATE email_templates SET label = $2, language = $3, content_text = $4, content_html = $5, created_at = $6 AT TIME ZONE 'UTC', updated_at = $7 AT TIME ZONE 'UTC' WHERE email_templates.uuid = $1::uuid |sql} |> template ->. Caqti_type.unit ;; let update ?ctx template = Sihl.Database.exec ?ctx update_request template let clean_request = let open Caqti_request.Infix in "TRUNCATE TABLE email_templates CASCADE" |> Caqti_type.(unit ->. unit) ;; let clean ?ctx () = Sihl.Database.exec ?ctx clean_request () end module Migration = struct let create_templates_table = Sihl.Database.Migration.create_step ~label:"create templates table" {sql| CREATE TABLE IF NOT EXISTS email_templates ( id SERIAL, uuid UUID NOT NULL, name VARCHAR(128) NOT NULL, content_text TEXT NOT NULL, content_html TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), PRIMARY KEY (id), UNIQUE (uuid), UNIQUE (name) ) |sql} ;; let rename_name_column = Sihl.Database.Migration.create_step ~label:"rename name column" {sql| ALTER TABLE email_templates RENAME COLUMN name TO label |sql} ;; let add_updated_at_column = Sihl.Database.Migration.create_step ~label:"add updated_at column" {sql| ALTER TABLE email_templates ADD COLUMN updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() |sql} ;; let make_html_nullable = Sihl.Database.Migration.create_step ~label:"make html nullable" {sql| ALTER TABLE email_templates ALTER COLUMN content_html DROP NOT NULL |sql} ;; let remove_timezone = Sihl.Database.Migration.create_step ~label:"remove timezone info from timestamps" {sql| ALTER TABLE email_templates ALTER COLUMN created_at TYPE TIMESTAMP, ALTER COLUMN updated_at TYPE TIMESTAMP |sql} ;; let add_language_column = Sihl.Database.Migration.create_step ~label:"add language column" {sql| ALTER TABLE email_templates ADD COLUMN language VARCHAR(128) NULL |sql} ;; let remove_unique_label_constraint = Sihl.Database.Migration.create_step ~label:"remove unique label constraint" {sql| ALTER TABLE email_templates DROP CONSTRAINT email_templates_name_key |sql} ;; let make_label_language_combination_unique = Sihl.Database.Migration.create_step ~label:"make label language combination unique" {sql| ALTER TABLE email_templates ADD CONSTRAINT email_templates_label_language_key UNIQUE(label, language) |sql} ;; let migration () = Sihl.Database.Migration.( empty "email" |> add_step create_templates_table |> add_step rename_name_column |> add_step add_updated_at_column |> add_step make_html_nullable |> add_step remove_timezone |> add_step add_language_column |> add_step remove_unique_label_constraint |> add_step make_label_language_combination_unique) ;; end let register_migration () = MigrationService.register_migration (Migration.migration ()) ;; let register_cleaner () = Sihl.Cleaner.register_cleaner Sql.clean let get = Sql.get let get_by_label = Sql.get_by_label let insert = Sql.insert let update = Sql.update end
sihl-email
3.0.5
Unknown
Unknown
Unknown
dune
sihl-3.0.5/sihl-email/test/dune
(executables (names template email_mariadb email_postgresql) (libraries sihl sihl-email alcotest-lwt caqti-driver-mariadb caqti-driver-postgresql) (preprocess (pps lwt_ppx)))
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl-email/test/email.ml
open Alcotest_lwt let template_testable = Alcotest.testable Sihl.Contract.Email_template.pp (fun a b -> let open Sihl.Contract.Email_template in CCString.equal a.id b.id) ;; module Make (EmailService : Sihl.Contract.Email.Sig) (EmailTemplateService : Sihl.Contract.Email_template.Sig) = struct let create_template _ () = let%lwt () = Sihl.Cleaner.clean_all () in let%lwt template = EmailTemplateService.create ~label:"foo" ~html:"some html" "some text" in Alcotest.(check string "name" "foo" template.label); Alcotest.(check (option string) "label" None template.language); Alcotest.(check string "has text" "some text" template.text); Alcotest.(check (option string) "has html" (Some "some html") template.html); Lwt.return () ;; let create_template_with_language _ () = let%lwt () = Sihl.Cleaner.clean_all () in let%lwt template = EmailTemplateService.create ~label:"foo" ~language:"EN" ~html:"some html" "some text" in Alcotest.(check string "label" "foo" template.label); Alcotest.(check (option string) "language" (Some "EN") template.language); Alcotest.(check string "has text" "some text" template.text); Alcotest.(check (option string) "has html" (Some "some html") template.html); Lwt.return () ;; let update_template _ () = let%lwt () = Sihl.Cleaner.clean_all () in let%lwt created = EmailTemplateService.create ~label:"foo" ~html:"some html" "some text" in let updated = Sihl_email.Template.set_label "newname" created in let%lwt template = EmailTemplateService.update updated in Alcotest.(check string "label" "newname" template.label); Lwt.return () ;; let get_template_by_label_and_language _ () = let%lwt () = Sihl.Cleaner.clean_all () in let%lwt expected = EmailTemplateService.create ~label:"foo" ~language:"EN" ~html:"some html" "some text" in let%lwt existing = EmailTemplateService.get_by_label ~language:"EN" "foo" in let%lwt not_existing = EmailTemplateService.get_by_label ~language:"DE" "foo" in Alcotest.( check (option template_testable) "template" (Some expected) existing); Alcotest.(check (option template_testable) "template" None not_existing); Lwt.return () ;; let send_simple_email _ () = let email = Sihl_email.create ~recipient:"[email protected]" ~sender:"[email protected]" ~subject:"test" ~html:"some html" "some text" in let%lwt () = EmailService.send email in let sent_email = EmailService.inbox () |> List.hd in Alcotest.( check string "has recipient" "[email protected]" sent_email.recipient); Alcotest.(check string "has subject" "test" sent_email.subject); Alcotest.( check (option string) "has html" (Some "some html") sent_email.html); Alcotest.(check string "has text" "some text" sent_email.text); Lwt.return () ;; let send_inline_templated_email _ () = let%lwt () = Sihl.Cleaner.clean_all () in let raw_email = Sihl.Contract.Email.create ~recipient:"[email protected]" ~sender:"[email protected]" ~subject:"test" ~html:"<html>hello {name}, you have signed in {number} of times!</html>" "hello {name}, you have signed in {number} of times!" in let email = Sihl_email.Template.render_email_with_data [ "name", "walter"; "number", "8" ] raw_email in let%lwt () = EmailService.send email in let sent_email = EmailService.inbox () |> List.hd in let html_rendered = "<html>hello walter, you have signed in 8 of times!</html>" in let text_rendered = "hello walter, you have signed in 8 of times!" in Alcotest.( check (option string) "has html" (Some html_rendered) sent_email.html); Alcotest.(check string "has text" text_rendered sent_email.text); Lwt.return () ;; let send_templated_email _ () = let%lwt () = Sihl.Cleaner.clean_all () in let%lwt template = EmailTemplateService.create ~label:"some template" ~html:"<html>hello {name}, you have signed in {number} of times!</html>" "hello {name}, you have signed in {number} of times!" in let email = Sihl_email.Template.create_email_of_template ~sender:"[email protected]" ~recipient:"[email protected]" ~subject:"test" template [ "name", "walter"; "number", "8" ] in let%lwt () = EmailService.send email in let sent_email = EmailService.inbox () |> List.hd in let html_rendered = "<html>hello walter, you have signed in 8 of times!</html>" in let text_rendered = "hello walter, you have signed in 8 of times!" in Alcotest.( check (option string) "has html" (Some html_rendered) sent_email.html); Alcotest.(check string "has text" text_rendered sent_email.text); Lwt.return () ;; let suite = [ ( "email" , [ test_case "create email template" `Quick create_template ; test_case "create email template with language" `Quick create_template ; test_case "update email template" `Quick update_template ; test_case "get email template by label and language" `Quick get_template_by_label_and_language ; test_case "send simple email" `Quick send_simple_email ; test_case "send inline templated email" `Quick send_inline_templated_email ; test_case "send templated email" `Quick send_templated_email ] ) ] ;; end
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl-email/test/email_mariadb.ml
let services = [ Sihl.Database.Migration.MariaDb.register [] ; Sihl_email.Template.MariaDb.register () ; Sihl_email.Smtp.register () ] ;; module Test = Email.Make (Sihl_email.Smtp) (Sihl_email.Template.MariaDb) let () = Sihl.Configuration.read_string "DATABASE_URL_TEST_MARIADB" |> Option.value ~default:"mariadb://admin:[email protected]:3306/dev" |> Unix.putenv "DATABASE_URL"; Unix.putenv "SIHL_ENV" "test"; Logs.set_level (Sihl.Log.get_log_level ()); Logs.set_reporter (Sihl.Log.cli_reporter ()); Lwt_main.run (let%lwt _ = Sihl.Container.start_services services in let%lwt () = Sihl.Database.Migration.MariaDb.run_all () in Alcotest_lwt.run "mariadb" Test.suite) ;;
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl-email/test/email_postgresql.ml
let services = [ Sihl.Database.Migration.PostgreSql.register [] ; Sihl_email.Template.PostgreSql.register () ; Sihl_email.Smtp.register () ] ;; module Test = Email.Make (Sihl_email.Smtp) (Sihl_email.Template.PostgreSql) let () = Sihl.Configuration.read_string "DATABASE_URL_TEST_POSTGRESQL" |> Option.value ~default:"postgres://admin:[email protected]:5432/dev" |> Unix.putenv "DATABASE_URL"; Unix.putenv "SIHL_ENV" "test"; Logs.set_level (Sihl.Log.get_log_level ()); Logs.set_reporter (Sihl.Log.cli_reporter ()); Lwt_main.run (let%lwt _ = Sihl.Container.start_services services in let%lwt () = Sihl.Database.Migration.PostgreSql.run_all () in Alcotest_lwt.run "postgresql" Test.suite) ;;
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl-email/test/template.ml
let test_email_rendering_simple () = let data = [ "foo", "bar" ] in let actual, _ = Sihl_email.Template.render data "{foo}" None in Alcotest.(check string) "Renders template" "bar" actual; let data = [ "foo", "hey"; "bar", "ho" ] in let actual, _ = Sihl_email.Template.render data "{foo} {bar}" None in Alcotest.(check string) "Renders template" "hey ho" actual ;; let test_email_rendering_complex () = let data = [ "foo", "hey"; "bar", "ho" ] in let actual, _ = Sihl_email.Template.render data "{foo} {bar}{foo}" None in Alcotest.(check string) "Renders template" "hey hohey" actual ;; let suite = Alcotest. [ ( "email" , [ test_case "render simple" `Quick test_email_rendering_simple ; test_case "render complex" `Quick test_email_rendering_complex ] ) ] ;; let () = Unix.putenv "SIHL_ENV" "test"; Alcotest.run "template" suite ;;
sihl-email
3.0.5
Unknown
Unknown
Unknown
opam
sihl-3.0.5/sihl-queue.opam
# This file is generated by dune, edit dune-project instead opam-version: "2.0" version: "3.0.5" synopsis: "Queue service implementations for Sihl" description: "Modules for running tasks in the background on a persistent queue." maintainer: ["[email protected]"] authors: ["Josef Erben" "Aron Erben" "Miko Nieminen"] license: "MIT" homepage: "https://github.com/oxidizing/sihl" doc: "https://oxidizing.github.io/sihl/" bug-reports: "https://github.com/oxidizing/sihl/issues" depends: [ "dune" {>= "2.7"} "ocaml" {>= "4.08.0"} "sihl" {= version} "tyxml-ppx" {>= "4.4.0"} "alcotest-lwt" {>= "1.4.0" & with-test} "caqti-driver-postgresql" {>= "1.8.0" & with-test} "caqti-driver-mariadb" {>= "1.8.0" & with-test} "odoc" {with-doc} ] build: [ ["dune" "subst"] {dev} [ "dune" "build" "-p" name "-j" jobs "@install" "@runtest" {with-test} "@doc" {with-doc} ] ] dev-repo: "git+https://github.com/oxidizing/sihl.git"
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl-queue/src/admin_ui.ml
open Tyxml let cancel scope csrf id = let path = Format.sprintf "%s/%s/cancel" scope id in [%html {| <form style="display: inline;" action="|} path {|" method="Post"> <input type="hidden" name="csrf" value="|} csrf {|"> <input type="hidden" id="|} id {|"> <button type="submit" class="sihl-admin-ui-table-row-cancel sihl-admin-ui-queue-table-row-cancel sihl-admin-ui-queue-table-button">Cancel</button> </form> |}] ;; let requeue scope csrf id = let path = Format.sprintf "%s/%s/requeue" scope id in [%html {| <form style="display: inline;" action="|} path {|" method="Post"> <input type="hidden" name="csrf" value="|} csrf {|"> <input type="hidden" id="|} id {|"> <button type="submit" class="sihl-admin-ui-table-row-requeue sihl-admin-ui-queue-table-row-requeue sihl-admin-ui-queue-table-button">Re-queue</button> </form> |}] ;; let status ?prefix scope csrf (job : Sihl.Contract.Queue.instance) = let scope = Format.asprintf "%s%s" scope (Option.value ~default:"" prefix) in let now = Ptime_clock.now () in match job.status with | Sihl.Contract.Queue.Succeeded -> [%html {|<div><span class="sihl-admin-ui-table-row-success sihl-admin-ui-queue-table-row-success">Succeeded</span>|} [ requeue scope csrf job.id ] {|</div>|}] | Sihl.Contract.Queue.Failed -> [%html {|<div><span class="sihl-admin-ui-table-row-failed sihl-admin-ui-queue-table-row-failed">Failed</span>|} [ requeue scope csrf job.id ] {|</div>|}] | Sihl.Contract.Queue.Cancelled -> [%html {|<div><span class="sihl-admin-ui-table-row-failed sihl-admin-ui-queue-table-row-failed">Cancelled</span>|} [ requeue scope csrf job.id ] {|</div>|}] | Sihl.Contract.Queue.Pending -> let next_try_in = if Ptime.is_earlier now ~than:job.next_run_at then Some (Ptime.Span.round ~frac_s:0 (Ptime.Span.sub (Ptime.to_span job.next_run_at) (Ptime.to_span now))) else None in let next_try_in = next_try_in |> Option.map (Format.asprintf "%a" Ptime.Span.pp) |> Option.value ~default:"0s" |> Format.sprintf "Next try in: %s" in [%html {|<div><span class="sihl-admin-ui-table-row-pending sihl-admin-ui-queue-table-row-pending">|} [ Html.txt next_try_in ] {|</span>|} [ cancel scope csrf job.id ] {|</div>|}] ;; let pre_style = {| white-space: pre-wrap; white-space: -moz-pre-wrap; white-space: -pre-wrap; white-space: -o-pre-wrap; word-wrap: break-word; |} ;; let row ?prefix scope csrf (job : Sihl.Contract.Queue.instance) = let last_error_at = job.last_error_at |> Option.map Ptime.to_rfc3339 |> Option.value ~default:"Never" in let status_class = match job.status with | Sihl.Contract.Queue.Succeeded -> "succeeded" | Sihl.Contract.Queue.Failed -> "failed" | Sihl.Contract.Queue.Cancelled -> "cancelled" | Sihl.Contract.Queue.Pending -> "pending" in let classes = [ "sihl-admin-ui-table-body-row" ; "sihl-admin-ui-queue-table-body-row" ; Format.asprintf "sihl-admin-ui-queue-table-body-row-status-%s" status_class ] in let input = if String.equal job.input "" then [%html {|<td class="sihl-admin-ui-table-body-cell sihl-admin-ui-queue-table-body-cell">|} [ Html.txt "" ] {| </td>|}] else [%html {|<td class="sihl-admin-ui-table-body-cell sihl-admin-ui-queue-table-body-cell"><pre style="|} pre_style {|">|} [ Html.txt job.input ] {|</pre></td>|}] in [%html {| <tr class="|} classes {|"> <td class="sihl-admin-ui-table-body-cell sihl-admin-ui-queue-table-body-cell">|} [ Html.txt job.id ] {|</td> <td class="sihl-admin-ui-table-body-cell sihl-admin-ui-queue-table-body-cell">|} [ Html.txt job.name ] {|</td>|} [ input ] {|<td class="sihl-admin-ui-table-body-cell sihl-admin-ui-queue-table-body-cell">|} [ Html.txt (Format.sprintf "%d/%d" job.tries job.max_tries) ] {|</td> <td class="sihl-admin-ui-table-body-cell sihl-admin-ui-queue-table-body-cell"><pre style="|} pre_style {|">|} [ Html.txt (Option.value ~default:"" job.last_error) ] {|</pre> </td> <td class="sihl-admin-ui-table-body-cell sihl-admin-ui-queue-table-body-cell">|} [ Html.txt last_error_at ] {| </td> <td class="sihl-admin-ui-table-body-cell sihl-admin-ui-queue-table-body-cell">|} [ status ?prefix scope csrf job ] {|</td> </tr> |}] ;; let table ?prefix scope csrf (jobs : Sihl.Contract.Queue.instance list) = let path = Format.sprintf "%s/html/index" scope in [%html {| <table data-hx-get="|} path {|" data-hx-trigger="every 5s" data-hx-swap="outerHTML" class="sihl-admin-ui-table sihl-admin-ui-queue-table"> <thead class="sihl-admin-ui-table-header sihl-admin-ui-queue-table-header"> <tr class="sihl-admin-ui-table-header-row sihl-admin-ui-queue-table-header-row"> <th class="sihl-admin-ui-table-header-cell sihl-admin-ui-queue-table-header-cell">ID</th> <th class="sihl-admin-ui-table-header-cell sihl-admin-ui-queue-table-header-cell">Job type</th> <th class="sihl-admin-ui-table-header-cell sihl-admin-ui-queue-table-header-cell">Input</th> <th class="sihl-admin-ui-table-header-cell sihl-admin-ui-queue-table-header-cell">Tries</th> <th class="sihl-admin-ui-table-header-cell sihl-admin-ui-queue-table-header-cell">Last error</th> <th class="sihl-admin-ui-table-header-cell sihl-admin-ui-queue-table-header-cell">Last error at</th> <th class="sihl-admin-ui-table-header-cell sihl-admin-ui-queue-table-header-cell">Status</th> </tr> </thead> <tbody class="sihl-admin-ui-table-body sihl-admin-ui-queue-table-body"> |} (List.map (row ?prefix scope csrf) jobs) {| </tbody> </table> |}] ;; let base = [%html {| body { font-family: sans-serif; } .sihl-admin-ui-queue-back { text-decoration: none; font-size: 1.5rem; } .sihl-admin-ui-table { width: 100%; border-collapse: collapse; margin-top: 10px; } .sihl-admin-ui-table-header-cell, .sihl-admin-ui-table-body-cell { text-align: left; padding: 12px 15px; } .sihl-admin-ui-queue-table-button { cursor: pointer; margin-top: 5px; padding: 5px 10px; border-radius: 0.2em; text-decoration: none; text-align: center; -webkit-transition: all 0.2s; -o-transition: all 0.2s; transition: all 0.2s; } |}] ;; let light = [%html {| .sihl-admin-ui-table-header-cell, .sihl-admin-ui-table-body-cell { border: 1px solid black; } .sihl-admin-ui-queue-table-header { background-color: #DDDDDD; } .sihl-admin-ui-queue-table-body-row-status-failed { background-color: #FFCCCC; } .sihl-admin-ui-queue-table-body-row-status-succeeded { background-color: #CCFFCC; } .sihl-admin-ui-queue-table-button { border: 1px solid black; } .sihl-admin-ui-queue-table-button:hover{ color: #FFFFFF; background-color: #777777; } |}] ;; let dark = [%html {| body { background-color: #282828; } .sihl-admin-ui-queue-back { color: white; } .sihl-admin-ui-table-header-cell, .sihl-admin-ui-table-body-cell { border: 1px solid #282828; color: #D8D8D8; } .sihl-admin-ui-queue-table-header { background-color: #404040; } .sihl-admin-ui-queue-table-body-row-status-failed { background-color: #5d3030; } .sihl-admin-ui-queue-table-body-row-status-succeeded { background-color: #305430; } .sihl-admin-ui-queue-table-button { border: 1px solid #282828; background-color: #282828; color: white; } .sihl-admin-ui-queue-table-button:hover{ color: black; background-color: #EEEEEE; } |}] ;; let page ?back ?theme body = let body = match back with | Some back -> let back_button = [%html {|<a href="|} back {|" class="sihl-admin-ui-back sihl-admin-ui-queue-back">← Go back</a>|}] in List.cons back_button body | None -> body in let body = match theme with | Some `Light -> let theme = [%html {|<style>|} [ base; light ] {|</style>|}] in List.concat [ body; [ theme ] ] | Some `Dark -> let theme = [%html {|<style>|} [ base; dark ] {|</style>|}] in List.concat [ body; [ theme ] ] | Some (`Custom _) -> body | None -> let theme = [%html {|<style>|} [ base; light ] {|</style>|}] in List.concat [ body; [ theme ] ] in let body = match Sihl.Configuration.read_string "HTMX_SCRIPT_URL" with | Some htmx -> let htmx_script = [%html {|<script src="|} htmx {|"></script>|}] in List.concat [ body; [ htmx_script ] ] | None -> body in match theme with | Some (`Custom url) -> [%html {| <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"/> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="|} url {|" rel="stylesheet"> <title>Queue Dashboard</title> </head> <body>|} body {| </body> </html> |}] | _ -> [%html {| <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"/> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Queue Dashboard</title> </head> <body>|} body {| </body> </html> |}] ;; let index ?prefix ?back ?theme scope find_jobs = Sihl.Web.get "" (fun req -> let csrf = match Sihl.Web.Csrf.find req with | Some csrf -> csrf | None -> failwith "No CSRF token found" in let%lwt jobs = find_jobs () in Lwt.return @@ Sihl.Web.Response.of_html (page ?back ?theme [ table ?prefix scope csrf jobs ])) ;; let html_index scope find_jobs = Sihl.Web.get "/html/index" (fun req -> let csrf = match Sihl.Web.Csrf.find req with | Some csrf -> csrf | None -> failwith "No CSRF token found" in let%lwt jobs = find_jobs () in let html = Format.asprintf "%a" Tyxml.Html._pp_elt (table scope csrf jobs) in Lwt.return @@ Sihl.Web.Response.of_plain_text html) ;; let cancel scope find_job cancel_job = Sihl.Web.post "/:id/cancel" (fun req -> let id = Sihl.Web.Router.param req "id" in let%lwt job = find_job id in let%lwt _ = cancel_job job in Lwt.return @@ Sihl.Web.Response.redirect_to scope) ;; let requeue scope find_job requeue_job = Sihl.Web.post "/:id/requeue" (fun req -> let id = Sihl.Web.Router.param req "id" in let%lwt job = find_job id in let%lwt _ = requeue_job job in Lwt.return @@ Sihl.Web.Response.redirect_to scope) ;; let middlewares = [ Opium.Middleware.content_length ; Opium.Middleware.etag ; Sihl.Web.Middleware.csrf () ; Sihl.Web.Middleware.flash () ] ;; let router search_jobs find_job cancel_job requeue_job ?back ?theme ?prefix scope = Sihl.Web.choose ~middlewares ~scope [ index ?prefix ?back ?theme scope search_jobs ; html_index scope search_jobs ; cancel scope find_job cancel_job ; requeue scope find_job requeue_job ] ;;
sihl-email
3.0.5
Unknown
Unknown
Unknown
dune
sihl-3.0.5/sihl-queue/src/dune
(library (name sihl_queue) (public_name sihl-queue) (libraries sihl) (preprocess (pps tyxml-ppx lwt_ppx))) (documentation (package sihl-queue))
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl-queue/src/repo.ml
module Map = Map.Make (String) module type Sig = sig val lifecycles : Sihl.Container.lifecycle list val register_migration : unit -> unit val register_cleaner : unit -> unit val enqueue : ?ctx:(string * string) list -> Sihl.Contract.Queue.instance -> unit Lwt.t val enqueue_all : ?ctx:(string * string) list -> Sihl.Contract.Queue.instance list -> unit Lwt.t val find_workable : ?ctx:(string * string) list -> unit -> Sihl.Contract.Queue.instance list Lwt.t val find : ?ctx:(string * string) list -> string -> Sihl.Contract.Queue.instance option Lwt.t val query : ?ctx:(string * string) list -> unit -> Sihl.Contract.Queue.instance list Lwt.t val update : ?ctx:(string * string) list -> Sihl.Contract.Queue.instance -> unit Lwt.t val delete : ?ctx:(string * string) list -> Sihl.Contract.Queue.instance -> unit Lwt.t end module InMemory : Sig = Repo_inmemory module MariaDb : Sig = Repo_sql.MakeMariaDb (Sihl.Database.Migration.MariaDb) module PostgreSql : Sig = Repo_sql.MakePostgreSql (Sihl.Database.Migration.PostgreSql)
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl-queue/src/repo_inmemory.ml
module Map = Map.Make (String) let lifecycles = [] let state = ref Map.empty let ordered_ids = ref [] let register_cleaner () = let cleaner ?ctx:_ _ = state := Map.empty; ordered_ids := []; Lwt.return () in Sihl.Cleaner.register_cleaner cleaner ;; let register_migration () = () let enqueue ?ctx:_ job_instance = let open Sihl.Contract.Queue in let id = job_instance.id in ordered_ids := List.cons id !ordered_ids; state := Map.add id job_instance !state; Lwt.return () ;; let enqueue_all ?ctx:_ job_instances = job_instances |> List.fold_left (fun res job -> Lwt.bind res (fun _ -> enqueue job)) (Lwt.return ()) ;; let update ?ctx:_ job_instance = let open Sihl.Contract.Queue in let id = job_instance.id in state := Map.add id job_instance !state; Lwt.return () ;; let find_workable ?ctx:_ () = let all_job_instances = List.map (fun id -> Map.find_opt id !state) !ordered_ids in let now = Ptime_clock.now () in let rec filter_pending all_job_instances result = match all_job_instances with | Some job_instance :: job_instances -> if Sihl.Contract.Queue.should_run job_instance now then filter_pending job_instances (List.cons job_instance result) else filter_pending job_instances result | None :: job_instances -> filter_pending job_instances result | [] -> result in Lwt.return @@ filter_pending all_job_instances [] ;; let query ?ctx:_ () = Lwt.return @@ List.map (fun id -> Map.find id !state) !ordered_ids ;; let find ?ctx:_ id = Lwt.return @@ Map.find_opt id !state let delete ?ctx:_ (job : Sihl.Contract.Queue.instance) = state := Map.remove job.id !state; Lwt.return () ;;
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl-queue/src/repo_sql.ml
module Map = Map.Make (String) let status = let open Sihl.Contract.Queue in let to_string = function | Pending -> "pending" | Succeeded -> "succeeded" | Failed -> "failed" | Cancelled -> "cancelled" in let of_string str = match str with | "pending" -> Ok Pending | "succeeded" -> Ok Succeeded | "failed" -> Ok Failed | "cancelled" -> Ok Cancelled | _ -> Error (Printf.sprintf "Unexpected job status %s found" str) in let encode m = Ok (to_string m) in let decode = of_string in Caqti_type.(custom ~encode ~decode string) ;; let job = let open Sihl.Contract.Queue in let encode m = Ok ( m.id , ( m.name , ( m.input , ( m.tries , ( m.next_run_at , (m.max_tries, (m.status, (m.last_error, m.last_error_at))) ) ) ) ) ) in let decode ( id , ( name , ( input , ( tries , (next_run_at, (max_tries, (status, (last_error, last_error_at)))) ) ) ) ) = Ok { id ; name ; input ; tries ; next_run_at ; max_tries ; status ; last_error ; last_error_at } in Caqti_type.( custom ~encode ~decode (tup2 string (tup2 string (tup2 string (tup2 int (tup2 ptime (tup2 int (tup2 status (tup2 (option string) (option ptime)))))))))) ;; module MakeMariaDb (MigrationService : Sihl.Contract.Migration.Sig) = struct let lifecycles = [ Sihl.Database.lifecycle; MigrationService.lifecycle ] let enqueue_request = let open Caqti_request.Infix in {sql| INSERT INTO queue_jobs ( uuid, name, input, tries, next_run_at, max_tries, status, last_error, last_error_at ) VALUES ( UNHEX(REPLACE($1, '-', '')), $2, $3, $4, $5, $6, $7, $8, $9 ) |sql} |> job ->. Caqti_type.unit ;; let enqueue ?ctx job_instance = Sihl.Database.exec ?ctx enqueue_request job_instance ;; (* MariaDB expects uuid to be bytes, since we can't unhex when using caqti's populate, we have to do that manually. *) let populatable job_instances = job_instances |> List.map (fun j -> Sihl.Contract.Queue. { j with id = (match j.id |> Uuidm.of_string with | Some uuid -> Uuidm.to_bytes uuid | None -> failwith "Invalid uuid provided") }) ;; let enqueue_all ?ctx job_instances = Sihl.Database.transaction' ?ctx (fun connection -> let module Connection = (val connection : Caqti_lwt.CONNECTION) in Connection.populate ~table:"queue_jobs" ~columns: [ "uuid" ; "name" ; "input" ; "tries" ; "next_run_at" ; "max_tries" ; "status" ; "last_error" ; "last_error_at" ] job (job_instances |> populatable |> List.rev |> Caqti_lwt.Stream.of_list) |> Lwt.map Caqti_error.uncongested) ;; let update_request = let open Caqti_request.Infix in {sql| UPDATE queue_jobs SET name = $2, input = $3, tries = $4, next_run_at = $5, max_tries = $6, status = $7, last_error = $8, last_error_at = $9 WHERE queue_jobs.uuid = UNHEX(REPLACE($1, '-', '')) |sql} |> job ->. Caqti_type.unit ;; let update ?ctx job_instance = Sihl.Database.exec ?ctx update_request job_instance ;; let find_workable_request = let open Caqti_request.Infix in {sql| SELECT LOWER(CONCAT( SUBSTR(HEX(uuid), 1, 8), '-', SUBSTR(HEX(uuid), 9, 4), '-', SUBSTR(HEX(uuid), 13, 4), '-', SUBSTR(HEX(uuid), 17, 4), '-', SUBSTR(HEX(uuid), 21) )), name, input, tries, next_run_at, max_tries, status, last_error, last_error_at FROM queue_jobs WHERE status = "pending" AND next_run_at <= NOW() AND tries < max_tries ORDER BY id DESC |sql} |> Caqti_type.unit ->* job ;; let find_workable ?ctx () = Sihl.Database.collect ?ctx find_workable_request () ;; let query = let open Caqti_request.Infix in {sql| SELECT LOWER(CONCAT( SUBSTR(HEX(uuid), 1, 8), '-', SUBSTR(HEX(uuid), 9, 4), '-', SUBSTR(HEX(uuid), 13, 4), '-', SUBSTR(HEX(uuid), 17, 4), '-', SUBSTR(HEX(uuid), 21) )), name, input, tries, next_run_at, max_tries, status, last_error, last_error_at FROM queue_jobs ORDER BY next_run_at DESC LIMIT 100 |sql} |> Caqti_type.unit ->* job ;; let query ?ctx () = Sihl.Database.collect ?ctx query () let find_request = let open Caqti_request.Infix in {sql| SELECT LOWER(CONCAT( SUBSTR(HEX(uuid), 1, 8), '-', SUBSTR(HEX(uuid), 9, 4), '-', SUBSTR(HEX(uuid), 13, 4), '-', SUBSTR(HEX(uuid), 17, 4), '-', SUBSTR(HEX(uuid), 21) )), name, input, tries, next_run_at, max_tries, status, last_error, last_error_at FROM queue_jobs WHERE uuid = UNHEX(REPLACE(?, '-', '')) |sql} |> Caqti_type.string ->? job ;; let find ?ctx id = Sihl.Database.find_opt ?ctx find_request id let delete_request = let open Caqti_request.Infix in {sql| DELETE FROM job_queues WHERE uuid = UNHEX(REPLACE(?, '-', '')) |sql} |> Caqti_type.(string ->. unit) ;; let delete ?ctx (job : Sihl.Contract.Queue.instance) = Sihl.Database.exec ?ctx delete_request job.id ;; let clean_request = let open Caqti_request.Infix in "TRUNCATE TABLE queue_jobs" |> Caqti_type.(unit ->. unit) ;; let clean ?ctx () = Sihl.Database.exec ?ctx clean_request () module Migration = struct let fix_collation = Sihl.Database.Migration.create_step ~label:"fix collation" {sql| SET collation_server = 'utf8mb4_unicode_ci' |sql} ;; let create_jobs_table = Sihl.Database.Migration.create_step ~label:"create jobs table" {sql| CREATE TABLE IF NOT EXISTS queue_jobs ( id BIGINT UNSIGNED AUTO_INCREMENT, uuid BINARY(16) NOT NULL, name VARCHAR(128) NOT NULL, input TEXT NULL, tries BIGINT UNSIGNED, next_run_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, max_tries BIGINT UNSIGNED, status VARCHAR(128) NOT NULL, PRIMARY KEY (id), CONSTRAINT unique_uuid UNIQUE KEY (uuid) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci |sql} ;; let set_null_input_to_empty_string = Sihl.Database.Migration.create_step ~label:"set input to not null" {sql| UPDATE queue_jobs SET input = '' WHERE input IS NULL |sql} ;; let set_input_not_null = Sihl.Database.Migration.create_step ~label:"set input to not null" {sql| ALTER TABLE queue_jobs MODIFY COLUMN input TEXT NOT NULL DEFAULT '' |sql} ;; let add_error_columns = Sihl.Database.Migration.create_step ~label:"add error columns" {sql| ALTER TABLE queue_jobs ADD COLUMN last_error TEXT, ADD COLUMN last_error_at TIMESTAMP |sql} ;; let migration = Sihl.Database.Migration.( empty "queue" |> add_step fix_collation |> add_step create_jobs_table |> add_step set_null_input_to_empty_string |> add_step set_input_not_null |> add_step add_error_columns) ;; end let register_cleaner () = Sihl.Cleaner.register_cleaner clean let register_migration () = MigrationService.register_migration Migration.migration ;; end module MakePostgreSql (MigrationService : Sihl.Contract.Migration.Sig) = struct let lifecycles = [ Sihl.Database.lifecycle; MigrationService.lifecycle ] let enqueue_request = let open Caqti_request.Infix in {sql| INSERT INTO queue_jobs ( uuid, name, input, tries, next_run_at, max_tries, status, last_error, last_error_at ) VALUES ( $1::uuid, $2, $3, $4, $5 AT TIME ZONE 'UTC', $6, $7, $8, $9 AT TIME ZONE 'UTC' ) |sql} |> job ->. Caqti_type.unit ;; let enqueue ?ctx job_instance = Sihl.Database.exec ?ctx enqueue_request job_instance ;; let enqueue_all ?ctx job_instances = Sihl.Database.transaction' ?ctx (fun connection -> let module Connection = (val connection : Caqti_lwt.CONNECTION) in Connection.populate ~table:"queue_jobs" ~columns: [ "uuid" ; "name" ; "input" ; "tries" ; "next_run_at" ; "max_tries" ; "status" ; "last_error" ; "last_error_at" ] job (Caqti_lwt.Stream.of_list (List.rev job_instances)) |> Lwt.map Caqti_error.uncongested) ;; let update_request = let open Caqti_request.Infix in {sql| UPDATE queue_jobs SET name = $2, input = $3, tries = $4, next_run_at = $5 AT TIME ZONE 'UTC', max_tries = $6, status = $7, last_error = $8, last_error_at = $9 AT TIME ZONE 'UTC' WHERE queue_jobs.uuid = $1::uuid |sql} |> job ->. Caqti_type.unit ;; let update ?ctx job_instance = Sihl.Database.exec ?ctx update_request job_instance ;; let find_workable_request = let open Caqti_request.Infix in {sql| SELECT uuid, name, input, tries, next_run_at, max_tries, status, last_error, last_error_at FROM queue_jobs WHERE status = 'pending' AND next_run_at <= NOW() AND tries < max_tries ORDER BY id DESC |sql} |> Caqti_type.unit ->* job ;; let find_workable ?ctx () = Sihl.Database.collect ?ctx find_workable_request () ;; let query = let open Caqti_request.Infix in {sql| SELECT uuid, name, input, tries, next_run_at, max_tries, status, last_error, last_error_at FROM queue_jobs ORDER BY next_run_at DESC |sql} |> Caqti_type.unit ->* job ;; let query ?ctx () = Sihl.Database.collect ?ctx query () let find_request = let open Caqti_request.Infix in {sql| SELECT uuid, name, input, tries, next_run_at, max_tries, status, last_error, last_error_at FROM queue_jobs WHERE uuid = $1::uuid |sql} |> Caqti_type.string ->? job ;; let find ?ctx id = Sihl.Database.find_opt ?ctx find_request id let delete_request = let open Caqti_request.Infix in {sql| DELETE FROM job_queues WHERE uuid = $1::uuid |sql} |> Caqti_type.(string ->. unit) ;; let delete ?ctx (job : Sihl.Contract.Queue.instance) = Sihl.Database.exec ?ctx delete_request job.id ;; let clean_request = let open Caqti_request.Infix in "TRUNCATE TABLE queue_jobs" |> Caqti_type.(unit ->. unit) ;; let clean ?ctx () = Sihl.Database.exec ?ctx clean_request () module Migration = struct let create_jobs_table = Sihl.Database.Migration.create_step ~label:"create jobs table" {sql| CREATE TABLE IF NOT EXISTS queue_jobs ( id serial, uuid uuid NOT NULL, name VARCHAR(128) NOT NULL, input TEXT NULL, tries BIGINT, next_run_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, max_tries BIGINT, status VARCHAR(128) NOT NULL, PRIMARY KEY (id), UNIQUE (uuid) ) |sql} ;; let set_null_input_to_empty_string = Sihl.Database.Migration.create_step ~label:"set input to not null" {sql| UPDATE queue_jobs SET input = '' WHERE input IS NULL |sql} ;; let set_input_not_null = Sihl.Database.Migration.create_step ~label:"set input to not null" {sql| ALTER TABLE queue_jobs ALTER COLUMN input SET DEFAULT '', ALTER COLUMN input SET NOT NULL |sql} ;; let add_error_columns = Sihl.Database.Migration.create_step ~label:"add error columns" {sql| ALTER TABLE queue_jobs ADD COLUMN last_error TEXT NULL, ADD COLUMN last_error_at TIMESTAMP WITH TIME ZONE |sql} ;; let remove_timezone = Sihl.Database.Migration.create_step ~label:"remove timezone info from timestamps" {sql| ALTER TABLE queue_jobs ALTER COLUMN next_run_at TYPE TIMESTAMP, ALTER COLUMN last_error_at TYPE TIMESTAMP |sql} ;; let migration = Sihl.Database.Migration.( empty "queue" |> add_step create_jobs_table |> add_step set_null_input_to_empty_string |> add_step set_input_not_null |> add_step add_error_columns |> add_step remove_timezone) ;; end let register_cleaner () = Sihl.Cleaner.register_cleaner clean let register_migration () = MigrationService.register_migration Migration.migration ;; end
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl-queue/src/sihl_queue.ml
include Sihl.Contract.Queue let log_src = Logs.Src.create ("sihl.service." ^ Sihl.Contract.Queue.name) module Logs = (val Logs.src_log log_src : Logs.LOG) let create_instance input delay now (job : 'a job) = let input = job.encode input in let name = job.name in let next_run_at = match delay with | Some delay -> Option.value (Ptime.add_span now delay) ~default:now | None -> now in let max_tries = job.max_tries in { id = Uuidm.v `V4 |> Uuidm.to_string ; name ; input ; tries = 0 ; next_run_at ; max_tries ; status = Pending ; last_error = None ; last_error_at = None } ;; let update_next_run_at (retry_delay : Ptime.Span.t) (job_instance : instance) = let next_run_at = match Ptime.add_span job_instance.next_run_at retry_delay with | Some date -> date | None -> failwith "Can not determine next run date of job" in { job_instance with next_run_at } ;; let incr_tries job_instance = { job_instance with tries = job_instance.tries + 1 } ;; module Make (Repo : Repo.Sig) : Sihl.Contract.Queue.Sig = struct type config = { force_async : bool option } let config force_async = { force_async } let schema = let open Conformist in make [ optional (bool ~meta:"If set to true, the queue is used even in development." ~default:false "QUEUE_FORCE_ASYNC") ] config ;; let registered_jobs : job' list ref = ref [] let stop_schedule : (unit -> unit) option ref = ref None let dispatch ?ctx ?delay input (job : 'a job) = let open Sihl.Contract.Queue in let config = Sihl.Configuration.read schema in let force_async = Option.value ~default:false config.force_async in if Sihl.Configuration.is_production () || force_async then ( let name = job.name in Logs.debug (fun m -> m "Dispatching job %s" name); let now = Ptime_clock.now () in let job_instance = create_instance input delay now job in Repo.enqueue ?ctx job_instance) else ( Logs.info (fun m -> m "Skipping queue in development environment"); match%lwt job.handle input with | Ok () -> Lwt.return () | Error msg -> Logs.err (fun m -> m "Error while processing job '%s': %s" name msg); Lwt.return ()) ;; let dispatch_all ?ctx ?delay inputs job = let config = Sihl.Configuration.read schema in let force_async = Option.value ~default:false config.force_async in if Sihl.Configuration.is_production () || force_async then ( let now = Ptime_clock.now () in let job_instances = List.map (fun input -> create_instance input delay now job) inputs in Repo.enqueue_all ?ctx job_instances) else ( Logs.info (fun m -> m "Skipping queue in development environment"); let rec loop inputs = match inputs with | input :: inputs -> Lwt.bind (job.handle input) (function | Ok () -> loop inputs | Error msg -> Logs.err (fun m -> m "Error while processing job '%s': %s" job.name msg); loop inputs) | [] -> Lwt.return () in loop inputs) ;; let run_job (input : string) (job : job') (job_instance : instance) : (unit, string) Result.t Lwt.t = let job_instance_id = job_instance.id in let%lwt result = Lwt.catch (fun () -> job.handle input) (fun exn -> let exn_string = Printexc.to_string exn in Logs.err (fun m -> m "Exception caught while running job, this is a bug in your job \ handler. Don't throw exceptions there, use Result.t instead. \ '%s'" exn_string); Lwt.return @@ Error exn_string) in match result with | Error msg -> Logs.err (fun m -> m "Failure while running job instance %a %s" pp_instance job_instance msg); Lwt.catch (fun () -> let%lwt () = job.failed msg job_instance in Lwt.return @@ Error msg) (fun exn -> let exn_string = Printexc.to_string exn in Logs.err (fun m -> m "Exception caught while cleaning up job, this is a bug in your \ job failure handler, make sure to not throw exceptions there \ '%s" exn_string); Lwt.return @@ Error exn_string) | Ok () -> Logs.debug (fun m -> m "Successfully ran job instance '%s'" job_instance_id); Lwt.return @@ Ok () ;; let update ~job_instance = Repo.update job_instance let work_job (job : job') (job_instance : instance) = let now = Ptime_clock.now () in if should_run job_instance now then ( let input_string = job_instance.input in let%lwt job_run_status = run_job input_string job job_instance in let job_instance = job_instance |> incr_tries |> update_next_run_at job.retry_delay in let job_instance = match job_run_status with | Error msg -> if job_instance.tries >= job.max_tries then { job_instance with status = Failed ; last_error = Some msg ; last_error_at = Some (Ptime_clock.now ()) } else { job_instance with last_error = Some msg ; last_error_at = Some (Ptime_clock.now ()) } | Ok () -> { job_instance with status = Succeeded } in update ~job_instance) else ( Logs.debug (fun m -> m "Not going to run job instance %a" pp_instance job_instance); Lwt.return ()) ;; let work_queue ~jobs = let%lwt pending_job_instances = Repo.find_workable () in let n_job_instances = List.length pending_job_instances in if n_job_instances > 0 then ( Logs.debug (fun m -> m "Start working queue of length %d" (List.length pending_job_instances)); let rec loop job_instances jobs = match job_instances with | [] -> Lwt.return () | (job_instance : instance) :: job_instances -> let job = List.find_opt (fun job -> job.name |> String.equal job_instance.name) jobs in (match job with | None -> loop job_instances jobs | Some job -> work_job job job_instance) in let%lwt () = loop pending_job_instances jobs in Logs.debug (fun m -> m "Finish working queue"); Lwt.return ()) else Lwt.return () ;; let register_jobs jobs = registered_jobs := List.concat [ !registered_jobs; jobs ]; Lwt.return () ;; let start_queue () = Logs.debug (fun m -> m "Start job queue"); (* This function runs every second, the request context gets created here with each tick *) let scheduled_function () = let jobs = !registered_jobs in if List.length jobs > 0 then ( let job_strings = jobs |> List.map (fun job -> job.name) |> String.concat ", " in Logs.debug (fun m -> m "Run job queue with registered jobs: %s" job_strings); work_queue ~jobs) else ( Logs.debug (fun m -> m "No jobs found to run, trying again later"); Lwt.return ()) in let schedule = Sihl.Schedule.create Sihl.Schedule.every_second scheduled_function "job_queue" in stop_schedule := Some (Sihl.Schedule.schedule schedule); Lwt.return () ;; let start () = Sihl.Configuration.require schema; start_queue () ;; let stop () = registered_jobs := []; match !stop_schedule with | Some stop_schedule -> stop_schedule (); Lwt.return () | None -> Logs.warn (fun m -> m "Can not stop schedule"); Lwt.return () ;; let lifecycle = Sihl.Container.create_lifecycle Sihl.Contract.Queue.name ~dependencies:(fun () -> List.cons Sihl.Schedule.lifecycle Repo.lifecycles) ~start ~stop ;; let register ?(jobs = []) () = Repo.register_migration (); Repo.register_cleaner (); registered_jobs := List.concat [ !registered_jobs; jobs ]; let configuration = Sihl.Configuration.make ~schema () in Sihl.Container.Service.create ~configuration lifecycle ;; let query () : instance list Lwt.t = Repo.query () let find id : instance Lwt.t = let%lwt job = Repo.find id in match job with | Some job -> Lwt.return job | None -> failwith (Format.asprintf "Failed to find with id %s" id) ;; let update (job : instance) : instance Lwt.t = let%lwt () = Repo.update job in let%lwt updated = Repo.find job.id in match updated with | Some job -> Lwt.return job | None -> failwith (Format.asprintf "Failed to update job %a" pp_instance job) ;; let requeue (job : instance) : instance Lwt.t = let status = Pending in let tries = 0 in let next_run_at = Ptime_clock.now () in let updated = { job with status; tries; next_run_at } in update updated ;; let cancel (job : instance) : instance Lwt.t = let status = Cancelled in let updated = { job with status } in update updated ;; let router ?back ?theme scope = Admin_ui.router query find cancel requeue ?back ?theme scope ;; end module InMemory = Make (Repo.InMemory) module MariaDb = Make (Repo.MariaDb) module PostgreSql = Make (Repo.PostgreSql)
sihl-email
3.0.5
Unknown
Unknown
Unknown
mli
sihl-3.0.5/sihl-queue/src/sihl_queue.mli
(** [instance_status] is the status of the job on the queue. *) type instance_status = Sihl.Contract.Queue.instance_status = | Pending | Succeeded | Failed | Cancelled (** [instance] is a queued job with a concrete input. *) type instance = Sihl.Contract.Queue.instance = { id : string ; name : string ; input : string ; tries : int ; next_run_at : Ptime.t ; max_tries : int ; status : instance_status ; last_error : string option ; last_error_at : Ptime.t option } (** ['a job] is a job that can be dispatched where ['a] is the type of the input. *) type 'a job = 'a Sihl.Contract.Queue.job = { name : string ; encode : 'a -> string ; decode : string -> ('a, string) Result.t ; handle : 'a -> (unit, string) Result.t Lwt.t ; failed : string -> instance -> unit Lwt.t ; max_tries : int ; retry_delay : Ptime.Span.t } (** [job'] is a helper type that is used to remove the input type from [job]. Use [job'] to register jobs. *) type job' = Sihl.Contract.Queue.job' = { name : string ; handle : string -> (unit, string) Result.t Lwt.t ; failed : string -> instance -> unit Lwt.t ; max_tries : int ; retry_delay : Ptime.Span.t } (** [hide job] returns a [job'] that can be registered with the queue service. It hides the input type of the job. A [job'] can be registered but not dispatched. *) val hide : 'a job -> job' (** [create_job ?max_tries ?retry_delay ?failed handle encode decode name] returns a job that can be placed on the queue (dispatched) for later processing. [max_tries] is the maximum times a job can fail. If a job fails [max_tries] number of times, the status of the job becomes [Failed]. By default, a job can fail [5] times. [retry_delay] is the time span between two retries. By default, this value is one minute. [failed] is the error handler that is called when [handle] returns an error or raises an exception. By default, this function does nothing. Use [failed] to clean up resources or raise some error in a monitoring system in case a job fails. [handle] is the function that is called with the input when processing the job. If an exception is raised, the exception is turned into [Error]. [encode] is called right after dispatching a job. The provided input data is encoded as string which is used for persisting the queue. [decode] is called before starting to process a job. [decode] turns the persisted string into the input data that is passed to the handle function. [name] is the name of the job, it has to be unique among all registered jobs. *) val create_job : ('a -> (unit, string) result Lwt.t) -> ?max_tries:int -> ?retry_delay:Ptime.span -> ?failed:(string -> instance -> unit Lwt.t) -> ('a -> string) -> (string -> ('a, string) Result.t) -> string -> 'a job val pp_job : (Format.formatter -> 'a -> unit) -> Format.formatter -> 'a job -> unit val pp_job' : Format.formatter -> job' -> unit val pp_instance : Format.formatter -> instance -> unit (** [should_run job now] returns true if the queued [job] should run [now], false if not. If a queued [job] should run it will be processed by any idle worker as soon as possible. *) val should_run : instance -> Ptime.t -> bool val log_src : Logs.src module InMemory : sig (** The in-memory queue is not a persistent queue. If the process goes down, all jobs are lost. It doesn't support locking and the queue is unbounded, use it only for testing! *) include Sihl.Contract.Queue.Sig end module MariaDb : sig (** The MariaDB queue backend supports fully persistent queues and locking. *) include Sihl.Contract.Queue.Sig end module PostgreSql : sig (** The PostgreSQL queue backend supports fully persistent queues and locking. *) include Sihl.Contract.Queue.Sig end
sihl-email
3.0.5
Unknown
Unknown
Unknown
dune
sihl-3.0.5/sihl-queue/test/dune
(executables (names queue_inmemory queue_mariadb queue_postgresql) (libraries sihl sihl-queue alcotest-lwt caqti-driver-mariadb caqti-driver-postgresql) (preprocess (pps ppx_deriving_yojson lwt_ppx)))
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl-queue/test/queue.ml
open Alcotest_lwt let create_instance input delay now (job : 'a Sihl_queue.job) = let open Sihl_queue in let input = job.encode input in let name = job.name in let next_run_at = match delay with | Some delay -> Option.value (Ptime.add_span now delay) ~default:now | None -> now in let max_tries = job.max_tries in { id = Uuidm.v `V4 |> Uuidm.to_string ; name ; input ; tries = 0 ; next_run_at ; max_tries ; status = Pending ; last_error = None ; last_error_at = None } ;; let update_next_run_at (retry_delay : Ptime.Span.t) (job_instance : Sihl_queue.instance) = let open Sihl_queue in let next_run_at = match Ptime.add_span job_instance.next_run_at retry_delay with | Some date -> date | None -> failwith "Can not determine next run date of job" in { job_instance with next_run_at } ;; let incr_tries job_instance = let open Sihl_queue in { job_instance with tries = job_instance.tries + 1 } ;; let should_run_job _ () = Sihl.Configuration.store [ "QUEUE_FORCE_ASYNC", "true" ]; let now = Ptime_clock.now () in let job = Sihl_queue.create_job (fun _ -> Lwt_result.return ()) ~max_tries:3 ~retry_delay:(Sihl.Time.Span.minutes 1) (fun () -> "") (fun _ -> Ok ()) "foo" in let job_instance = create_instance () None now job in let actual = Sihl_queue.should_run job_instance now in Alcotest.(check bool) "pending job should run" true actual; let delay = Some (Sihl.Time.Span.days 1) in let job_instance = create_instance () delay now job in let actual = Sihl_queue.should_run job_instance now in Alcotest.(check bool) "pending job with start_at in the future should not run" false actual; let job_instance = create_instance () None now job |> incr_tries |> incr_tries in let actual = Sihl_queue.should_run job_instance now in Alcotest.(check bool) "pending job with tries < max_tries should not run" true actual; let job_instance = create_instance () None now job |> incr_tries |> incr_tries |> incr_tries in let actual = Sihl_queue.should_run job_instance now in Alcotest.(check bool) "pending job with tries = max_tries should not run" false actual; let job_instance = create_instance () None now job in let job_instance = { job_instance with status = Sihl_queue.Failed } in let actual = Sihl_queue.should_run job_instance now in Alcotest.(check bool) "failed job should not run" false actual; let job_instance = create_instance () None now job in let job_instance = { job_instance with status = Sihl_queue.Succeeded } in let actual = Sihl_queue.should_run job_instance now in Alcotest.(check bool) "succeeded job should not run" false actual; let job_instance = create_instance () None now job |> update_next_run_at job.retry_delay in let actual = Sihl_queue.should_run job_instance now in Alcotest.(check bool) "job that hasn't cooled down should not run" false actual; Lwt.return () ;; module Make (QueueService : Sihl.Contract.Queue.Sig) = struct let dispatched_job_gets_processed _ () = Sihl.Configuration.store [ "QUEUE_FORCE_ASYNC", "true" ]; let has_ran_job = ref false in let%lwt () = Sihl.Container.stop_services [ QueueService.register () ] in let%lwt () = Sihl.Cleaner.clean_all () in let job = Sihl_queue.create_job ~max_tries:3 ~retry_delay:(Sihl.Time.Span.minutes 1) (fun _ -> Lwt_result.return (has_ran_job := true)) (fun () -> "") (fun _ -> Ok ()) "foo" in let service = QueueService.register ~jobs:[ Sihl_queue.hide job ] () in let%lwt _ = Sihl.Container.start_services [ service ] in let%lwt () = QueueService.dispatch () job in let%lwt () = Lwt_unix.sleep 2.0 in let%lwt () = Sihl.Container.stop_services [ service ] in let () = Alcotest.(check bool "has processed job" true !has_ran_job) in Lwt.return () ;; let all_dispatched_jobs_gets_processed _ () = Sihl.Configuration.store [ "QUEUE_FORCE_ASYNC", "true" ]; let processed_inputs = ref [] in let%lwt () = Sihl.Container.stop_services [ QueueService.register () ] in let%lwt () = Sihl.Cleaner.clean_all () in let job = Sihl_queue.create_job ~max_tries:3 ~retry_delay:(Sihl.Time.Span.minutes 1) (fun input -> Lwt_result.return (processed_inputs := List.cons input !processed_inputs)) (fun str -> str) (fun str -> Ok str) "foo" in let service = QueueService.register ~jobs:[ Sihl_queue.hide job ] () in let%lwt _ = Sihl.Container.start_services [ service ] in let%lwt () = QueueService.dispatch_all [ "three"; "two"; "one" ] job in let%lwt () = Lwt_unix.sleep 4.0 in let%lwt () = Sihl.Container.stop_services [ service ] in let () = Alcotest.( check (list string) "has processed inputs" [ "one"; "two"; "three" ] !processed_inputs) in Lwt.return () ;; let two_dispatched_jobs_get_processed _ () = Sihl.Configuration.store [ "QUEUE_FORCE_ASYNC", "true" ]; let has_ran_job1 = ref false in let has_ran_job2 = ref false in let%lwt () = Sihl.Container.stop_services [ QueueService.register () ] in let%lwt () = Sihl.Cleaner.clean_all () in let job1 = Sihl_queue.create_job ~max_tries:3 ~retry_delay:(Sihl.Time.Span.minutes 1) (fun _ -> Lwt_result.return (has_ran_job1 := true)) (fun () -> "") (fun _ -> Ok ()) "foo1" in let job2 = Sihl_queue.create_job ~max_tries:3 ~retry_delay:(Sihl.Time.Span.minutes 1) (fun _ -> Lwt_result.return (has_ran_job2 := true)) (fun () -> "") (fun _ -> Ok ()) "foo2" in let service = QueueService.register ~jobs:[ Sihl_queue.hide job1; Sihl_queue.hide job2 ] () in let%lwt _ = Sihl.Container.start_services [ service ] in let%lwt () = QueueService.dispatch () job1 in let%lwt () = QueueService.dispatch () job2 in let%lwt () = Lwt_unix.sleep 4.0 in let%lwt () = Sihl.Container.stop_services [ service ] in let () = Alcotest.(check bool "has processed job1" true !has_ran_job1) in let () = Alcotest.(check bool "has processed job2" true !has_ran_job1) in Lwt.return () ;; let cleans_up_job_after_error _ () = Sihl.Configuration.store [ "QUEUE_FORCE_ASYNC", "true" ]; let has_cleaned_up_job = ref false in let%lwt () = Sihl.Container.stop_services [ QueueService.register () ] in let%lwt () = Sihl.Cleaner.clean_all () in let job = Sihl_queue.create_job ~max_tries:3 ~retry_delay:(Sihl.Time.Span.minutes 1) (fun _ -> Lwt_result.fail "didn't work") ~failed:(fun _ _ -> Lwt.return (has_cleaned_up_job := true)) (fun () -> "") (fun _ -> Ok ()) "foo" in let service = QueueService.register ~jobs:[ Sihl_queue.hide job ] () in let%lwt _ = Sihl.Container.start_services [ service ] in let%lwt () = QueueService.dispatch () job in let%lwt () = Lwt_unix.sleep 2.0 in let%lwt () = Sihl.Container.stop_services [ service ] in let () = Alcotest.(check bool "has cleaned up job" true !has_cleaned_up_job) in Lwt.return () ;; let cleans_up_job_after_exception _ () = Sihl.Configuration.store [ "QUEUE_FORCE_ASYNC", "true" ]; let has_cleaned_up_job = ref false in let%lwt () = Sihl.Container.stop_services [ QueueService.register () ] in let%lwt () = Sihl.Cleaner.clean_all () in let job = Sihl_queue.create_job (fun _ -> failwith "didn't work") ~max_tries:3 ~retry_delay:(Sihl.Time.Span.minutes 1) ~failed:(fun _ _ -> Lwt.return (has_cleaned_up_job := true)) (fun () -> "") (fun _ -> Ok ()) "foo" in let service = QueueService.register ~jobs:[ Sihl_queue.hide job ] () in let%lwt _ = Sihl.Container.start_services [ service ] in let%lwt () = QueueService.dispatch () job in let%lwt () = Lwt_unix.sleep 2.0 in let%lwt () = Sihl.Container.stop_services [ service ] in let () = Alcotest.(check bool "has cleaned up job" true !has_cleaned_up_job) in Lwt.return () ;; let suite = [ ( "queue" , [ test_case "should job run" `Quick should_run_job ; test_case "all dispatched jobs get processed" `Quick all_dispatched_jobs_gets_processed ; test_case "dispatched job gets processed" `Quick dispatched_job_gets_processed ; test_case "two dispatched jobs get processed" `Quick two_dispatched_jobs_get_processed ; test_case "cleans up job after error" `Quick cleans_up_job_after_error ; test_case "cleans up job after exception" `Quick cleans_up_job_after_exception ] ) ] ;; end
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl-queue/test/queue_inmemory.ml
let services = [ Sihl.Schedule.register []; Sihl_queue.InMemory.register () ] module Test = Queue.Make (Sihl_queue.InMemory) let () = Logs.set_level (Sihl.Log.get_log_level ()); Logs.set_reporter (Sihl.Log.cli_reporter ()); Lwt_main.run (let%lwt _ = Sihl.Container.start_services services in Alcotest_lwt.run "in-memory" Test.suite) ;;
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl-queue/test/queue_mariadb.ml
let services = [ Sihl.Schedule.register [] ; Sihl.Database.register () ; Sihl.Database.Migration.MariaDb.register [] ; Sihl_queue.MariaDb.register () ] ;; module Test = Queue.Make (Sihl_queue.MariaDb) let () = Sihl.Configuration.read_string "DATABASE_URL_TEST_MARIADB" |> Option.value ~default:"mariadb://admin:[email protected]:3306/dev" |> Unix.putenv "DATABASE_URL"; Logs.set_level (Sihl.Log.get_log_level ()); Logs.set_reporter (Sihl.Log.cli_reporter ()); Lwt_main.run (let%lwt _ = Sihl.Container.start_services services in let%lwt () = Sihl.Database.Migration.MariaDb.run_all () in Alcotest_lwt.run "mariadb" Test.suite) ;;
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl-queue/test/queue_postgresql.ml
let services = [ Sihl.Schedule.register [] ; Sihl.Database.register () ; Sihl.Database.Migration.PostgreSql.register [] ; Sihl_queue.PostgreSql.register () ] ;; module Test = Queue.Make (Sihl_queue.PostgreSql) let () = Sihl.Configuration.read_string "DATABASE_URL_TEST_POSTGRESQL" |> Option.value ~default:"postgres://admin:[email protected]:5432/dev" |> Unix.putenv "DATABASE_URL"; Logs.set_level (Sihl.Log.get_log_level ()); Logs.set_reporter (Sihl.Log.cli_reporter ()); Lwt_main.run (let%lwt _ = Sihl.Container.start_services services in let%lwt () = Sihl.Database.Migration.PostgreSql.run_all () in Alcotest_lwt.run "postgresql" Test.suite) ;;
sihl-email
3.0.5
Unknown
Unknown
Unknown
opam
sihl-3.0.5/sihl-storage.opam
# This file is generated by dune, edit dune-project instead opam-version: "2.0" version: "3.0.5" synopsis: "Storage service implementations for Sihl" description: "Modules for storing large binary blobs using either PostgreSQL or MariaDB." maintainer: ["[email protected]"] authors: ["Josef Erben" "Aron Erben" "Miko Nieminen"] license: "MIT" homepage: "https://github.com/oxidizing/sihl" doc: "https://oxidizing.github.io/sihl/" bug-reports: "https://github.com/oxidizing/sihl/issues" depends: [ "dune" {>= "2.7"} "ocaml" {>= "4.08.0"} "sihl" {= version} "alcotest-lwt" {>= "1.4.0" & with-test} "caqti-driver-postgresql" {>= "1.8.0" & with-test} "caqti-driver-mariadb" {>= "1.8.0" & with-test} "odoc" {with-doc} ] build: [ ["dune" "subst"] {dev} [ "dune" "build" "-p" name "-j" jobs "@install" "@runtest" {with-test} "@doc" {with-doc} ] ] dev-repo: "git+https://github.com/oxidizing/sihl.git"
sihl-email
3.0.5
Unknown
Unknown
Unknown
dune
sihl-3.0.5/sihl-storage/src/dune
(library (name sihl_storage) (public_name sihl-storage) (libraries sihl) (preprocess (pps ppx_deriving_yojson lwt_ppx)))
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl-storage/src/repo.ml
module type Sig = sig val register_migration : unit -> unit val register_cleaner : unit -> unit val insert_file : ?ctx:(string * string) list -> Sihl.Contract.Storage.stored -> unit Lwt.t val insert_blob : ?ctx:(string * string) list -> id:string -> string -> unit Lwt.t val get_file : ?ctx:(string * string) list -> string -> Sihl.Contract.Storage.stored option Lwt.t val get_blob : ?ctx:(string * string) list -> string -> string option Lwt.t val update_file : ?ctx:(string * string) list -> Sihl.Contract.Storage.stored -> unit Lwt.t val update_blob : ?ctx:(string * string) list -> id:string -> string -> unit Lwt.t val delete_file : ?ctx:(string * string) list -> string -> unit Lwt.t val delete_blob : ?ctx:(string * string) list -> string -> unit Lwt.t end module MakeMariaDb (MigrationService : Sihl.Contract.Migration.Sig) : Sig = struct let stored_file = let encode m = let open Sihl.Contract.Storage in let { file; blob } = m in let { id; filename; filesize; mime } = file in Ok (id, (filename, (filesize, (mime, blob)))) in let decode (id, (filename, (filesize, (mime, blob)))) = let open Sihl.Contract.Storage in let file = { id; filename; filesize; mime } in Ok { file; blob } in Caqti_type.( custom ~encode ~decode Caqti_type.(tup2 string (tup2 string (tup2 int (tup2 string string))))) ;; let insert_request = let open Caqti_request.Infix in {sql| INSERT INTO storage_handles ( uuid, filename, filesize, mime, asset_blob ) VALUES ( UNHEX(REPLACE(?, '-', '')), ?, ?, ?, UNHEX(REPLACE(?, '-', '')) ) |sql} |> stored_file ->. Caqti_type.unit ;; let insert_file ?ctx file = Sihl.Database.exec ?ctx insert_request file let update_file_request = let open Caqti_request.Infix in {sql| UPDATE storage_handles SET filename = $2, filesize = $3, mime = $4, asset_blob = UNHEX(REPLACE($5, '-', '')) WHERE storage_handles.uuid = UNHEX(REPLACE($1, '-', '')) |sql} |> stored_file ->. Caqti_type.unit ;; let update_file ?ctx file = Sihl.Database.exec ?ctx update_file_request file let get_file_request = let open Caqti_request.Infix in {sql| SELECT LOWER(CONCAT( SUBSTR(HEX(uuid), 1, 8), '-', SUBSTR(HEX(uuid), 9, 4), '-', SUBSTR(HEX(uuid), 13, 4), '-', SUBSTR(HEX(uuid), 17, 4), '-', SUBSTR(HEX(uuid), 21) )), filename, filesize, mime, LOWER(CONCAT( SUBSTR(HEX(asset_blob), 1, 8), '-', SUBSTR(HEX(asset_blob), 9, 4), '-', SUBSTR(HEX(asset_blob), 13, 4), '-', SUBSTR(HEX(asset_blob), 17, 4), '-', SUBSTR(HEX(asset_blob), 21) )) FROM storage_handles WHERE storage_handles.uuid = UNHEX(REPLACE(?, '-', '')) |sql} |> Caqti_type.string ->? stored_file ;; let get_file ?ctx id = Sihl.Database.find_opt ?ctx get_file_request id let delete_file_request = let open Caqti_request.Infix in {sql| DELETE FROM storage_handles WHERE storage_handles.uuid = UNHEX(REPLACE(?, '-', '')) |sql} |> Caqti_type.(string ->. unit) ;; let delete_file ?ctx id = Sihl.Database.exec ?ctx delete_file_request id let get_blob_request = let open Caqti_request.Infix in {sql| SELECT asset_data FROM storage_blobs WHERE storage_blobs.uuid = UNHEX(REPLACE(?, '-', '')) |sql} |> Caqti_type.(string ->? string) ;; let get_blob ?ctx id = Sihl.Database.find_opt ?ctx get_blob_request id let insert_blob_request = let open Caqti_request.Infix in {sql| INSERT INTO storage_blobs ( uuid, asset_data ) VALUES ( UNHEX(REPLACE(?, '-', '')), ? ) |sql} |> Caqti_type.(tup2 string string ->. unit) ;; let insert_blob ?ctx ~id blob = Sihl.Database.exec ?ctx insert_blob_request (id, blob) ;; let update_blob_request = let open Caqti_request.Infix in {sql| UPDATE storage_blobs SET asset_data = $2 WHERE storage_blobs.uuid = UNHEX(REPLACE($1, '-', '')) |sql} |> Caqti_type.(tup2 string string ->. unit) ;; let update_blob ?ctx ~id blob = Sihl.Database.exec ?ctx update_blob_request (id, blob) ;; let delete_blob_request = let open Caqti_request.Infix in {sql| DELETE FROM storage_blobs WHERE storage_blobs.uuid = UNHEX(REPLACE(?, '-', '')) |sql} |> Caqti_type.(string ->. unit) ;; let delete_blob ?ctx id = Sihl.Database.exec ?ctx delete_blob_request id let clean_handles_request = let open Caqti_request.Infix in "TRUNCATE storage_handles" |> Caqti_type.(unit ->. unit) ;; let clean_handles ?ctx () = Sihl.Database.exec ?ctx clean_handles_request () let clean_blobs_request = let open Caqti_request.Infix in "TRUNCATE storage_blobs" |> Caqti_type.(unit ->. unit) ;; let clean_blobs ?ctx () = Sihl.Database.exec ?ctx clean_blobs_request () let fix_collation = Sihl.Database.Migration.create_step ~label:"fix collation" {sql| SET collation_server = 'utf8mb4_unicode_ci' |sql} ;; let create_blobs_table = Sihl.Database.Migration.create_step ~label:"create blobs table" {sql| CREATE TABLE IF NOT EXISTS storage_blobs ( id BIGINT UNSIGNED AUTO_INCREMENT, uuid BINARY(16) NOT NULL, asset_data MEDIUMBLOB NOT NULL, created TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (id), CONSTRAINT unique_uuid UNIQUE KEY (uuid) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci |sql} ;; let create_handles_table = Sihl.Database.Migration.create_step ~label:"create handles table" {sql| CREATE TABLE IF NOT EXISTS storage_handles ( id BIGINT UNSIGNED AUTO_INCREMENT, uuid BINARY(16) NOT NULL, filename VARCHAR(255) NOT NULL, filesize BIGINT UNSIGNED, mime VARCHAR(128) NOT NULL, asset_blob BINARY(16) NOT NULL, created TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (id), CONSTRAINT unique_uuid UNIQUE KEY (uuid) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci |sql} ;; let migration () = Sihl.Database.Migration.( empty "storage" |> add_step fix_collation |> add_step create_blobs_table |> add_step create_handles_table) ;; let register_migration () = MigrationService.register_migration (migration ()) let register_cleaner () = let cleaner ?ctx () = let%lwt () = clean_handles ?ctx () in clean_blobs ?ctx () in Sihl.Cleaner.register_cleaner cleaner ;; end
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl-storage/src/sihl_storage.ml
include Sihl.Contract.Storage let log_src = Logs.Src.create ("sihl.service." ^ Sihl.Contract.Storage.name) module Logs = (val Logs.src_log log_src : Logs.LOG) module Make (Repo : Repo.Sig) : Sihl.Contract.Storage.Sig = struct let find_opt = Repo.get_file let find ?ctx id = let%lwt file = Repo.get_file ?ctx id in match file with | None -> raise (Sihl.Contract.Storage.Exception ("File not found with id " ^ id)) | Some file -> Lwt.return file ;; let delete ?ctx id = let%lwt file = find ?ctx id in let blob_id = file.Sihl.Contract.Storage.blob in let%lwt () = Repo.delete_file ?ctx file.file.id in Repo.delete_blob ?ctx blob_id ;; let upload_base64 ?ctx ?id file base64 = let blob_id = Option.value id ~default:(Uuidm.v `V4 |> Uuidm.to_string) in let%lwt blob = match Base64.decode base64 with | Error (`Msg msg) -> Logs.err (fun m -> m "Could not upload base64 content of file %a" pp_file file); raise (Sihl.Contract.Storage.Exception msg) | Ok blob -> Lwt.return blob in let%lwt () = Repo.insert_blob ?ctx ~id:blob_id blob in let stored_file = Sihl.Contract.Storage.{ file; blob = blob_id } in let%lwt () = Repo.insert_file ?ctx stored_file in Lwt.return stored_file ;; let update_base64 ?ctx file base64 = let blob_id = file.Sihl.Contract.Storage.blob in let%lwt blob = match Base64.decode base64 with | Error (`Msg msg) -> Logs.err (fun m -> m "Could not upload base64 content of file %a" pp_stored file); raise (Sihl.Contract.Storage.Exception msg) | Ok blob -> Lwt.return blob in let%lwt () = Repo.update_blob ?ctx ~id:blob_id blob in let%lwt () = Repo.update_file ?ctx file in Lwt.return file ;; let download_data_base64_opt ?ctx file = let blob_id = file.Sihl.Contract.Storage.blob in let%lwt blob = Repo.get_blob ?ctx blob_id in match Option.map Base64.encode blob with | Some (Error (`Msg msg)) -> Logs.err (fun m -> m "Could not get base64 content of file %a" pp_stored file); raise (Sihl.Contract.Storage.Exception msg) | Some (Ok blob) -> Lwt.return @@ Some blob | None -> Lwt.return None ;; let download_data_base64 ?ctx file = let blob_id = file.Sihl.Contract.Storage.blob in let%lwt blob = Repo.get_blob ?ctx blob_id in match Option.map Base64.encode blob with | Some (Error (`Msg msg)) -> Logs.err (fun m -> m "Could not get base64 content of file %a" pp_stored file); raise (Sihl.Contract.Storage.Exception msg) | Some (Ok blob) -> Lwt.return blob | None -> raise (Sihl.Contract.Storage.Exception (Format.asprintf "File data not found for file %a" pp_stored file)) ;; let start () = Lwt.return () let stop () = Lwt.return () let lifecycle = Sihl.Container.create_lifecycle "storage" ~start ~stop let register () = Repo.register_migration (); Repo.register_cleaner (); Sihl.Container.Service.create lifecycle ;; end module MariaDb : Sihl.Contract.Storage.Sig = Make (Repo.MakeMariaDb (Sihl.Database.Migration.MariaDb))
sihl-email
3.0.5
Unknown
Unknown
Unknown
dune
sihl-3.0.5/sihl-storage/test/dune
(executables (names storage_mariadb) (libraries sihl sihl-storage alcotest-lwt caqti-driver-mariadb) (preprocess (pps lwt_ppx)))
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl-storage/test/storage.ml
open Alcotest_lwt let file_equal f1 f2 = String.equal (Format.asprintf "%a" Sihl_storage.pp_file f1) (Format.asprintf "%a" Sihl_storage.pp_file f2) ;; let alco_file = Alcotest.testable Sihl_storage.pp_file file_equal module Make (StorageService : Sihl.Contract.Storage.Sig) = struct let fetch_uploaded_file _ () = let%lwt () = Sihl.Cleaner.clean_all () in let file_id = Uuidm.v `V4 |> Uuidm.to_string in let file = Sihl.Contract.Storage. { id = file_id ; filename = "diploma.pdf" ; filesize = 123 ; mime = "application/pdf" } in let%lwt _ = StorageService.upload_base64 file "ZmlsZWNvbnRlbnQ=" in let%lwt uploaded_file = StorageService.find ~ctx:[] file_id in let actual_file = uploaded_file.Sihl.Contract.Storage.file in Alcotest.(check alco_file "has same file" file actual_file); let%lwt actual_blob = StorageService.download_data_base64 uploaded_file in Alcotest.(check string "has same blob" "ZmlsZWNvbnRlbnQ=" actual_blob); Lwt.return () ;; let update_uploaded_file _ () = let%lwt () = Sihl.Cleaner.clean_all () in let file_id = Uuidm.v `V4 |> Uuidm.to_string in let file = Sihl.Contract.Storage. { id = file_id ; filename = "diploma.pdf" ; filesize = 123 ; mime = "application/pdf" } in let%lwt stored_file = StorageService.upload_base64 file "ZmlsZWNvbnRlbnQ=" in let updated_file = Sihl_storage.set_filename_stored "assessment.pdf" stored_file in let%lwt actual_file = StorageService.update_base64 updated_file "bmV3Y29udGVudA==" in Alcotest.( check alco_file "has updated file" updated_file.Sihl.Contract.Storage.file actual_file.Sihl.Contract.Storage.file); let%lwt actual_blob = StorageService.download_data_base64 stored_file in Alcotest.(check string "has updated blob" "bmV3Y29udGVudA==" actual_blob); Lwt.return () ;; let suite = [ ( "storage" , [ test_case "upload file" `Quick fetch_uploaded_file ; test_case "update file" `Quick update_uploaded_file ] ) ] ;; end
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl-storage/test/storage_mariadb.ml
let services = [ Sihl.Database.register () ; Sihl.Database.Migration.MariaDb.register [] ; Sihl_storage.MariaDb.register () ] ;; module Test = Storage.Make (Sihl_storage.MariaDb) let () = Sihl.Configuration.read_string "DATABASE_URL_TEST_MARIADB" |> Option.value ~default:"mariadb://admin:[email protected]:3306/dev" |> Unix.putenv "DATABASE_URL"; Logs.set_level (Sihl.Log.get_log_level ()); Logs.set_reporter (Sihl.Log.cli_reporter ()); Lwt_main.run (let%lwt _ = Sihl.Container.start_services services in let%lwt () = Sihl.Database.Migration.MariaDb.run_all () in Alcotest_lwt.run "mariadb" Test.suite) ;;
sihl-email
3.0.5
Unknown
Unknown
Unknown
opam
sihl-3.0.5/sihl-token.opam
# This file is generated by dune, edit dune-project instead opam-version: "2.0" version: "3.0.5" synopsis: "Token service implementations for Sihl" description: "Modules for token handling with support for JWT blacklisting and server-side stored tokens using PostgreSQL and MariaDB." maintainer: ["[email protected]"] authors: ["Josef Erben" "Aron Erben" "Miko Nieminen"] license: "MIT" homepage: "https://github.com/oxidizing/sihl" doc: "https://oxidizing.github.io/sihl/" bug-reports: "https://github.com/oxidizing/sihl/issues" depends: [ "dune" {>= "2.7"} "ocaml" {>= "4.08.0"} "sihl" {= version} "alcotest-lwt" {>= "1.4.0" & with-test} "caqti-driver-postgresql" {>= "1.8.0" & with-test} "caqti-driver-mariadb" {>= "1.8.0" & with-test} "odoc" {with-doc} ] build: [ ["dune" "subst"] {dev} [ "dune" "build" "-p" name "-j" jobs "@install" "@runtest" {with-test} "@doc" {with-doc} ] ] dev-repo: "git+https://github.com/oxidizing/sihl.git"
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl-token/src/blacklist_repo.ml
module type Sig = sig val lifecycles : Sihl.Container.lifecycle list val insert : ?ctx:(string * string) list -> string -> unit Lwt.t val has : ?ctx:(string * string) list -> string -> bool Lwt.t val delete : ?ctx:(string * string) list -> string -> unit Lwt.t val register_cleaner : unit -> unit val register_migration : unit -> unit end module InMemory : Sig = struct let lifecycles = [] let store = Hashtbl.create 100 let insert ?ctx:_ token = Hashtbl.add store token (); Lwt.return () ;; let has ?ctx:_ token = Lwt.return @@ Hashtbl.mem store token let delete ?ctx:_ token = Lwt.return @@ Hashtbl.remove store token let register_cleaner () = Sihl.Cleaner.register_cleaner (fun ?ctx:_ () -> Lwt.return (Hashtbl.clear store)) ;; let register_migration () = () end module MariaDb : Sig = struct module Migration = Sihl.Database.Migration.MariaDb let lifecycles = [ Sihl.Database.lifecycle; Migration.lifecycle ] let insert_request = let open Caqti_request.Infix in {sql| INSERT INTO token_blacklist ( token_value, created_at ) VALUES ( $1, $2 ) |sql} |> Caqti_type.(tup2 string ptime ->. unit) ;; let insert ?ctx token = let now = Ptime_clock.now () in Sihl.Database.exec ?ctx insert_request (token, now) ;; let find_request_opt = let open Caqti_request.Infix in {sql| SELECT token_value, created_at FROM token_blacklist WHERE token_blacklist.token_value = ? |sql} |> Caqti_type.(string ->? tup2 string ptime) ;; let find_opt ?ctx token = Sihl.Database.find_opt ?ctx find_request_opt token let has ?ctx token = let%lwt token = find_opt ?ctx token in Lwt.return @@ Option.is_some token ;; let delete_request = let open Caqti_request.Infix in {sql| DELETE FROM token_blacklist WHERE token_blacklist.token_value = ? |sql} |> Caqti_type.(string ->. unit) ;; let delete ?ctx token = Sihl.Database.exec ?ctx delete_request token let fix_collation = Sihl.Database.Migration.create_step ~label:"fix collation" "SET collation_server = 'utf8mb4_unicode_ci'" ;; let create_jobs_table = Sihl.Database.Migration.create_step ~label:"create token blacklist table" {sql| CREATE TABLE IF NOT EXISTS token_blacklist ( id BIGINT UNSIGNED AUTO_INCREMENT, token_value VARCHAR(2000) NOT NULL, created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci |sql} ;; let migration = Sihl.Database.Migration.( empty "tokens_blacklist" |> add_step fix_collation |> add_step create_jobs_table) ;; let register_migration () = Migration.register_migration migration let clean_request = let open Caqti_request.Infix in "TRUNCATE token_blacklist" |> Caqti_type.(unit ->. unit) ;; let clean ?ctx () = Sihl.Database.exec ?ctx clean_request () let register_cleaner () = Sihl.Cleaner.register_cleaner clean end module PostgreSql : Sig = struct module Migration = Sihl.Database.Migration.PostgreSql let lifecycles = [ Sihl.Database.lifecycle; Migration.lifecycle ] let insert_request = let open Caqti_request.Infix in {sql| INSERT INTO token_blacklist ( token_value, created_at ) VALUES ( $1, $2 AT TIME ZONE 'UTC' ) |sql} |> Caqti_type.(tup2 string ptime ->. unit) ;; let insert ?ctx token = let now = Ptime_clock.now () in Sihl.Database.exec ?ctx insert_request (token, now) ;; let find_request_opt = let open Caqti_request.Infix in {sql| SELECT token_value, created_at FROM token_blacklist WHERE token_blacklist.token_value = ? |sql} |> Caqti_type.(string ->? tup2 string ptime) ;; let find_opt ?ctx token = Sihl.Database.find_opt ?ctx find_request_opt token let has ?ctx token = let%lwt token = find_opt ?ctx token in Lwt.return @@ Option.is_some token ;; let delete_request = let open Caqti_request.Infix in {sql| DELETE FROM token_blacklist WHERE token_blacklist.token_value = ? |sql} |> Caqti_type.(string ->. unit) ;; let delete ?ctx token = Sihl.Database.exec ?ctx delete_request token let create_jobs_table = Sihl.Database.Migration.create_step ~label:"create token blacklist table" {sql| CREATE TABLE IF NOT EXISTS token_blacklist ( id serial, token_value VARCHAR(2000) NOT NULL, created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (id) ) |sql} ;; let remove_timezone = Sihl.Database.Migration.create_step ~label:"remove timezone info from timestamps" {sql| ALTER TABLE token_blacklist ALTER COLUMN created_at TYPE TIMESTAMP |sql} ;; let migration = Sihl.Database.Migration.( empty "tokens_blacklist" |> add_step create_jobs_table |> add_step remove_timezone) ;; let register_migration () = Migration.register_migration migration let clean_request = let open Caqti_request.Infix in "TRUNCATE token_blacklist" |> Caqti_type.(unit ->. unit) ;; let clean ?ctx () = Sihl.Database.exec ?ctx clean_request () let register_cleaner () = Sihl.Cleaner.register_cleaner clean end
sihl-email
3.0.5
Unknown
Unknown
Unknown
dune
sihl-3.0.5/sihl-token/src/dune
(library (name sihl_token) (public_name sihl-token) (libraries sihl) (preprocess (pps ppx_deriving_yojson lwt_ppx))) (documentation (package sihl-token))
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl-token/src/repo.ml
module Database = Sihl.Database module Cleaner = Sihl.Cleaner module Migration = Sihl.Database.Migration module Model = struct module Data = struct type t = (string * string) list [@@deriving yojson] let to_string data = data |> to_yojson |> Yojson.Safe.to_string let of_string str = str |> Yojson.Safe.from_string |> of_yojson end module Status = struct type t = | Active | Inactive let to_string = function | Active -> "active" | Inactive -> "inactive" ;; let of_string str = match str with | "active" -> Ok Active | "inactive" -> Ok Inactive | _ -> Error (Printf.sprintf "Invalid token status %s provided" str) ;; end type t = { id : string ; value : string ; data : Data.t ; status : Status.t ; expires_at : Ptime.t ; created_at : Ptime.t } let t = let ( let* ) = Result.bind in let encode m = let status = Status.to_string m.status in let data = Data.to_string m.data in Ok (m.id, (m.value, (data, (status, (m.expires_at, m.created_at))))) in let decode (id, (value, (data, (status, (expires_at, created_at))))) = let* status = Status.of_string status in let* data = Data.of_string data in Ok { id; value; data; status; expires_at; created_at } in Caqti_type.( custom ~encode ~decode (tup2 string (tup2 string (tup2 string (tup2 string (tup2 ptime ptime)))))) ;; end module type Sig = sig val lifecycles : Sihl.Container.lifecycle list val register_migration : unit -> unit val register_cleaner : unit -> unit val find : ?ctx:(string * string) list -> string -> Model.t Lwt.t val find_opt : ?ctx:(string * string) list -> string -> Model.t option Lwt.t val find_by_id : ?ctx:(string * string) list -> string -> Model.t Lwt.t val insert : ?ctx:(string * string) list -> Model.t -> unit Lwt.t val update : ?ctx:(string * string) list -> Model.t -> unit Lwt.t module Model = Model end module MariaDb (MigrationService : Sihl.Contract.Migration.Sig) : Sig = struct let lifecycles = [ Database.lifecycle; MigrationService.lifecycle ] module Model = Model module Sql = struct let find_request = let open Caqti_request.Infix in {sql| SELECT LOWER(CONCAT( SUBSTR(HEX(uuid), 1, 8), '-', SUBSTR(HEX(uuid), 9, 4), '-', SUBSTR(HEX(uuid), 13, 4), '-', SUBSTR(HEX(uuid), 17, 4), '-', SUBSTR(HEX(uuid), 21) )), token_value, token_data, status, expires_at, created_at FROM token_tokens WHERE token_tokens.token_value = ? |sql} |> Caqti_type.string ->! Model.t ;; let find ?ctx value = Database.find ?ctx find_request value let find_request_opt = let open Caqti_request.Infix in {sql| SELECT LOWER(CONCAT( SUBSTR(HEX(uuid), 1, 8), '-', SUBSTR(HEX(uuid), 9, 4), '-', SUBSTR(HEX(uuid), 13, 4), '-', SUBSTR(HEX(uuid), 17, 4), '-', SUBSTR(HEX(uuid), 21) )), token_value, token_data, status, expires_at, created_at FROM token_tokens WHERE token_tokens.token_value = ? |sql} |> Caqti_type.string ->? Model.t ;; let find_opt ?ctx value = Database.find_opt ?ctx find_request_opt value let find_by_id_request = let open Caqti_request.Infix in {sql| SELECT LOWER(CONCAT( SUBSTR(HEX(uuid), 1, 8), '-', SUBSTR(HEX(uuid), 9, 4), '-', SUBSTR(HEX(uuid), 13, 4), '-', SUBSTR(HEX(uuid), 17, 4), '-', SUBSTR(HEX(uuid), 21) )), token_value, token_data, status, expires_at, created_at FROM token_tokens WHERE token_tokens.uuid = UNHEX(REPLACE(?, '-', '')) |sql} |> Caqti_type.string ->! Model.t ;; let find_by_id ?ctx id = Database.find ?ctx find_by_id_request id let insert_request = let open Caqti_request.Infix in {sql| INSERT INTO token_tokens ( uuid, token_value, token_data, status, expires_at, created_at ) VALUES ( UNHEX(REPLACE($1, '-', '')), $2, $3, $4, $5, $6 ) |sql} |> Model.t ->. Caqti_type.unit ;; let insert ?ctx token = Database.exec ?ctx insert_request token let update_request = let open Caqti_request.Infix in {sql| UPDATE token_tokens SET token_data = $3, status = $4, expires_at = $5, created_at = $6 WHERE token_tokens.token_value = $2 |sql} |> Model.t ->. Caqti_type.unit ;; let update ?ctx token = Database.exec ?ctx update_request token let clean_request = let open Caqti_request.Infix in "TRUNCATE token_tokens" |> Caqti_type.(unit ->. unit) ;; let clean ?ctx () = Database.exec ?ctx clean_request () end module Migration = struct let fix_collation = Migration.create_step ~label:"fix collation" "SET collation_server = 'utf8mb4_unicode_ci'" ;; let create_tokens_table = Migration.create_step ~label:"create tokens table" {sql| CREATE TABLE IF NOT EXISTS token_tokens ( id BIGINT UNSIGNED AUTO_INCREMENT, uuid BINARY(16) NOT NULL, token_value VARCHAR(128) NOT NULL, token_data VARCHAR(1024), token_kind VARCHAR(128) NOT NULL, status VARCHAR(128) NOT NULL, expires_at TIMESTAMP NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (id), CONSTRAINT unqiue_uuid UNIQUE KEY (uuid), CONSTRAINT unique_value UNIQUE KEY (token_value) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci |sql} ;; let remove_token_kind_column = Migration.create_step ~label:"remove token kind column" "ALTER TABLE token_tokens DROP COLUMN token_kind" ;; let migration () = Migration.( empty "tokens" |> add_step fix_collation |> add_step create_tokens_table |> add_step remove_token_kind_column) ;; end let register_migration () = MigrationService.register_migration (Migration.migration ()) ;; let register_cleaner () = Cleaner.register_cleaner Sql.clean let find = Sql.find let find_opt = Sql.find_opt let find_by_id = Sql.find_by_id let insert = Sql.insert let update = Sql.update end module PostgreSql (MigrationService : Sihl.Contract.Migration.Sig) : Sig = struct let lifecycles = [ Database.lifecycle; MigrationService.lifecycle ] module Model = Model module Sql = struct let find_request = let open Caqti_request.Infix in {sql| SELECT uuid, token_value, token_data, status, expires_at, created_at FROM token_tokens WHERE token_tokens.token_value = $1::text |sql} |> Caqti_type.string ->! Model.t ;; let find ?ctx value = Database.find ?ctx find_request value let find_request_opt = let open Caqti_request.Infix in {sql| SELECT uuid, token_value, token_data, status, expires_at, created_at FROM token_tokens WHERE token_tokens.token_value = $1::text |sql} |> Caqti_type.string ->? Model.t ;; let find_opt ?ctx value = Database.find_opt ?ctx find_request_opt value let find_by_id_request = let open Caqti_request.Infix in {sql| SELECT uuid, token_value, token_data, status, expires_at, created_at FROM token_tokens WHERE token_tokens.uuid = $1::uuid |sql} |> Caqti_type.string ->! Model.t ;; let find_by_id ?ctx id = Database.find ?ctx find_by_id_request id let insert_request = let open Caqti_request.Infix in {sql| INSERT INTO token_tokens ( uuid, token_value, token_data, status, expires_at, created_at ) VALUES ( $1::uuid, $2, $3, $4, $5 AT TIME ZONE 'UTC', $6 AT TIME ZONE 'UTC' ) |sql} |> Model.t ->. Caqti_type.unit ;; let insert ?ctx token = Database.exec ?ctx insert_request token let update_request = let open Caqti_request.Infix in {sql| UPDATE token_tokens SET uuid = $1::uuid, token_data = $3, status = $4, expires_at = $5 AT TIME ZONE 'UTC', created_at = $6 AT TIME ZONE 'UTC' WHERE token_tokens.token_value = $2 |sql} |> Model.t ->. Caqti_type.unit ;; let update ?ctx token = Database.exec ?ctx update_request token let clean_request = let open Caqti_request.Infix in "TRUNCATE token_tokens CASCADE" |> Caqti_type.(unit ->. unit) ;; let clean ?ctx () = Database.exec ?ctx clean_request () end module Migration = struct let create_tokens_table = Migration.create_step ~label:"create tokens table" {sql| CREATE TABLE IF NOT EXISTS token_tokens ( id serial, uuid uuid NOT NULL, token_value VARCHAR(128) NOT NULL, token_data VARCHAR(1024), status VARCHAR(128) NOT NULL, expires_at TIMESTAMP NOT NULL, created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (id), UNIQUE (uuid), UNIQUE (token_value) ) |sql} ;; let remove_timezone = Sihl.Database.Migration.create_step ~label:"remove timezone info from timestamps" {sql| ALTER TABLE token_tokens ALTER COLUMN created_at TYPE TIMESTAMP |sql} ;; let migration () = Migration.( empty "tokens" |> add_step create_tokens_table |> add_step remove_timezone) ;; end let register_migration () = MigrationService.register_migration (Migration.migration ()) ;; let register_cleaner () = Cleaner.register_cleaner Sql.clean let find = Sql.find let find_opt = Sql.find_opt let find_by_id = Sql.find_by_id let insert = Sql.insert let update = Sql.update end
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl-token/src/sihl_token.ml
let log_src = Logs.Src.create ("sihl.service." ^ Sihl.Contract.Token.name) module Logs = (val Logs.src_log log_src : Logs.LOG) module Make (Repo : Repo.Sig) : Sihl.Contract.Token.Sig = struct type config = { token_length : int option } let config token_length = { token_length } let schema = let open Conformist in make [ optional (int ~default:80 "TOKEN_LENGTH") ] config ;; let is_valid_token token = let open Repo.Model in String.equal (Status.to_string token.status) (Status.to_string Status.Active) && Ptime.is_later token.expires_at ~than:(Ptime_clock.now ()) ;; let make id ?(expires_in = Sihl.Time.OneDay) ?now ?(length = 80) data = let open Repo.Model in let value = Sihl.Random.base64 length in let expires_in = Sihl.Time.duration_to_span expires_in in let now = Option.value ~default:(Ptime_clock.now ()) now in let expires_at = match Ptime.add_span now expires_in with | Some expires_at -> expires_at | None -> failwith ("Could not parse expiry date for token with id " ^ id) in let status = Status.Active in let created_at = Ptime_clock.now () in { id; value; data; status; expires_at; created_at } ;; let create ?ctx ?secret:_ ?expires_in data = let open Repo.Model in let id = Uuidm.v `V4 |> Uuidm.to_string in let length = Option.value ~default:30 (Sihl.Configuration.read schema).token_length in let token = make id ?expires_in ~length data in let%lwt () = Repo.insert ?ctx token in Repo.find_by_id ?ctx id |> Lwt.map (fun token -> token.value) ;; let read ?ctx ?secret:_ ?force token_value ~k = let open Repo.Model in let%lwt token = Repo.find_opt ?ctx token_value in match token with | None -> Lwt.return None | Some token -> (match is_valid_token token, force with | true, _ | false, Some () -> (match List.find_opt (fun (key, _) -> String.equal k key) token.data with | Some (_, value) -> Lwt.return (Some value) | None -> Lwt.return None) | false, None -> Lwt.return None) ;; let read_all ?ctx ?secret:_ ?force token = let open Repo.Model in let%lwt token = Repo.find ?ctx token in match is_valid_token token, force with | true, _ | false, Some () -> Lwt.return (Some token.data) | false, None -> Lwt.return None ;; let verify ?ctx ?secret:_ token = let%lwt token = Repo.find_opt ?ctx token in match token with | Some _ -> Lwt.return true | None -> Lwt.return false ;; let deactivate ?ctx token = let open Repo.Model in let%lwt token = Repo.find ?ctx token in let updated = { token with status = Status.Inactive } in Repo.update ?ctx updated ;; let activate ?ctx token = let open Repo.Model in let%lwt token = Repo.find ?ctx token in let updated = { token with status = Status.Active } in Repo.update ?ctx updated ;; let is_active ?ctx token = let open Repo.Model in let%lwt token = Repo.find ?ctx token in match token.status with | Status.Active -> Lwt.return true | Status.Inactive -> Lwt.return false ;; let is_expired ?ctx ?secret:_ token = let open Repo.Model in let%lwt token = Repo.find ?ctx token in Lwt.return (Ptime.is_earlier token.expires_at ~than:(Ptime_clock.now ())) ;; let is_valid ?ctx ?secret:_ token = let open Repo.Model in let%lwt token = Repo.find_opt ?ctx token in match token with | None -> Lwt.return false | Some token -> (match token.status with | Status.Inactive -> Lwt.return false | Status.Active -> Lwt.return (Ptime.is_later token.expires_at ~than:(Ptime_clock.now ()))) ;; let start () = (* Make sure that configuration is valid *) Sihl.Configuration.require schema; Lwt.return () ;; let stop () = Lwt.return () let lifecycle = Sihl.Container.create_lifecycle Sihl.Contract.Token.name ~dependencies:(fun () -> Repo.lifecycles) ~start ~stop ;; let register () = Repo.register_migration (); Repo.register_cleaner (); let configuration = Sihl.Configuration.make ~schema () in Sihl.Container.Service.create ~configuration lifecycle ;; end module MakeJwt (Repo : Blacklist_repo.Sig) : Sihl.Contract.Token.Sig = struct let calculate_exp expires_in = Sihl.Time.date_from_now (Ptime_clock.now ()) expires_in |> Ptime.to_float_s |> Int.of_float |> string_of_int ;; let create ?ctx:_ ?secret ?(expires_in = Sihl.Time.OneWeek) data = let secret = Option.value ~default:(Sihl.Configuration.read_secret ()) secret in let data = match List.find_opt (fun (k, _) -> String.equal k "exp") data with | Some (_, v) -> (match int_of_string_opt v with | Some _ -> data | None -> let exp = calculate_exp expires_in in List.cons ("exp", exp) data) | None -> let exp = calculate_exp expires_in in List.cons ("exp", exp) data in match Jwto.encode HS512 secret data with | Error msg -> raise @@ Sihl.Contract.Token.Exception msg | Ok token -> Lwt.return token ;; let deactivate ?ctx:_ token = Repo.insert token let activate ?ctx:_ token = Repo.delete token let is_active ?ctx:_ token = Repo.has token |> Lwt.map not let read ?ctx:_ ?secret ?force token_value ~k = let secret = Option.value ~default:(Sihl.Configuration.read_secret ()) secret in match Jwto.decode_and_verify secret token_value, force with | Error msg, None -> Logs.warn (fun m -> m "Failed to decode and verify token: %s" msg); Lwt.return None | Ok token, None -> let%lwt is_active = is_active token_value in if is_active then ( match List.find_opt (fun (key, _) -> String.equal k key) (Jwto.get_payload token) with | Some (_, value) -> Lwt.return (Some value) | None -> Lwt.return None) else Lwt.return None | Ok token, Some () -> (match List.find_opt (fun (key, _) -> String.equal k key) (Jwto.get_payload token) with | Some (_, value) -> Lwt.return (Some value) | None -> Lwt.return None) | Error msg, Some () -> Logs.warn (fun m -> m "Failed to decode and verify token: %s" msg); (match Jwto.decode token_value with | Error msg -> Logs.warn (fun m -> m "Failed to decode token: %s" msg); Lwt.return None | Ok token -> (match List.find_opt (fun (key, _) -> String.equal k key) (Jwto.get_payload token) with | Some (_, value) -> Lwt.return (Some value) | None -> Lwt.return None)) ;; let read_all ?ctx:_ ?secret ?force token_value = let secret = Option.value ~default:(Sihl.Configuration.read_secret ()) secret in match Jwto.decode_and_verify secret token_value, force with | Error msg, None -> Logs.warn (fun m -> m "Failed to decode and verify token: %s" msg); Lwt.return None | Ok token, Some () -> Lwt.return (Some (Jwto.get_payload token)) | Ok token, None -> let%lwt is_active = is_active token_value in if is_active then Lwt.return (Some (Jwto.get_payload token)) else Lwt.return None | Error msg, Some () -> Logs.warn (fun m -> m "Failed to decode and verify token: %s" msg); (match Jwto.decode token_value with | Error msg -> Logs.warn (fun m -> m "Failed to decode token: %s" msg); Lwt.return None | Ok token -> Lwt.return (Some (Jwto.get_payload token))) ;; let verify ?ctx:_ ?secret token = let secret = Option.value ~default:(Sihl.Configuration.read_secret ()) secret in match Jwto.decode_and_verify secret token with | Ok _ -> Lwt.return true | Error _ -> Lwt.return false ;; let is_expired ?ctx:_ ?secret token_value = let secret = Option.value ~default:(Sihl.Configuration.read_secret ()) secret in match Jwto.decode_and_verify secret token_value with | Ok token -> (match List.find_opt (fun (k, _) -> String.equal k "exp") (Jwto.get_payload token) with | Some (_, exp) -> let exp = exp |> int_of_string_opt |> Option.map float_of_int in (match Option.bind exp Ptime.of_float_s with | Some expiration_date -> let is_expired = Ptime.is_earlier expiration_date ~than:(Ptime_clock.now ()) in Lwt.return is_expired | None -> raise @@ Sihl.Contract.Token.Exception (Format.sprintf "Invalid 'exp' claim found in token '%s'" token_value)) | None -> Lwt.return false) | Error msg -> Logs.warn (fun m -> m "Failed to decode and verify token: %s" msg); Lwt.return true ;; let is_valid ?ctx ?secret token = let%lwt is_expired = is_expired ?ctx ?secret token in Lwt.return (not is_expired) ;; let start () = Lwt.return () let stop () = Lwt.return () let lifecycle = Sihl.Container.create_lifecycle Sihl.Contract.Token.name ~dependencies:(fun () -> Repo.lifecycles) ~start ~stop ;; let register () = Repo.register_migration (); Repo.register_cleaner (); Sihl.Container.Service.create lifecycle ;; end module MariaDb = Make (Repo.MariaDb (Sihl.Database.Migration.MariaDb)) module PostgreSql = Make (Repo.PostgreSql (Sihl.Database.Migration.PostgreSql)) module JwtInMemory = MakeJwt (Blacklist_repo.InMemory) module JwtMariaDb = MakeJwt (Blacklist_repo.MariaDb) module JwtPostgreSql = MakeJwt (Blacklist_repo.PostgreSql)
sihl-email
3.0.5
Unknown
Unknown
Unknown
mli
sihl-3.0.5/sihl-token/src/sihl_token.mli
val log_src : Logs.src module MariaDb : sig include Sihl.Contract.Token.Sig end module PostgreSql : sig include Sihl.Contract.Token.Sig end module JwtInMemory : sig include Sihl.Contract.Token.Sig end module JwtMariaDb : sig include Sihl.Contract.Token.Sig end module JwtPostgreSql : sig include Sihl.Contract.Token.Sig end
sihl-email
3.0.5
Unknown
Unknown
Unknown
dune
sihl-3.0.5/sihl-token/test/dune
(executables (names mariadb postgresql jwt_inmemory jwt_mariadb jwt_postgresql) (libraries sihl sihl-token alcotest-lwt caqti-driver-mariadb caqti-driver-postgresql) (preprocess (pps lwt_ppx)))
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl-token/test/jwt_inmemory.ml
let services = [ Sihl_token.JwtInMemory.register () ] module Test = Token.Make (Sihl_token.JwtInMemory) let () = Logs.set_level (Sihl.Log.get_log_level ()); Logs.set_reporter (Sihl.Log.cli_reporter ()); Lwt_main.run (let%lwt _ = Sihl.Container.start_services services in Alcotest_lwt.run "jwt in-memory" Test.suite) ;;
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl-token/test/jwt_mariadb.ml
let services = [ Sihl.Database.register () ; Sihl.Database.Migration.MariaDb.register [] ; Sihl_token.JwtMariaDb.register () ] ;; module Test = Token.Make (Sihl_token.JwtMariaDb) let () = Sihl.Configuration.read_string "DATABASE_URL_TEST_MARIADB" |> Option.value ~default:"mariadb://admin:[email protected]:3306/dev" |> Unix.putenv "DATABASE_URL"; Logs.set_level (Sihl.Log.get_log_level ()); Logs.set_reporter (Sihl.Log.cli_reporter ()); Lwt_main.run (let%lwt _ = Sihl.Container.start_services services in let%lwt () = Sihl.Database.Migration.MariaDb.run_all () in Alcotest_lwt.run "jwt mariadb" Test.suite) ;;
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl-token/test/jwt_postgresql.ml
let services = [ Sihl.Database.register () ; Sihl.Database.Migration.PostgreSql.register [] ; Sihl_token.JwtPostgreSql.register () ] ;; module Test = Token.Make (Sihl_token.JwtPostgreSql) let () = Sihl.Configuration.read_string "DATABASE_URL_TEST_POSTGRESQL" |> Option.value ~default:"postgres://admin:[email protected]:5432/dev" |> Unix.putenv "DATABASE_URL"; Logs.set_level (Sihl.Log.get_log_level ()); Logs.set_reporter (Sihl.Log.cli_reporter ()); Lwt_main.run (let%lwt _ = Sihl.Container.start_services services in let%lwt () = Sihl.Database.Migration.PostgreSql.run_all () in Alcotest_lwt.run "jwt postgresql" Test.suite) ;;
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl-token/test/mariadb.ml
let services = [ Sihl.Database.register () ; Sihl.Database.Migration.MariaDb.register [] ; Sihl_token.MariaDb.register () ] ;; module Test = Token.Make (Sihl_token.MariaDb) let () = Sihl.Configuration.read_string "DATABASE_URL_TEST_MARIADB" |> Option.value ~default:"mariadb://admin:[email protected]:3306/dev" |> Unix.putenv "DATABASE_URL"; Logs.set_level (Sihl.Log.get_log_level ()); Logs.set_reporter (Sihl.Log.cli_reporter ()); Lwt_main.run (let%lwt _ = Sihl.Container.start_services services in let%lwt () = Sihl.Database.Migration.MariaDb.run_all () in Alcotest_lwt.run "mariadb" Test.suite) ;;
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl-token/test/postgresql.ml
let services = [ Sihl.Database.register () ; Sihl.Database.Migration.PostgreSql.register [] ; Sihl_token.PostgreSql.register () ] ;; module Test = Token.Make (Sihl_token.PostgreSql) let () = Sihl.Configuration.read_string "DATABASE_URL_TEST_POSTGRESQL" |> Option.value ~default:"postgres://admin:[email protected]:5432/dev" |> Unix.putenv "DATABASE_URL"; Logs.set_level (Sihl.Log.get_log_level ()); Logs.set_reporter (Sihl.Log.cli_reporter ()); Lwt_main.run (let%lwt _ = Sihl.Container.start_services services in let%lwt () = Sihl.Database.Migration.PostgreSql.run_all () in Alcotest_lwt.run "postgresql" Test.suite) ;;
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl-token/test/token.ml
open Alcotest_lwt module Make (TokenService : Sihl.Contract.Token.Sig) = struct let create_and_read_token _ () = let%lwt () = Sihl.Cleaner.clean_all () in let%lwt token = TokenService.create [ "foo", "bar"; "fooz", "baz" ] in let%lwt value = TokenService.read token ~k:"foo" in Alcotest.(check (option string) "reads value" (Some "bar") value); let%lwt is_valid_signature = TokenService.verify token in Alcotest.(check bool "has valid signature" true is_valid_signature); let%lwt is_active = TokenService.is_active token in Alcotest.(check bool "is active" true is_active); let%lwt is_expired = TokenService.is_expired token in Alcotest.(check bool "is not expired" false is_expired); let%lwt is_valid = TokenService.is_valid token in Alcotest.(check bool "is valid" true is_valid); Lwt.return () ;; let deactivate_and_reactivate_token _ () = let%lwt () = Sihl.Cleaner.clean_all () in let%lwt token = TokenService.create [ "foo", "bar" ] in let%lwt value = TokenService.read token ~k:"foo" in Alcotest.(check (option string) "reads value" (Some "bar") value); let%lwt () = TokenService.deactivate token in let%lwt value = TokenService.read token ~k:"foo" in Alcotest.(check (option string) "reads no value" None value); let%lwt value = TokenService.read ~force:() token ~k:"foo" in Alcotest.(check (option string) "force reads value" (Some "bar") value); let%lwt () = TokenService.activate token in let%lwt value = TokenService.read token ~k:"foo" in Alcotest.(check (option string) "reads value again" (Some "bar") value); Lwt.return () ;; let forge_token _ () = let%lwt () = Sihl.Cleaner.clean_all () in let%lwt token = TokenService.create [ "foo", "bar" ] in let%lwt value = TokenService.read token ~k:"foo" in Alcotest.(check (option string) "reads value" (Some "bar") value); let forged_token = "prefix" ^ token in let%lwt value = TokenService.read forged_token ~k:"foo" in Alcotest.(check (option string) "reads no value" None value); let%lwt value = TokenService.read ~force:() forged_token ~k:"foo" in Alcotest.(check (option string) "force doesn't read value" None value); let%lwt is_valid_signature = TokenService.verify forged_token in Alcotest.(check bool "signature is not valid" false is_valid_signature); Lwt.return () ;; let suite = [ ( "token" , [ test_case "create and find token" `Quick create_and_read_token ; test_case "deactivate and re-activate token" `Quick deactivate_and_reactivate_token ; test_case "forge token" `Quick forge_token ] ) ] ;; end
sihl-email
3.0.5
Unknown
Unknown
Unknown
opam
sihl-3.0.5/sihl-user.opam
# This file is generated by dune, edit dune-project instead opam-version: "2.0" version: "3.0.5" synopsis: "User service implementations for Sihl" description: "Modules for user management and password reset workflows with support for PostgreSQL and MariaDB." maintainer: ["[email protected]"] authors: ["Josef Erben" "Aron Erben" "Miko Nieminen"] license: "MIT" homepage: "https://github.com/oxidizing/sihl" doc: "https://oxidizing.github.io/sihl/" bug-reports: "https://github.com/oxidizing/sihl/issues" depends: [ "dune" {>= "2.7"} "ocaml" {>= "4.08.0"} "sihl" {= version} "sihl-token" {= version & with-test} "alcotest-lwt" {>= "1.4.0" & with-test} "caqti-driver-postgresql" {>= "1.8.0" & with-test} "caqti-driver-mariadb" {>= "1.8.0" & with-test} "odoc" {with-doc} ] build: [ ["dune" "subst"] {dev} [ "dune" "build" "-p" name "-j" jobs "@install" "@runtest" {with-test} "@doc" {with-doc} ] ] dev-repo: "git+https://github.com/oxidizing/sihl.git"
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl-user/src/authz.ml
type guard = bool * string let authorize (can, msg) = if can then Ok () else Error msg let any guards msg = let can = guards |> List.map authorize |> List.find_opt Result.is_ok |> Option.is_some in authorize (can, msg) ;;
sihl-email
3.0.5
Unknown
Unknown
Unknown
dune
sihl-3.0.5/sihl-user/src/dune
(library (name sihl_user) (public_name sihl-user) (libraries sihl) (preprocess (pps lwt_ppx))) (documentation (package sihl-user))
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl-user/src/password_reset.ml
let log_src = Logs.Src.create ("sihl.service." ^ Sihl.Contract.Password_reset.name) ;; module Logs = (val Logs.src_log log_src : Logs.LOG) module Make (UserService : Sihl.Contract.User.Sig) (TokenService : Sihl.Contract.Token.Sig) = struct let create_reset_token ?ctx email = let%lwt user = UserService.find_by_email_opt ?ctx email in match user with | Some user -> let user_id = user.id in TokenService.create ?ctx ~expires_in:Sihl.Time.OneDay [ "user_id", user_id ] |> Lwt.map Option.some | None -> Logs.warn (fun m -> m "No user found with email %s" email); Lwt.return None ;; let reset_password ?ctx ~token password password_confirmation = let%lwt user_id = TokenService.read ?ctx token ~k:"user_id" in match user_id with | None -> Lwt.return @@ Error "Token invalid or not assigned to any user" | Some user_id -> let%lwt user = UserService.find ?ctx user_id in let%lwt result = UserService.set_password ?ctx user ~password ~password_confirmation in Lwt.return @@ Result.map (fun _ -> ()) result ;; let start () = Lwt.return () let stop () = Lwt.return () let lifecycle = Sihl.Container.create_lifecycle Sihl.Contract.Password_reset.name ~start ~stop ~dependencies:(fun () -> [ TokenService.lifecycle; UserService.lifecycle ]) ;; let register () = Sihl.Container.Service.create lifecycle end
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl-user/src/sihl_user.ml
include Sihl.Contract.User let log_src = Logs.Src.create ("sihl.service." ^ Sihl.Contract.User.name) module Logs = (val Logs.src_log log_src : Logs.LOG) module Make (Repo : User_repo.Sig) : Sihl.Contract.User.Sig = struct let find_opt = Repo.get let find ?ctx user_id = let%lwt m_user = find_opt ?ctx user_id in match m_user with | Some user -> Lwt.return user | None -> Logs.err (fun m -> m "User not found with id %s" user_id); raise (Sihl.Contract.User.Exception "User not found") ;; let find_by_email_opt = Repo.get_by_email let find_by_email ?ctx email = let%lwt user = find_by_email_opt ?ctx email in match user with | Some user -> Lwt.return user | None -> Logs.err (fun m -> m "User not found with email %s" email); raise (Sihl.Contract.User.Exception "User not found") ;; let search ?ctx ?(sort = `Desc) ?filter ?(limit = 50) ?(offset = 0) () = Repo.search ?ctx sort filter ~limit ~offset ;; let update_details ~user:_ ~email:_ ~username:_ = failwith "update()" let update ?ctx ?email ?username ?name ?given_name ?status user = let updated = { user with email = Option.value ~default:user.email email ; username = (match username with | Some username -> Some username | None -> user.username) ; name = (match name with | Some name -> Some name | None -> user.name) ; given_name = (match given_name with | Some given_name -> Some given_name | None -> user.given_name) ; status = Option.value ~default:user.status status } in let%lwt () = Repo.update ?ctx updated in find ?ctx user.id ;; let update_password ?ctx ?(password_policy = default_password_policy) user ~old_password ~new_password ~new_password_confirmation = match validate_change_password user ~old_password ~new_password ~new_password_confirmation ~password_policy with | Ok () -> let updated_user = match set_user_password user new_password with | Ok user -> user | Error msg -> Logs.err (fun m -> m "Can not update password of user '%s': %s" user.email msg); raise (Sihl.Contract.User.Exception msg) in let%lwt () = Repo.update ?ctx updated_user in find ?ctx user.id |> Lwt.map Result.ok | Error msg -> Lwt.return @@ Error msg ;; let set_password ?ctx ?(password_policy = default_password_policy) user ~password ~password_confirmation = let%lwt result = validate_new_password ~password ~password_confirmation ~password_policy |> Lwt.return in match result with | Error msg -> Lwt.return @@ Error msg | Ok () -> let%lwt result = Repo.get ?ctx user.id in (* Re-fetch user to make sure that we have an up-to-date model *) let%lwt user = match result with | Some user -> Lwt.return user | None -> raise (Sihl.Contract.User.Exception "Failed to create user") in let updated_user = match set_user_password user password with | Ok user -> user | Error msg -> Logs.err (fun m -> m "Can not set password of user %s: %s" user.email msg); raise (Sihl.Contract.User.Exception msg) in let%lwt () = Repo.update ?ctx updated_user in find ?ctx user.id |> Lwt.map Result.ok ;; let create ?ctx ?id ~email ~password ~username ~name ~given_name ~admin confirmed = let user = make ?id ~email ~password ~username ~name ~given_name ~admin confirmed in match user with | Ok user -> let%lwt () = Repo.insert ?ctx user in let%lwt user = find ?ctx user.id in Lwt.return (Ok user) | Error msg -> raise (Sihl.Contract.User.Exception msg) ;; let create_user ?ctx ?id ?username ?name ?given_name ~password email = let%lwt user = create ?ctx ?id ~password ~username ~name ~given_name ~admin:false ~email false in match user with | Ok user -> Lwt.return user | Error msg -> raise (Sihl.Contract.User.Exception msg) ;; let create_admin ?ctx ?id ?username ?name ?given_name ~password email = let%lwt user = Repo.get_by_email ?ctx email in let%lwt () = match user with | Some _ -> Logs.err (fun m -> m "Can not create admin '%s' since the email is already taken" email); raise (Sihl.Contract.User.Exception "Email already taken") | None -> Lwt.return () in let%lwt user = create ?ctx ?id ~password ~username ~name ~given_name ~admin:true ~email true in match user with | Ok user -> Lwt.return user | Error msg -> Logs.err (fun m -> m "Can not create admin '%s': %s" email msg); raise (Sihl.Contract.User.Exception msg) ;; let register_user ?ctx ?id ?(password_policy = default_password_policy) ?username ?name ?given_name email ~password ~password_confirmation = match validate_new_password ~password ~password_confirmation ~password_policy with | Error msg -> Lwt_result.fail @@ `Invalid_password_provided msg | Ok () -> let%lwt user = find_by_email_opt ?ctx email in (match user with | None -> create_user ?ctx ?id ?username ?name ?given_name ~password email |> Lwt.map Result.ok | Some _ -> Lwt_result.fail `Already_registered) ;; let login ?ctx email ~password = let open Sihl.Contract.User in let%lwt user = find_by_email_opt ?ctx email in match user with | None -> Lwt_result.fail `Does_not_exist | Some user -> if matches_password password user then Lwt_result.return user else Lwt_result.fail `Incorrect_password ;; let start () = Lwt.return () let stop () = Lwt.return () let create_admin_cmd = Sihl.Command.make ~name:"user.admin" ~help:"<email> <password>" ~description:"Creates a user with admin privileges." (fun args -> match args with | [ email; password ] -> let%lwt () = start () in create_admin ~password email |> Lwt.map ignore |> Lwt.map Option.some | _ -> Lwt.return None) ;; let lifecycle = Sihl.Container.create_lifecycle Sihl.Contract.User.name ~dependencies:(fun () -> Repo.lifecycles) ~start ~stop ;; let register () = Repo.register_migration (); Repo.register_cleaner (); Sihl.Container.Service.create ~commands:[ create_admin_cmd ] lifecycle ;; module Web = struct let user_from_session = Web.user_from_session find_opt let user_from_token = Web.user_from_token find_opt end end module PostgreSql = Make (User_repo.MakePostgreSql (Sihl.Database.Migration.PostgreSql)) module MariaDb = Make (User_repo.MakeMariaDb (Sihl.Database.Migration.MariaDb)) module Password_reset = struct let log_src = Password_reset.log_src module MakePostgreSql (TokenService : Sihl.Contract.Token.Sig) = Password_reset.Make (PostgreSql) (TokenService) module MakeMariaDb (TokenService : Sihl.Contract.Token.Sig) = Password_reset.Make (MariaDb) (TokenService) end
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl-user/src/user_repo.ml
module Database = Sihl.Database module Cleaner = Sihl.Cleaner module Migration = Sihl.Database.Migration module Model = Sihl.Contract.User module type Sig = sig val register_migration : unit -> unit val register_cleaner : unit -> unit val lifecycles : Sihl.Container.lifecycle list val search : ?ctx:(string * string) list -> [ `Desc | `Asc ] -> string option -> limit:int -> offset:int -> (Model.t list * int) Lwt.t val get : ?ctx:(string * string) list -> string -> Model.t option Lwt.t val get_by_email : ?ctx:(string * string) list -> string -> Model.t option Lwt.t val insert : ?ctx:(string * string) list -> Model.t -> unit Lwt.t val update : ?ctx:(string * string) list -> Model.t -> unit Lwt.t end let status = let encode m = m |> Model.status_to_string |> Result.ok in let decode = Model.status_of_string in Caqti_type.(custom ~encode ~decode string) ;; let user = let open Sihl.Contract.User in let encode m = Ok ( m.id , ( m.email , ( m.username , ( m.name , ( m.given_name , ( m.password , ( m.status , (m.admin, (m.confirmed, (m.created_at, m.updated_at))) ) ) ) ) ) ) ) in let decode ( id , ( email , ( username , ( name , ( given_name , ( password , (status, (admin, (confirmed, (created_at, updated_at)))) ) ) ) ) ) ) = Ok { id ; email ; username ; name ; given_name ; password ; status ; admin ; confirmed ; created_at ; updated_at } in Caqti_type.( custom ~encode ~decode (tup2 string (tup2 string (tup2 (option string) (tup2 (option string) (tup2 (option string) (tup2 string (tup2 status (tup2 bool (tup2 bool (tup2 ptime ptime))))))))))) ;; module MakeMariaDb (MigrationService : Sihl.Contract.Migration.Sig) : Sig = struct let lifecycles = [ Database.lifecycle; MigrationService.lifecycle ] module Migration = struct let fix_collation = Migration.create_step ~label:"fix collation" {sql| SET collation_server = 'utf8mb4_unicode_ci' |sql} ;; let create_users_table = Migration.create_step ~label:"create users table" {sql| CREATE TABLE IF NOT EXISTS user_users ( id BIGINT UNSIGNED AUTO_INCREMENT, uuid BINARY(16) NOT NULL, email VARCHAR(128) NOT NULL, password VARCHAR(128) NOT NULL, username VARCHAR(128), status VARCHAR(128) NOT NULL, admin BOOLEAN NOT NULL DEFAULT false, confirmed BOOLEAN NOT NULL DEFAULT false, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (id), CONSTRAINT unique_uuid UNIQUE KEY (uuid), CONSTRAINT unique_email UNIQUE KEY (email) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci |sql} ;; let add_updated_at_column = Sihl.Database.Migration.create_step ~label:"add updated_at column" {sql| ALTER TABLE user_users ADD COLUMN updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP |sql} ;; let add_name_columns = Sihl.Database.Migration.create_step ~label:"add name columns" {sql| ALTER TABLE user_users ADD COLUMN name VARCHAR(128) NULL, ADD COLUMN given_name VARCHAR(128) NULL |sql} ;; let migration () = Migration.( empty "user" |> add_step fix_collation |> add_step create_users_table |> add_step add_updated_at_column |> add_step add_name_columns) ;; end let filter_fragment = {sql| WHERE user_users.email LIKE $1 OR user_users.username LIKE $1 OR user_users.name LIKE $1 OR user_users.given_name LIKE $1 OR user_users.status LIKE $1 |sql} ;; let search_query = {sql| SELECT COUNT(*) OVER() as total, LOWER(CONCAT( SUBSTR(HEX(uuid), 1, 8), '-', SUBSTR(HEX(uuid), 9, 4), '-', SUBSTR(HEX(uuid), 13, 4), '-', SUBSTR(HEX(uuid), 17, 4), '-', SUBSTR(HEX(uuid), 21) )), email, username, name, given_name, password, status, admin, confirmed, created_at, updated_at FROM user_users |sql} ;; let request = Sihl.Database.prepare_search_request ~search_query ~filter_fragment ~sort_by_field:"id" user ;; let search ?ctx sort filter ~limit ~offset = Sihl.Database.run_search_request ?ctx request sort filter ~limit ~offset ;; let get_request = let open Caqti_request.Infix in {sql| SELECT LOWER(CONCAT( SUBSTR(HEX(uuid), 1, 8), '-', SUBSTR(HEX(uuid), 9, 4), '-', SUBSTR(HEX(uuid), 13, 4), '-', SUBSTR(HEX(uuid), 17, 4), '-', SUBSTR(HEX(uuid), 21) )), email, username, name, given_name, password, status, admin, confirmed, created_at, updated_at FROM user_users WHERE user_users.uuid = UNHEX(REPLACE(?, '-', '')) |sql} |> Caqti_type.string ->? user ;; let get ?ctx id = Database.find_opt ?ctx get_request id let get_by_email_request = let open Caqti_request.Infix in {sql| SELECT LOWER(CONCAT( SUBSTR(HEX(uuid), 1, 8), '-', SUBSTR(HEX(uuid), 9, 4), '-', SUBSTR(HEX(uuid), 13, 4), '-', SUBSTR(HEX(uuid), 17, 4), '-', SUBSTR(HEX(uuid), 21) )), email, username, name, given_name, password, status, admin, confirmed, created_at, updated_at FROM user_users WHERE user_users.email LIKE ? |sql} |> Caqti_type.string ->? user ;; let get_by_email ?ctx email = Database.find_opt ?ctx get_by_email_request email ;; let insert_request = let open Caqti_request.Infix in {sql| INSERT INTO user_users ( uuid, email, username, name, given_name, password, status, admin, confirmed, created_at, updated_at ) VALUES ( UNHEX(REPLACE($1, '-', '')), LOWER($2), $3, $4, $5, $6, $7, $8, $9, $10, $11 ) |sql} |> user ->. Caqti_type.unit ;; let insert ?ctx user = Database.exec ?ctx insert_request user let update_request = let open Caqti_request.Infix in {sql| UPDATE user_users SET email = LOWER($2), username = $3, name = $4, given_name = $5, password = $6, status = $7, admin = $8, confirmed = $9, created_at = $10, updated_at = $11 WHERE user_users.uuid = UNHEX(REPLACE($1, '-', '')) |sql} |> user ->. Caqti_type.unit ;; let update ?ctx user = Database.exec ?ctx update_request user let clean_request = let open Caqti_request.Infix in "TRUNCATE user_users" |> Caqti_type.(unit ->. unit) ;; let clean ?ctx () = Database.exec ?ctx clean_request () let register_migration () = MigrationService.register_migration (Migration.migration ()) ;; let register_cleaner () = Cleaner.register_cleaner clean end module MakePostgreSql (MigrationService : Sihl.Contract.Migration.Sig) : Sig = struct let lifecycles = [ Database.lifecycle; MigrationService.lifecycle ] module Migration = struct let create_users_table = Migration.create_step ~label:"create users table" {sql| CREATE TABLE IF NOT EXISTS user_users ( id serial, uuid uuid NOT NULL, email VARCHAR(128) NOT NULL, password VARCHAR(128) NOT NULL, username VARCHAR(128), status VARCHAR(128) NOT NULL, admin BOOLEAN NOT NULL DEFAULT false, confirmed BOOLEAN NOT NULL DEFAULT false, created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (id), UNIQUE (uuid), UNIQUE (email) ) |sql} ;; let add_updated_at_column = Sihl.Database.Migration.create_step ~label:"add updated_at column" {sql| ALTER TABLE user_users ADD COLUMN updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() |sql} ;; let remove_timezone = Sihl.Database.Migration.create_step ~label:"remove timezone info from timestamps" {sql| ALTER TABLE user_users ALTER COLUMN created_at TYPE TIMESTAMP, ALTER COLUMN updated_at TYPE TIMESTAMP |sql} ;; let add_name_columns = Sihl.Database.Migration.create_step ~label:"add name columns" {sql| ALTER TABLE user_users ADD COLUMN name VARCHAR(128) NULL, ADD COLUMN given_name VARCHAR(128) NULL |sql} ;; let migration () = Migration.( empty "user" |> add_step create_users_table |> add_step add_updated_at_column |> add_step remove_timezone |> add_step add_name_columns) ;; end let filter_fragment = {sql| WHERE user_users.email LIKE $1 OR user_users.username LIKE $1 OR user_users.name LIKE $1 OR user_users.given_name LIKE $1 OR user_users.status LIKE $1 |sql} ;; let search_query = {sql| SELECT COUNT(*) OVER() as total, uuid, email, username, name, given_name, password, status, admin, confirmed, created_at, updated_at FROM user_users |sql} ;; let request = Sihl.Database.prepare_search_request ~search_query ~filter_fragment ~sort_by_field:"id" user ;; let search ?ctx sort filter ~limit ~offset = Sihl.Database.run_search_request ?ctx request sort filter ~limit ~offset ;; let get_request = let open Caqti_request.Infix in {sql| SELECT uuid as id, email, username, name, given_name, password, status, admin, confirmed, created_at, updated_at FROM user_users WHERE user_users.uuid = $1::uuid |sql} |> Caqti_type.string ->? user ;; let get ?ctx id = Database.find_opt ?ctx get_request id let get_by_email_request = let open Caqti_request.Infix in {sql| SELECT uuid as id, email, username, name, given_name, password, status, admin, confirmed, created_at, updated_at FROM user_users WHERE LOWER(user_users.email) = LOWER(?) |sql} |> Caqti_type.string ->? user ;; let get_by_email ?ctx email = Database.find_opt ?ctx get_by_email_request email ;; let insert_request = let open Caqti_request.Infix in {sql| INSERT INTO user_users ( uuid, email, username, name, given_name, password, status, admin, confirmed, created_at, updated_at ) VALUES ( $1::uuid, LOWER($2), $3, $4, $5, $6, $7, $8, $9, $10 AT TIME ZONE 'UTC', $11 AT TIME ZONE 'UTC' ) |sql} |> user ->. Caqti_type.unit ;; let insert ?ctx user = Database.exec ?ctx insert_request user let update_request = let open Caqti_request.Infix in {sql| UPDATE user_users SET email = LOWER($2), username = $3, name = $4, given_name = $5, password = $6, status = $7, admin = $8, confirmed = $9, created_at = $10, updated_at = $11 WHERE user_users.uuid = $1::uuid |sql} |> user ->. Caqti_type.unit ;; let update ?ctx user = Database.exec ?ctx update_request user let clean_request = let open Caqti_request.Infix in "TRUNCATE TABLE user_users CASCADE" |> Caqti_type.(unit ->. unit) ;; let clean ?ctx () = Database.exec ?ctx clean_request () let register_migration () = MigrationService.register_migration (Migration.migration ()) ;; let register_cleaner () = Cleaner.register_cleaner clean end
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl-user/src/web.ml
let user_from_token find_user ?ctx ?(key = "user_id") read_token req : Sihl.Contract.User.t option Lwt.t = match Sihl.Web.Request.bearer_token req with | Some token -> let%lwt user_id = read_token ?ctx token ~k:key in (match user_id with | None -> Lwt.return None | Some user_id -> find_user ?ctx user_id) | None -> Lwt.return None ;; let user_from_session find_user ?ctx ?cookie_key ?secret ?(key = "user_id") req : Sihl.Contract.User.t option Lwt.t = match Sihl.Web.Session.find ?cookie_key ?secret key req with | Some user_id -> find_user ?ctx user_id | None -> Lwt.return None ;;
sihl-email
3.0.5
Unknown
Unknown
Unknown
dune
sihl-3.0.5/sihl-user/test/dune
(executables (names password_reset_mariadb password_reset_postgresql user_mariadb user_postgresql) (libraries sihl sihl-user sihl-token alcotest-lwt caqti-driver-mariadb caqti-driver-postgresql) (preprocess (pps lwt_ppx)))
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl-user/test/password_reset.ml
open Alcotest_lwt module Make (UserService : Sihl.Contract.User.Sig) (PasswordResetService : Sihl.Contract.Password_reset.Sig) = struct let reset_password_suceeds _ () = let%lwt () = Sihl.Cleaner.clean_all () in let%lwt _ = UserService.create_user "[email protected]" ~password:"123456789" in let%lwt token = PasswordResetService.create_reset_token ~ctx:[] "[email protected]" |> Lwt.map (Option.to_result ~none:"User with email not found") |> Lwt.map Result.get_ok in let%lwt () = PasswordResetService.reset_password ~ctx:[] ~token "newpassword" "newpassword" |> Lwt.map Result.get_ok in let%lwt _ = UserService.login "[email protected]" ~password:"newpassword" |> Lwt.map Result.get_ok in Lwt.return () ;; let suite = [ ( "password reset" , [ test_case "password reset" `Quick reset_password_suceeds ] ) ] ;; end
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl-user/test/password_reset_mariadb.ml
module TokenService = Sihl_token.JwtMariaDb module PasswordResetService = Sihl_user.Password_reset.MakeMariaDb (TokenService) let services = [ Sihl.Database.Migration.MariaDb.register [] ; TokenService.register () ; Sihl_user.MariaDb.register () ; PasswordResetService.register () ] ;; module Test = Password_reset.Make (Sihl_user.MariaDb) (PasswordResetService) let () = Sihl.Configuration.read_string "DATABASE_URL_TEST_MARIADB" |> Option.value ~default:"mariadb://admin:[email protected]:3306/dev" |> Unix.putenv "DATABASE_URL"; Logs.set_level (Sihl.Log.get_log_level ()); Logs.set_reporter (Sihl.Log.cli_reporter ()); Lwt_main.run (let%lwt _ = Sihl.Container.start_services services in let%lwt () = Sihl.Database.Migration.MariaDb.run_all () in Alcotest_lwt.run "mariadb" Test.suite) ;;
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl-user/test/password_reset_postgresql.ml
module TokenService = Sihl_token.JwtPostgreSql module PasswordResetService = Sihl_user.Password_reset.MakePostgreSql (TokenService) let services = [ Sihl.Database.Migration.PostgreSql.register [] ; TokenService.register () ; Sihl_user.PostgreSql.register () ; PasswordResetService.register () ] ;; module Test = Password_reset.Make (Sihl_user.PostgreSql) (PasswordResetService) let () = Sihl.Configuration.read_string "DATABASE_URL_TEST_POSTGRESQL" |> Option.value ~default:"postgres://admin:[email protected]:5432/dev" |> Unix.putenv "DATABASE_URL"; Logs.set_level (Sihl.Log.get_log_level ()); Logs.set_reporter (Sihl.Log.cli_reporter ()); Lwt_main.run (let%lwt _ = Sihl.Container.start_services services in let%lwt () = Sihl.Database.Migration.PostgreSql.run_all () in Alcotest_lwt.run "postgresql" Test.suite) ;;
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl-user/test/user.ml
open Alcotest_lwt let equal u1 u2 = String.equal (Format.asprintf "%a" Sihl_user.pp u1) (Format.asprintf "%a" Sihl_user.pp u2) ;; let alcotest = Alcotest.testable Sihl_user.pp equal let validate_valid_password _ () = let password = "CD&*BA8txf3mRuGF" in let actual = Sihl_user.validate_new_password ~password ~password_confirmation:password ~password_policy:Sihl_user.default_password_policy in Alcotest.(check (result unit string) "is valid" (Ok ()) actual); Lwt.return () ;; let validate_invalid_password _ () = let password = "123" in let actual = Sihl_user.validate_new_password ~password ~password_confirmation:password ~password_policy:Sihl_user.default_password_policy in Alcotest.( check (result unit string) "is invalid" (Error "Password has to contain at least 8 characters") actual); Lwt.return () ;; module Make (UserService : Sihl.Contract.User.Sig) = struct let json_serialization _ () = let%lwt () = Sihl.Cleaner.clean_all () in let%lwt user = UserService.create_user ~password:"123123123" "[email protected]" in let user_after = user |> Sihl_user.to_yojson |> Sihl_user.of_yojson |> Result.get_ok in let user = Format.asprintf "%a" Sihl_user.pp user in let user_after = Format.asprintf "%a" Sihl_user.pp user_after in Alcotest.(check string "is same user" user_after user); Lwt.return () ;; let update_details _ () = let%lwt () = Sihl.Cleaner.clean_all () in let%lwt user = UserService.create_user ~password:"123123123" "[email protected]" in let%lwt updated_user = UserService.update user ~email:"[email protected]" ~username:"foo" in let actual_email = updated_user.email in let actual_username = updated_user.username in Alcotest.(check string "Has updated email" "[email protected]" actual_email); Alcotest.( check (option string) "Has updated username" (Some "foo") actual_username); Lwt.return () ;; let update_password _ () = let%lwt () = Sihl.Cleaner.clean_all () in let%lwt user = UserService.create_user ~password:"123123123" "[email protected]" in let%lwt _ = UserService.update_password user ~old_password:"123123123" ~new_password:"12345678" ~new_password_confirmation:"12345678" |> Lwt.map Result.get_ok in let%lwt user = UserService.login "[email protected]" ~password:"12345678" |> Lwt.map Result.get_ok in let actual_email = user.email in Alcotest.( check string "Can login with updated password" "[email protected]" actual_email); Lwt.return () ;; let update_password_fails _ () = let%lwt () = Sihl.Cleaner.clean_all () in let%lwt user = UserService.create_user ~password:"123123123" "[email protected]" in let%lwt change_result = UserService.update_password user ~old_password:"wrong_old_password" ~new_password:"12345678" ~new_password_confirmation:"12345678" in Alcotest.( check (result alcotest string) "Can login with updated password" (Error "Invalid current password provided") change_result); Lwt.return () ;; let find_by_email_is_case_insensitive _ () = let%lwt () = Sihl.Cleaner.clean_all () in let%lwt _ = UserService.create_user "[email protected]" ~password:"123123123" in let%lwt _ = UserService.create_user "[email protected]" ~password:"123123123" in let%lwt user = UserService.find_by_email_opt "[email protected]" in match user with | Some _ -> Lwt.return () | None -> Alcotest.fail "expected to find user with email" ;; let filter_users_by_email_returns_single_user _ () = let%lwt () = Sihl.Cleaner.clean_all () in let%lwt _ = UserService.create_user "[email protected]" ~password:"123123123" in let%lwt user = UserService.create_user "[email protected]" ~password:"123123123" in let%lwt _ = UserService.create_user "[email protected]" ~password:"123123123" in let%lwt actual_users, meta = UserService.search ~filter:"%foo%" ~limit:1 () in Alcotest.(check int "search matches 2 users" 2 meta); Alcotest.(check (list alcotest) "has one user" [ user ] actual_users); Lwt.return () ;; let filter_users_by_email_returns_all_users _ () = let%lwt () = Sihl.Cleaner.clean_all () in let%lwt _ = UserService.create_user "[email protected]" ~password:"123123123" in let%lwt user2 = UserService.create_user "[email protected]" ~password:"123123123" in let%lwt user3 = UserService.create_user "[email protected]" ~password:"123123123" in let%lwt _ = UserService.create_user "[email protected]" ~password:"123123123" in let%lwt actual_users, meta = UserService.search ~filter:"%user%" ~limit:2 () in Alcotest.(check int "has correct meta" 3 meta); Alcotest.( check (list alcotest) "has all users" [ user3; user2 ] actual_users); let%lwt actual_users, meta = UserService.search ~filter:"%user%" ~limit:1 ~offset:1 () in Alcotest.(check int "has correct meta" 3 meta); Alcotest.(check (list alcotest) "has one user" [ user2 ] actual_users); Lwt.return () ;; let sort_users _ () = let%lwt () = Sihl.Cleaner.clean_all () in let%lwt user1 = UserService.create_user "[email protected]" ~password:"123123123" in let%lwt user2 = UserService.create_user "[email protected]" ~password:"123123123" in let%lwt user3 = UserService.create_user "[email protected]" ~password:"123123123" in let%lwt actual_users, meta = UserService.search ~sort:`Desc ~filter:"%user%" ~limit:10 () in Alcotest.(check int "has correct meta" 3 meta); Alcotest.( check (list alcotest) "has all users" [ user3; user2; user1 ] actual_users); let%lwt actual_users, meta = UserService.search ~sort:`Asc ~filter:"%user%" ~limit:10 () in Alcotest.(check int "has correct meta" 3 meta); Alcotest.( check (list alcotest) "has all users" [ user1; user2; user3 ] actual_users); Lwt.return () ;; module Web = struct let fake_token = "faketoken" let read_token user_id ?ctx:_ token ~k = if String.equal k "user_id" && String.equal token fake_token then Lwt.return @@ Some user_id else Lwt.return None ;; let find_user id = if String.equal id "1" then Lwt.return @@ Some Sihl.Contract.User. { id = "1" ; email = "[email protected]" ; username = None ; name = None ; given_name = None ; password = "123123" ; status = Active ; admin = false ; confirmed = false ; created_at = Ptime_clock.now () ; updated_at = Ptime_clock.now () } else failwith "Invalid user id provided" ;; let user_from_token _ () = let%lwt () = Sihl.Cleaner.clean_all () in let%lwt user = UserService.create_user "[email protected]" ~password:"123123" in let read_token = read_token user.Sihl_user.id in let token_header = Format.sprintf "Bearer %s" fake_token in let req = Opium.Request.get "/some/path/login" |> Opium.Request.add_header ("authorization", token_header) in let handler req = let%lwt user = UserService.Web.user_from_token read_token req in let email = Option.map (fun user -> user.Sihl_user.email) user in Alcotest.( check (option string) "has same email" (Some "[email protected]") email); Lwt.return @@ Opium.Response.of_plain_text "" in let%lwt _ = handler req in Lwt.return () ;; let user_from_session _ () = let%lwt () = Sihl.Cleaner.clean_all () in let%lwt user = UserService.create_user "[email protected]" ~password:"123123" in let cookie = Sihl.Web.Response.of_plain_text "" |> Sihl.Web.Session.set [ "user_id", user.Sihl_user.id ] |> Sihl.Web.Response.cookie "_session" |> Option.get in let req = Opium.Request.get "/some/path/login" |> Opium.Request.add_cookie cookie.Sihl.Web.Cookie.value in let handler req = let%lwt user = UserService.Web.user_from_session req in let email = Option.map (fun user -> user.Sihl_user.email) user in Alcotest.( check (option string) "has same email" (Some "[email protected]") email); Lwt.return @@ Opium.Response.of_plain_text "" in let%lwt _ = handler req in Lwt.return () ;; end let suite = [ ( "user service" , [ test_case "validate valid password" `Quick validate_valid_password ; test_case "validate invalid password" `Quick validate_invalid_password ; test_case "json serialization" `Quick json_serialization ; test_case "update details" `Quick update_details ; test_case "update password" `Quick update_password ; test_case "update password fails" `Quick update_password_fails ; test_case "find by email is case insensitive" `Quick find_by_email_is_case_insensitive ; test_case "filter users by email returns single user" `Quick filter_users_by_email_returns_single_user ; test_case "filter users by email returns all users" `Quick filter_users_by_email_returns_all_users ; test_case "sort users" `Quick sort_users ] ) ; ( "web" , [ test_case "user from token" `Quick Web.user_from_token ; test_case "user from session" `Quick Web.user_from_session ] ) ] ;; end
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl-user/test/user_mariadb.ml
let services = [ Sihl.Database.Migration.MariaDb.register []; Sihl_user.MariaDb.register () ] ;; module Test = User.Make (Sihl_user.MariaDb) let () = Sihl.Configuration.read_string "DATABASE_URL_TEST_MARIADB" |> Option.value ~default:"mariadb://admin:[email protected]:3306/dev" |> Unix.putenv "DATABASE_URL"; Logs.set_level (Sihl.Log.get_log_level ()); Logs.set_reporter (Sihl.Log.cli_reporter ()); Lwt_main.run (let%lwt _ = Sihl.Container.start_services services in let%lwt () = Sihl.Database.Migration.MariaDb.run_all () in Alcotest_lwt.run "mariadb" Test.suite) ;;
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl-user/test/user_postgresql.ml
let services = [ Sihl.Database.Migration.PostgreSql.register [] ; Sihl_user.PostgreSql.register () ] ;; module Test = User.Make (Sihl_user.PostgreSql) let () = Sihl.Configuration.read_string "DATABASE_URL_TEST_POSTGRESQL" |> Option.value ~default:"postgres://admin:[email protected]:5432/dev" |> Unix.putenv "DATABASE_URL"; Logs.set_level (Sihl.Log.get_log_level ()); Logs.set_reporter (Sihl.Log.cli_reporter ()); Lwt_main.run (let%lwt _ = Sihl.Container.start_services services in let%lwt () = Sihl.Database.Migration.PostgreSql.run_all () in Alcotest_lwt.run "postgresql" Test.suite) ;;
sihl-email
3.0.5
Unknown
Unknown
Unknown
opam
sihl-3.0.5/sihl.opam
# This file is generated by dune, edit dune-project instead opam-version: "2.0" version: "3.0.5" synopsis: "The Sihl web framework" description: """ Sihl is a batteries-included web framework. Thanks to the modular architecture, included batteries can be swapped out easily. Statically typed functional programming with OCaml makes web development fun, fast and safe. Sihl supports PostgreSQL and MariaDB. """ maintainer: ["[email protected]"] authors: ["Josef Erben" "Aron Erben" "Miko Nieminen"] license: "MIT" homepage: "https://github.com/oxidizing/sihl" doc: "https://oxidizing.github.io/sihl/" bug-reports: "https://github.com/oxidizing/sihl/issues" depends: [ "dune" {>= "2.7"} "ocaml" {>= "4.12.0"} "conformist" {>= "0.6.0"} "dune-build-info" {>= "2.8.4"} "tsort" {>= "2.0.0"} "containers" {>= "3.6.1"} "logs" {>= "0.7.0"} "fmt" {>= "0.8.8"} "bos" {>= "0.2.0"} "sexplib" {>= "v0.13.0"} "yojson" {>= "1.7.0"} "ppx_deriving_yojson" {>= "3.5.2"} "tls" {>= "0.11.1"} "ssl" {>= "0.5.9"} "uuidm" {>= "0.9.7"} "lwt_ssl" {>= "1.1.3"} "lwt_ppx" {>= "2.0.1"} "caqti" {>= "1.8.0"} "caqti-lwt" {>= "1.3.0"} "safepass" {>= "3.0"} "jwto" {>= "0.3.0"} "uuidm" {>= "0.9.7"} "ppx_fields_conv" {>= "v0.13.0"} "ppx_sexp_conv" {>= "v0.13.0"} "nocrypto" {>= "0.5.4-2"} "cstruct" {>= "6.0.1"} "opium" {>= "0.20.0"} "cohttp-lwt-unix" {>= "2.5.4" & with-test} "alcotest-lwt" {>= "1.4.0" & with-test} "caqti-driver-postgresql" {>= "1.8.0" & with-test} "caqti-driver-mariadb" {>= "1.8.0" & with-test} "odoc" {with-doc} ] build: [ ["dune" "subst"] {dev} [ "dune" "build" "-p" name "-j" jobs "@install" "@runtest" {with-test} "@doc" {with-doc} ] ] dev-repo: "git+https://github.com/oxidizing/sihl.git"
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl/src/contract_cache.ml
let name = "cache" exception Exception of string module type Sig = sig (* TODO [jerben] Add a non-optional argument to define time to live *) (** [set entry] inserts an [entry] into the cache storage. [entry] is a tuple where the first element is the key and the second element is the value. Since the value is an optional, [set] can be used to remove a value from the store like so: [set ("foo", None)]. If a key exists already, the value is overwritten with the provided value. *) val set : ?ctx:(string * string) list -> string * string option -> unit Lwt.t (** [find key] returns the value that is associated with [key]. *) val find : ?ctx:(string * string) list -> string -> string option Lwt.t val register : unit -> Core_container.Service.t include Core_container.Service.Sig end
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl/src/contract_database.ml
type database = | MariaDb | PostgreSql (* Signature *) let name = "database" exception Exception of string module type Sig = sig (** ['a prepared_search_request] is a prepared SQL statement that can be used to sort, filter and paginate (= search) a collection. *) type 'a prepared_search_request val prepare_requests : string -> string -> string -> string (* Deprecated in 0.6.0 *) [@@deprecated "Use prepare_search_request instead"] (** [prepare_search_request ~search_query ~count_query ~filter_fragment ?sort_by_field type] returns a prepared SQL statement ['a prepared_search_request] by assembling the SQL query from the provided fragments. [search_query] is the [SELECT ... FROM table] part of the query. [count_query] is a query that is executed by Sihl after the search in order to obtain the total number of items in the table. For example [SELECT COUNT(\*\) FROM table]. [filter_fragment] is the fragment that is appended to [search_query] for filtering. Usually you want ot [OR] fields that are often searched for. For example [WHERE table.field1 LIKE $1 OR table.field2 $1 OR table.field3 LIKE $1]. [sort_by_field] is an optional field name that is used for sorting. By default, the field "id" is used. Note that in order to prepare the requests, the sort field has to be known beforehand. If you want to dynamically set the field, you need to write your own query at runtime. [format_filter] is a function applied to the filter keyword before it is passed to the database. By default, a keyword "keyword" is formatted to "%skeyword%s". This might not be what you want performance-wise. If you need full control, pass in the identity function and format the keyword yourself. [type] is the caqti type of an item of the collection. *) val prepare_search_request : search_query:string -> filter_fragment:string -> ?sort_by_field:string -> ?format_filter:(string -> string) -> 'a Caqti_type.t -> 'a prepared_search_request val run_request : (module Caqti_lwt.CONNECTION) -> 'a prepared_search_request -> [< `Asc | `Desc ] -> 'c option -> 'a -> ('b list * int) Lwt.t (* Deprecated in 0.6.0 *) [@@deprecated "Use run_search_request instead"] (** [run_search_request ?ctx prepared_request sort filter ~limit ~offset] runs the [prepared_request] and returns a partial result of the whole stored collection. The second element of the result tuple is the total amount of items in the whole collection. [prepared_request] is the returned prepared request by {!prepare_search_request}. [sort] is the sort order. The field that is sorted by was set by {!prepare_search_request}. [filter] is an optional keyword that is used to filter the collection. If no filter is provided, the collection is not filtered. [offset] is the number of items that the returned partial result is offset by. [limit] is the number of items of the returned partial result. [offset] and [limit] can be used together to implement pagination. An optional [ctx] can be provided. The tuple [("pool", "pool_name")] selects the pool ["pool_name"]. Make sure to initialize the pool with {!add_pool} beforehand. *) val run_search_request : ?ctx:(string * string) list -> 'a prepared_search_request -> [ `Asc | `Desc ] -> string option -> limit:int -> offset:int -> ('a list * int) Lwt.t (** [raise_error err] raises a printable caqti error [err] .*) val raise_error : ('a, Caqti_error.t) Result.t -> 'a (** [fetch_pool ?ctx ()] returns the connection pool referenced in [ctx] or the default connection pool if no connection pool is referenced. An optional [ctx] can be provided. The tuple [("pool", "pool_name")] selects the pool ["pool_name"]. Make sure to initialize the pool with {!add_pool} beforehand. *) val fetch_pool : ?ctx:(string * string) list -> unit -> (Caqti_lwt.connection, Caqti_error.t) Caqti_lwt.Pool.t (** [add_pool ~pool_size name database_url] creates a connection pool with a unique [name]. Creation fails if a pool with the same name was already created to avoid overwriting connection pools accidentally. The connection to the database is established. The pool can be referenced with its [name]. The service context can contain the pool name under the key `pool` to force the usage of a certain pool. A [pool_size] can be provided to define the number of connections that should be kept open. The default is 10. *) val add_pool : ?pool_size:int -> string -> string -> unit (** [find_opt ?ctx request input] runs a caqti [request] where [input] is the input of the caqti request and returns one row or [None]. Returns [None] if no rows are found. Note that the caqti request is only allowed to return one or zero rows, not many. An optional [ctx] can be provided. The tuple [("pool", "pool_name")] selects the pool ["pool_name"]. Make sure to initialize the pool with {!add_pool} beforehand. *) val find_opt : ?ctx:(string * string) list -> ('a, 'b, [< `One | `Zero ]) Caqti_request.t -> 'a -> 'b option Lwt.t (** [find ?ctx request input] runs a caqti [request] where [input] is the input of the caqti request and returns one row. Raises an exception if no row was found. Note that the caqti request is only allowed to return one or zero rows, not many. An optional [ctx] can be provided. The tuple [("pool", "pool_name")] selects the pool ["pool_name"]. Make sure to initialize the pool with {!add_pool} beforehand. *) val find : ?ctx:(string * string) list -> ('a, 'b, [< `One ]) Caqti_request.t -> 'a -> 'b Lwt.t (** [collect ?ctx request input] runs a caqti [request] where [input] is the input of the caqti request and retuns a list of rows. Note that the caqti request is allowed to return one, zero or many rows. An optional [ctx] can be provided. The tuple [("pool", "pool_name")] selects the pool ["pool_name"]. Make sure to initialize the pool with {!add_pool} beforehand. *) val collect : ?ctx:(string * string) list -> ('a, 'b, [< `One | `Zero | `Many ]) Caqti_request.t -> 'a -> 'b list Lwt.t (** [exec ?ctx request input] runs a caqti [request]. Note that the caqti request is not allowed to return any rows. Use {!exec} to run mutations. An optional [ctx] can be provided. The tuple [("pool", "pool_name")] selects the pool ["pool_name"]. Make sure to initialize the pool with {!add_pool} beforehand. *) val exec : ?ctx:(string * string) list -> ('b, unit, [< `Zero ]) Caqti_request.t -> 'b -> unit Lwt.t (** [query ?ctx f] runs the query [f] and returns the result. If the query fails the Lwt.t fails as well. An optional [ctx] can be provided. The tuple [("pool", "pool_name")] selects the pool ["pool_name"]. Make sure to initialize the pool with {!add_pool} beforehand. *) val query : ?ctx:(string * string) list -> (Caqti_lwt.connection -> 'a Lwt.t) -> 'a Lwt.t (** [query' ?ctx f] runs the query [f] and returns the result. Use [query'] instead of {!query} as a shorthand when you have a single caqti request to execute. An optional [ctx] can be provided. The tuple [("pool", "pool_name")] selects the pool ["pool_name"]. Make sure to initialize the pool with {!add_pool} beforehand. *) val query' : ?ctx:(string * string) list -> (Caqti_lwt.connection -> ('a, Caqti_error.t) Result.t Lwt.t) -> 'a Lwt.t (** [transaction ?ctx f] runs the query [f] in a transaction and returns the result. If the query fails the Lwt.t fails as well and the transaction gets rolled back. If the database driver doesn't support transactions, [transaction] gracefully becomes {!query}. An optional [ctx] can be provided. The tuple [("pool", "pool_name")] selects the pool ["pool_name"]. Make sure to initialize the pool with {!add_pool} beforehand. *) val transaction : ?ctx:(string * string) list -> (Caqti_lwt.connection -> 'a Lwt.t) -> 'a Lwt.t (** [transaction' ?ctx f] runs the query [f] in a transaction and returns the result. If the query fails the Lwt.t fails as well and the transaction gets rolled back. If the database driver doesn't support transactions, [transaction'] gracefully becomes {!query'}. An optional [ctx] can be provided. The tuple [("pool", "pool_name")] selects the pool ["pool_name"]. Make sure to initialize the pool with {!add_pool} beforehand. *) val transaction' : ?ctx:(string * string) list -> (Caqti_lwt.connection -> ('a, Caqti_error.t) Result.t Lwt.t) -> 'a Lwt.t val register : unit -> Core_container.Service.t include Core_container.Service.Sig end
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl/src/contract_email.ml
type t = { sender : string ; recipient : string ; subject : string ; text : string ; html : string option ; cc : string list ; bcc : string list } let name = "email" exception Exception of string module type Sig = sig (** [inbox ()] returns the content of the development in-memory mailbox. Intercepted emails land here, they can be used during testing to make sure that certain emails were sent. *) val inbox : unit -> t list (** [clear_inbox ()] removes all the emails from the development in-memory mailbox. A subsequent call on `inbox ()` will return an empty list. *) val clear_inbox : unit -> unit (** [send ?ctx email] sends the email [email]. The returned Lwt.t fulfills if the underlying email transport acknowledges sending. In case of SMTP, this might take a while. *) val send : ?ctx:(string * string) list -> t -> unit Lwt.t (** [bulk_send ?ctx emails] Sends the list of emails [emails]. If sending of one of them fails, the returned Lwt.t fails. *) val bulk_send : ?ctx:(string * string) list -> t list -> unit Lwt.t val register : unit -> Core_container.Service.t include Core_container.Service.Sig end (* Common functions and combinators *) let to_sexp { sender; recipient; subject; text; html; cc; bcc } = let open Sexplib0.Sexp_conv in let open Sexplib0.Sexp in let cc = List (List.cons (Atom "cc") (List.map sexp_of_string cc)) in let bcc = List (List.cons (Atom "bcc") (List.map sexp_of_string bcc)) in List [ List [ Atom "sender"; sexp_of_string sender ] ; List [ Atom "recipient"; sexp_of_string recipient ] ; List [ Atom "subject"; sexp_of_string subject ] ; List [ Atom "text"; sexp_of_string text ] ; List [ Atom "html"; sexp_of_option sexp_of_string html ] ; cc ; bcc ] ;; let pp fmt t = Sexplib0.Sexp.pp_hum fmt (to_sexp t) let of_yojson json = let open Yojson.Safe.Util in try let sender = json |> member "sender" |> to_string in let recipient = json |> member "recipient" |> to_string in let subject = json |> member "subject" |> to_string in let text = json |> member "text" |> to_string in let html = json |> member "html" |> to_string_option in let cc = json |> member "cc" |> to_list |> List.map to_string in let bcc = json |> member "bcc" |> to_list |> List.map to_string in Some { sender; recipient; subject; text; html; cc; bcc } with | _ -> None ;; let to_yojson email = `Assoc [ "sender", `String email.sender ; "recipient", `String email.recipient ; "subject", `String email.subject ; "text", `String email.text ; ( "html" , match email.html with | Some html -> `String html | None -> `Null ) ; "cc", `List (List.map (fun el -> `String el) email.cc) ; "bcc", `List (List.map (fun el -> `String el) email.bcc) ] ;; let set_text text email = { email with text } let set_html html email = { email with html } let create ?html ?(cc = []) ?(bcc = []) ~sender ~recipient ~subject text = { sender; recipient; subject; html; text; cc; bcc } ;;
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl/src/contract_email_template.ml
type t = { id : string ; label : string ; language : string option ; text : string ; html : string option ; created_at : Ptime.t ; updated_at : Ptime.t } let name = "email.template" module type Sig = sig (** [get ?ctx id] returns the email template by [id]. *) val get : ?ctx:(string * string) list -> string -> t option Lwt.t (** [get_by_label ?ctx ?language label] returns the email template by [label] and optional [language]. *) val get_by_label : ?ctx:(string * string) list -> ?language:string -> string -> t option Lwt.t (** [create ?ctx ?id ?html ?language label text] creates an email template with [text] as text email content and a [label]. An optional [html] content can be provided that will be displayed in email clients that support HTML and an optional [language] supports multiple content languages. *) val create : ?ctx:(string * string) list -> ?id:string -> ?html:string -> ?language:string -> label:string -> string -> t Lwt.t (** [update ?ctx template] updates the email [template]. *) val update : ?ctx:(string * string) list -> t -> t Lwt.t val register : unit -> Core_container.Service.t include Core_container.Service.Sig end (* Common *) let to_sexp { id; label; language; text; html; created_at; updated_at } = let open Sexplib0.Sexp_conv in let open Sexplib0.Sexp in List [ List [ Atom "id"; sexp_of_string id ] ; List [ Atom "label"; sexp_of_string label ] ; List [ Atom "language"; sexp_of_option sexp_of_string language ] ; List [ Atom "text"; sexp_of_string text ] ; List [ Atom "html"; sexp_of_option sexp_of_string html ] ; List [ Atom "created_at"; sexp_of_string (Ptime.to_rfc3339 created_at) ] ; List [ Atom "updated_at"; sexp_of_string (Ptime.to_rfc3339 updated_at) ] ] ;; let pp fmt t = Sexplib0.Sexp.pp_hum fmt (to_sexp t) let of_yojson json = let open Yojson.Safe.Util in try let id = json |> member "id" |> to_string in let label = json |> member "label" |> to_string in let language = json |> member "language" |> to_string_option in let text = json |> member "text" |> to_string in let html = json |> member "html" |> to_string_option in let created_at = json |> member "created_at" |> to_string in let updated_at = json |> member "updated_at" |> to_string in match Ptime.of_rfc3339 created_at, Ptime.of_rfc3339 updated_at with | Ok (created_at, _, _), Ok (updated_at, _, _) -> Some { id; label; language; text; html; created_at; updated_at } | _ -> None with | _ -> None ;; let to_yojson template = `Assoc [ "id", `String template.id ; "label", `String template.label ; ( "language" , match template.language with | Some language -> `String language | None -> `Null ) ; "text", `String template.text ; ( "html" , match template.html with | Some html -> `String html | None -> `Null ) ; "created_at", `String (Ptime.to_rfc3339 template.created_at) ; "updated_at", `String (Ptime.to_rfc3339 template.updated_at) ] ;; let set_label label template = { template with label } let set_text text template = { template with text } let set_html html template = { template with html } let set_language language template = { template with language } let replace_element str k v = let regexp = Str.regexp @@ "{" ^ k ^ "}" in Str.global_replace regexp v str ;; let render data text html = let rec render_value data value = match data with | [] -> value | (k, v) :: data -> render_value data @@ replace_element value k v in let text = render_value data text in let html = Option.map (render_value data) html in text, html ;; (* TODO Deprecate in later version *) (* [@@deprecated "Use Sihl_email.Template.render_email_with_data() instead"] *) let email_of_template ?template (email : Contract_email.t) data = let text, html = match template with | Some template -> render data template.text template.html | None -> render data email.text email.html in email |> Contract_email.set_text text |> Contract_email.set_html html |> Lwt.return ;; (* TODO Deprecate in later version *) (* [@@deprecated "Use Sihl_email.Template.render_email() instead"] *) let create_email_of_template ?(cc = []) ?(bcc = []) ~sender ~recipient ~subject template data = (* Create an empty mail, the content is rendered *) let email = Contract_email.create ~cc ~bcc ~sender ~recipient ~subject "" in let text, html = render data template.text template.html in email |> Contract_email.set_text text |> Contract_email.set_html html ;; let render_email_with_data data (email : Contract_email.t) = let text, html = render data email.text email.html in { email with text; html } ;;
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl/src/contract_http.ml
exception Exception of string let name = "http" module type Sig = sig val register : ?not_found_handler: (Opium.Request.t -> (Opium.Headers.t * Opium.Body.t) Lwt.t) -> ?middlewares:Rock.Middleware.t list -> Web.router -> Core_container.Service.t val log_src : Logs.src include Core_container.Service.Sig end
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl/src/contract_migration.ml
type step = { label : string ; statement : string ; check_fk : bool } type steps = step list type t = string * steps let name = "migration" exception Exception of string exception Dirty_migration module type Sig = sig (** [register_migration migration] registers a migration [migration] with the migration service so it can be executed with `run_all`. *) val register_migration : t -> unit (** [register_migrations migrations] registers migrations [migrations] with the migration service so it can be executed with `run_all`. *) val register_migrations : t list -> unit (** [execute ?ctx migrations] runs all migrations [migrations] on the connection pool. *) val execute : ?ctx:(string * string) list -> t list -> unit Lwt.t (** [run_all ?ctx ()] runs all migrations that have been registered on the connection pool. *) val run_all : ?ctx:(string * string) list -> unit -> unit Lwt.t (** [migrations_status ?ctx ?migrations ()] returns a list of migration namespaces and the number of their unapplied migrations. By default, the migrations are checked that have been registered when registering the migration service. Custom [migrations] can be provided to override this behaviour. *) val migrations_status : ?ctx:(string * string) list -> ?migrations:t list -> unit -> (string * int option) list Lwt.t (** [check_migration_status ?ctx ?migrations ()] returns a list of migration namespaces and the number of their unapplied migrations. It does the same thing as {!migration_status} and additionally interprets whether there are too many, not enough or just the right number of migrations applied. If there are too many or not enough migrations applied, a descriptive warning message is logged. *) val check_migrations_status : ?ctx:(string * string) list -> ?migrations:t list -> unit -> unit Lwt.t (** [pending_migrations ?ctx ()] returns a list of migrations that need to be executed in order to have all migrations applied on the connection pool. The returned migration is a tuple [(namespace, number)] where [namespace] is the namespace of the migration and [number] is the number of pending migrations that need to be applied in order to achieve the desired schema version. An empty list means that there are no pending migrations and that the database schema is up-to-date. *) val pending_migrations : ?ctx:(string * string) list -> unit -> (string * int) list Lwt.t val register : t list -> Core_container.Service.t include Core_container.Service.Sig end (* Common *) let to_sexp (namespace, steps) = let open Sexplib0.Sexp_conv in let open Sexplib0.Sexp in let steps = List.map (fun { label; statement; check_fk } -> List [ List [ Atom "label"; sexp_of_string label ] ; List [ Atom "statement"; sexp_of_string statement ] ; List [ Atom "check_fk"; sexp_of_bool check_fk ] ]) steps in List (List.cons (List [ Atom "namespace"; sexp_of_string namespace ]) steps) ;; let pp fmt t = Sexplib0.Sexp.pp_hum fmt (to_sexp t) let empty namespace = namespace, [] let create_step ~label ?(check_fk = true) statement = { label; check_fk; statement } ;; (* Append the migration step to the list of steps *) let add_step step (label, steps) = label, List.concat [ steps; [ step ] ]
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl/src/contract_password_reset.ml
let name = "password.reset" module type Sig = sig (** [create_reset_token ?ctx email] creates and stores a reset token. Returns [None] if there is no user with [email]. The reset token can be used with [reset_password] to set the password without knowing the old password. *) val create_reset_token : ?ctx:(string * string) list -> string -> string option Lwt.t (** [reset_password ?ctx ~token ~password ~password_confirmation] sets the password of a user associated with the reset [token]. *) val reset_password : ?ctx:(string * string) list -> token:string -> string -> string -> (unit, string) Result.t Lwt.t val register : unit -> Core_container.Service.t include Core_container.Service.Sig end
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl/src/contract_queue.ml
exception Exception of string type instance_status = | Pending | Succeeded | Failed | Cancelled [@@deriving show] type instance = { id : string ; name : string ; input : string ; tries : int ; next_run_at : Ptime.t ; max_tries : int ; status : instance_status ; last_error : string option ; last_error_at : Ptime.t option } [@@deriving show] type 'a job = { name : string ; encode : 'a -> string ; decode : string -> ('a, string) Result.t ; handle : 'a -> (unit, string) Result.t Lwt.t ; failed : string -> instance -> unit Lwt.t ; max_tries : int ; retry_delay : Ptime.Span.t } [@@deriving show] type job' = { name : string ; handle : string -> (unit, string) Result.t Lwt.t ; failed : string -> instance -> unit Lwt.t ; max_tries : int ; retry_delay : Ptime.Span.t } [@@deriving show] let hide (job : 'a job) : job' = let handle input = match job.decode input with | Ok decoded -> job.handle decoded | Error msg -> Lwt.return @@ Error msg in { name = job.name ; handle ; failed = job.failed ; max_tries = job.max_tries ; retry_delay = job.retry_delay } ;; let should_run (job_instance : instance) now = let tries = job_instance.tries in let max_tries = job_instance.max_tries in let next_run_at = job_instance.next_run_at in let has_tries_left = tries < max_tries in let is_after_delay = not (Ptime.is_later next_run_at ~than:now) in let is_pending = match job_instance.status with | Pending -> true | _ -> false in is_pending && has_tries_left && is_after_delay ;; let default_tries = 5 let default_retry_delay = Core_time.Span.minutes 1 let default_error_handler msg (instance : instance) = Lwt.return @@ Logs.err (fun m -> m "Job with id '%s' and name '%s' failed for input '%s': %s" instance.id instance.name instance.input msg) ;; let create_job handle ?(max_tries = default_tries) ?(retry_delay = default_retry_delay) ?(failed = default_error_handler) encode decode name = { name; handle; failed; max_tries; retry_delay; encode; decode } ;; (* Service signature *) let name = "queue" module type Sig = sig (** [router ?back scope] returns a router that can be passed to the web server to serve the job queue dashboard. [back] is an optional URL which renders a back button on the dashboard. Use this to provide your admin user a way to easily exit the dashboard. By default, no URL is provided and no back button is shown. [scope] is the URL path under which the dashboard can be accessed. It is common to have some admin UI under [/admin], the job queue dashboard could be available under [/admin/queue]. You can use HTMX by setting [HTMX_SCRIPT_URL] to the URL of the HTMX JavaScript file that is then embedded into the dashboard using the <script> tag in the page body. HTMX is used to add dynamic features such as auto-refresh. The dashboard is perfectly usable without it. By default, HTMX is not used. *) val router : ?back:string -> ?theme:[ `Custom of string | `Light | `Dark ] -> string -> Web.router (** [dispatch ?ctx ?delay input job] queues [job] for later processing and returns [unit Lwt.t] once the job has been queued. An optional [delay] determines the amount of time from now (when dispatch is called) up until the job can be run. If no delay is specified, the job is processed as soon as possible. [input] is the input of the [handle] function which is used for job processing. *) val dispatch : ?ctx:(string * string) list -> ?delay:Ptime.span -> 'a -> 'a job -> unit Lwt.t (** [dispatch_all ?ctx ?delay inputs jobs] queues all [jobs] for later processing and returns [unit Lwt.t] once all the jobs has been queued. The jobs are put onto the queue in reverse order. The first job in the list of [jobs] is put onto the queue last, which means it gets processed first. If the queue backend supports transactions, [dispatch_all] guarantees that either none or all jobs are queued. An optional [delay] determines the amount of time from now (when dispatch is called) up until the jobs can be run. If no delay is specified, the jobs are processed as soon as possible. [inputs] is the input of the [handle] function. It is a list of ['a], one for each ['a job] instance. *) val dispatch_all : ?ctx:(string * string) list -> ?delay:Ptime.span -> 'a list -> 'a job -> unit Lwt.t (** [register_jobs jobs] registers jobs that can be dispatched later on. Only registered jobs can be dispatched. Dispatching a job that was not registered does nothing. *) val register_jobs : job' list -> unit Lwt.t val register : ?jobs:job' list -> unit -> Core_container.Service.t include Core_container.Service.Sig end
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl/src/contract_random.ml
let name = "random" module type Sig = sig (** [base64 n] returns a Base64 encoded string containing [n] random bytes. This does not mean that the string contains [n] characters!. *) val base64 : int -> string (** [bytes n] returns a byte sequence as string with [n] random bytes. In most cases you want to use {!base64} to get a string that can be used safely in most web contexts. This does not mean that the string contains [n] characters!.*) val bytes : int -> string val register : unit -> Core_container.Service.t include Core_container.Service.Sig end
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl/src/contract_schedule.ml
let name = "schedule" module type Sig = sig (** [schedule ?ctx t] runs a schedule [t]. Call the returned function to cancel a schedule. *) val schedule : ?ctx:(string * string) list -> Core_schedule.t -> Core_schedule.stop_schedule val register : ?schedules:Core_schedule.t list -> unit -> Core_container.Service.t include Core_container.Service.Sig end
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl/src/contract_storage.ml
type file = { id : string ; filename : string ; filesize : int ; mime : string } type stored = { file : file ; blob : string } let name = "storage" exception Exception of string module type Sig = sig (** Get the meta data of a complete file. This will not download the content, use [get_data_base64] for that. *) val find_opt : ?ctx:(string * string) list -> string -> stored option Lwt.t val find : ?ctx:(string * string) list -> string -> stored Lwt.t val delete : ?ctx:(string * string) list -> string -> unit Lwt.t (** Upload base64 string as data content for [file]. *) val upload_base64 : ?ctx:(string * string) list -> ?id:string -> file -> string -> stored Lwt.t (** Upload and overwrite base64 strong content of [file]. *) val update_base64 : ?ctx:(string * string) list -> stored -> string -> stored Lwt.t (** Download actual file content for [file]. *) val download_data_base64_opt : ?ctx:(string * string) list -> stored -> string option Lwt.t val download_data_base64 : ?ctx:(string * string) list -> stored -> string Lwt.t val register : unit -> Core_container.Service.t include Core_container.Service.Sig end (* Common *) let file_to_sexp { id; filename; filesize; mime } = let open Sexplib0.Sexp_conv in let open Sexplib0.Sexp in List [ List [ Atom "id"; sexp_of_string id ] ; List [ Atom "filename"; sexp_of_string filename ] ; List [ Atom "filesize"; sexp_of_int filesize ] ; List [ Atom "mime"; sexp_of_string mime ] ] ;; let pp_file fmt t = Sexplib0.Sexp.pp_hum fmt (file_to_sexp t) let set_mime mime file = { file with mime } let set_filesize filesize file = { file with filesize } let set_filename filename file = { file with filename } let set_mime_stored mime stored_file = { stored_file with file = set_mime mime stored_file.file } ;; let set_filesize_stored size stored_file = { stored_file with file = set_filesize size stored_file.file } ;; let set_filename_stored name stored_file = { stored_file with file = set_filename name stored_file.file } ;; let stored_to_sexp { file; _ } = let open Sexplib0.Sexp_conv in let open Sexplib0.Sexp in List [ List [ Atom "file"; file_to_sexp file ] ; List [ Atom "blob"; sexp_of_string "<binary>" ] ] ;; let pp_stored fmt t = Sexplib0.Sexp.pp_hum fmt (stored_to_sexp t)
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl/src/contract_token.ml
exception Exception of string let name = "token" module type Sig = sig (** [create ?ctx ?expires_in ?secret data] returns a token that expires in [expires_in] with the associated data [data]. If no [expires_in] is set, the default is 7 days. An optional secret [secret] can be provided for the token signature, by default `SIHL_SECRET` is used. *) val create : ?ctx:(string * string) list -> ?secret:string -> ?expires_in:Core_time.duration -> (string * string) list -> string Lwt.t (** [read ?ctx ?secret ?force token k] returns the value that is associated with the key [k] in the token [token]. If [force] is set, the value is read and returned even if the token is expired, deactivated and the signature is invalid. If the token is completely invalid and can not be read, no value is returned. An optional secret [secret] can be provided to override the default `SIHL_SECRET`. *) val read : ?ctx:(string * string) list -> ?secret:string -> ?force:unit -> string -> k:string -> string option Lwt.t (** [read_all ?ctx ?secret ?force token] returns all key-value pairs associated with the token [token]. If [force] is set, the values are read and returned even if the token is expired, deactivated and the signature is invalid. If the token is completely invalid and can not be read, no value is returned. An optional secret [secret] can be provided to override the default `SIHL_SECRET`.*) val read_all : ?ctx:(string * string) list -> ?secret:string -> ?force:unit -> string -> (string * string) list option Lwt.t (** [verify ?ctx ?secret token] returns true if the token has a valid structure and the signature is valid, false otherwise. An optional secret [secret] can be provided to override the default `SIHL_SECRET`. *) val verify : ?ctx:(string * string) list -> ?secret:string -> string -> bool Lwt.t (** [deactivate ?ctx token] deactivates the token. Depending on the backend of the token service a blacklist is used to store the token. *) val deactivate : ?ctx:(string * string) list -> string -> unit Lwt.t (** [activate ?ctx token] re-activates the token. Depending on the backend of the token service a blacklist is used to store the token. *) val activate : ?ctx:(string * string) list -> string -> unit Lwt.t (** [is_active ?ctx token] returns true if the token is active, false if the token was deactivated. An expired token or a token that has an invalid signature is not necessarily inactive.*) val is_active : ?ctx:(string * string) list -> string -> bool Lwt.t (** [is_expired ?ctx token] returns true if the token is expired, false otherwise. An optional secret [secret] can be provided to override the default `SIHL_SECRET`. *) val is_expired : ?ctx:(string * string) list -> ?secret:string -> string -> bool Lwt.t (** [is_valid ?ctx token] returns true if the token is not expired, active and the signature is valid and false otherwise. A valid token can safely be used. An optional secret [secret] can be provided to override the default `SIHL_SECRET`. *) val is_valid : ?ctx:(string * string) list -> ?secret:string -> string -> bool Lwt.t val register : unit -> Core_container.Service.t include Core_container.Service.Sig end
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl/src/contract_user.ml
let ptime_to_yojson ptime = `String (Ptime.to_rfc3339 ptime) let ptime_of_yojson json = let open Yojson.Safe.Util in try match json |> to_string |> Ptime.of_rfc3339 with | Ok (ptime, _, _) -> Ok ptime | Error _ -> Error (Format.sprintf "Failed to parse date %s" (Yojson.Safe.to_string json)) with | _ -> Error (Format.sprintf "Failed to parse date %s" (Yojson.Safe.to_string json)) ;; type status = | Active | Inactive [@@deriving yojson, show] let status_of_string = function | "active" -> Ok Active | "inactive" -> Ok Inactive | other -> Error (Format.sprintf "Invalid user status '%s'" other) ;; let status_to_string = function | Active -> "active" | Inactive -> "inactive" ;; type t = { id : string ; email : string ; username : string option ; name : string option ; given_name : string option ; password : string [@opaque] ; status : status ; admin : bool ; confirmed : bool ; created_at : Ptime.t [@to_yojson ptime_to_yojson] [@of_yojson ptime_of_yojson] ; updated_at : Ptime.t [@to_yojson ptime_to_yojson] [@of_yojson ptime_of_yojson] } [@@deriving yojson, show] let equal u1 u2 = CCString.equal u1.id u2.id let show_name user = match user.given_name, user.name with | None, None -> None | Some name, None -> Some name | None, Some name -> Some name | Some given_name, Some family_name -> Some (Format.sprintf "%s %s" given_name family_name) ;; exception Exception of string let name = "user" module type Sig = sig module Web : sig (** [user_from_token ?ctx ?key read_token request] returns the user that is associated to the user id in the [Bearer] token of the [request]. [key] is the key in the token associated with the user id. By default, the value is [user_id]. [read_token] is a function that returns the associated value of [key] in a given token. *) val user_from_token : ?ctx:(string * string) list -> ?key:string -> (?ctx:(string * string) list -> string -> k:string -> string option Lwt.t) -> Rock.Request.t -> t option Lwt.t (** [user_from_session ?ctx ?cookie_key ?secret ?key ?secret request] returns the user that is associated to the user id in the session of the [request]. [cookie_key] is the name/key of the session cookie. By default, the value is [_session]. [secret] is used to verify the signature of the session cookie. By default, [SIHL_SECRET] is used. [key] is the key in the session associated with the user id. By default, the value is [user_id]. *) val user_from_session : ?ctx:(string * string) list -> ?cookie_key:string -> ?secret:string -> ?key:string -> Rock.Request.t -> t option Lwt.t end (** [search ?ctx ?sort ?filter ?limit ?offset ()] returns a list of users that is a partial view on all stored users. [sort] is the default sorting order of the created date. By default, this value is [`Desc]. [filter] is a search keyword that is applied in a best-effort way on user details. The keyword has to occur in only one field (such as email). [limit] is the length of the returned list. [offset] is the pagination offset of the partial view. *) val search : ?ctx:(string * string) list -> ?sort:[ `Desc | `Asc ] -> ?filter:string -> ?limit:int -> ?offset:int -> unit -> (t list * int) Lwt.t (** [find_opt ?ctx id] returns a user with [id]. *) val find_opt : ?ctx:(string * string) list -> string -> t option Lwt.t (** [find ?ctx id] returns a user with [id], [None] otherwise. *) val find : ?ctx:(string * string) list -> string -> t Lwt.t (** [find_by_email ?ctx email] returns a [User.t] if there is a user with email address [email]. The lookup is case-insensitive. Raises an [{!Exception}] otherwise. *) val find_by_email : ?ctx:(string * string) list -> string -> t Lwt.t (** [find_by_email_opt ?ctx email] returns a [User.t] if there is a user with email address [email]. *) val find_by_email_opt : ?ctx:(string * string) list -> string -> t option Lwt.t (** [update_password ?ctx ?password_policy user ~old_password ~new_password ~new_password_confirmation] updates the password of a [user] to [new_password] and returns the user. The [old_password] is the current password that the user has to enter. [new_password] has to equal [new_password_confirmation]. [password_policy] is a function that validates the [new_password] based on some password policy. By default, the policy is that a password has to be at least 8 characters long. *) val update_password : ?ctx:(string * string) list -> ?password_policy:(string -> (unit, string) Result.t) -> t -> old_password:string -> new_password:string -> new_password_confirmation:string -> (t, string) Result.t Lwt.t (** [update ?ctx?email ?username ?name ?given_name ?status user] stores the updated [user] and returns it. *) val update : ?ctx:(string * string) list -> ?email:string -> ?username:string -> ?name:string -> ?given_name:string -> ?status:status -> t -> t Lwt.t val update_details : user:t -> email:string -> username:string option -> t Lwt.t [@@deprecated "Use update() instead"] (** [set_password ?ctx ?policy user ~password ~password_confirmation] overrides the current password of a [user] and returns that user. [password] has to equal [password_confirmation]. [password_policy] is a function that validates the [new_password] based on some password policy. By default, the policy is that a password has to be at least 8 characters long. The current password doesn't have to be provided, therefore you should not expose this function to users but only admins. If you want the user to update their own password use {!update_password} instead. *) val set_password : ?ctx:(string * string) list -> ?password_policy:(string -> (unit, string) Result.t) -> t -> password:string -> password_confirmation:string -> (t, string) Result.t Lwt.t (** [create_user ?ctx ?id ?username ?name ?given_name email password] returns a non-admin user. Note that using [create_user] skips the registration workflow and should only be used with care.*) val create_user : ?ctx:(string * string) list -> ?id:string -> ?username:string -> ?name:string -> ?given_name:string -> password:string -> string -> t Lwt.t (** [create_admin ?ctx ?id ?username ?name ?given_name email password] returns an admin user. *) val create_admin : ?ctx:(string * string) list -> ?id:string -> ?username:string -> ?name:string -> ?given_name:string -> password:string -> string -> t Lwt.t (** [register_user ?ctx ?id ?password_policy ?username ?name ?given_name email password password_confirmation] creates a new user if the password is valid and if the email address was not already registered. Provide [password_policy] to check whether the password fulfills certain criteria. *) val register_user : ?ctx:(string * string) list -> ?id:string -> ?password_policy:(string -> (unit, string) result) -> ?username:string -> ?name:string -> ?given_name:string -> string -> password:string -> password_confirmation:string -> ( t , [ `Already_registered | `Invalid_password_provided of string ] ) Result.t Lwt.t (** [login ?ctx email ~password] returns the user associated with [email] if [password] matches the current password. *) val login : ?ctx:(string * string) list -> string -> password:string -> (t, [ `Does_not_exist | `Incorrect_password ]) Result.t Lwt.t val register : unit -> Core_container.Service.t include Core_container.Service.Sig end let to_sexp { id ; email ; username ; name ; given_name ; status ; admin ; confirmed ; created_at ; updated_at ; _ } = let open Sexplib0.Sexp_conv in let open Sexplib0.Sexp in List [ List [ Atom "id"; sexp_of_string id ] ; List [ Atom "email"; sexp_of_string email ] ; List [ Atom "username"; sexp_of_option sexp_of_string username ] ; List [ Atom "name"; sexp_of_option sexp_of_string name ] ; List [ Atom "given_name"; sexp_of_option sexp_of_string given_name ] ; List [ Atom "password"; sexp_of_string "********" ] ; List [ Atom "status"; sexp_of_string (status_to_string status) ] ; List [ Atom "admin"; sexp_of_bool admin ] ; List [ Atom "confirmed"; sexp_of_bool confirmed ] ; List [ Atom "created_at"; sexp_of_string (Ptime.to_rfc3339 created_at) ] ; List [ Atom "updated_at"; sexp_of_string (Ptime.to_rfc3339 updated_at) ] ] ;; (* Common *) module Hashing = struct let hash ?count plain = match count, not (Core_configuration.is_production ()) with | _, true -> Ok (Bcrypt.hash ~count:4 plain |> Bcrypt.string_of_hash) | Some count, false -> if count < 4 || count > 31 then Error "Password hashing count has to be between 4 and 31" else Ok (Bcrypt.hash ~count plain |> Bcrypt.string_of_hash) | None, false -> Ok (Bcrypt.hash ~count:10 plain |> Bcrypt.string_of_hash) ;; let matches ~hash ~plain = Bcrypt.verify plain (Bcrypt.hash_of_string hash) end let confirm user = { user with confirmed = true } let set_user_password user new_password = let hash = new_password |> Hashing.hash in Result.map (fun hash -> { user with password = hash }) hash ;; let set_user_details user ~email ~username = { user with email; username } let is_admin user = user.admin let is_owner user id = String.equal user.id id let is_confirmed user = user.confirmed let matches_password password user = Hashing.matches ~hash:user.password ~plain:password ;; let default_password_policy password = if String.length password >= 8 then Ok () else Error "Password has to contain at least 8 characters" ;; let validate_new_password ~password ~password_confirmation ~password_policy = let is_same = if String.equal password password_confirmation then Ok () else Error "Password confirmation doesn't match provided password" in let complies_with_policy = password_policy password in match is_same, complies_with_policy with | Ok (), Ok () -> Ok () | Error msg, _ -> Error msg | _, Error msg -> Error msg ;; let validate_change_password user ~old_password ~new_password ~new_password_confirmation ~password_policy = let matches_old_password = match matches_password old_password user with | true -> Ok () | false -> Error "Invalid current password provided" in let new_password_valid = validate_new_password ~password:new_password ~password_confirmation:new_password_confirmation ~password_policy in match matches_old_password, new_password_valid with | Ok (), Ok () -> Ok () | Error msg, _ -> Error msg | _, Error msg -> Error msg ;; let make ?id ~email ~password ~name ~given_name ~username ~admin confirmed = let hash = password |> Hashing.hash in let now = Ptime_clock.now () in Result.map (fun hash -> { id = Option.value id ~default:(Uuidm.v `V4 |> Uuidm.to_string) ; email ; password = hash ; username ; name ; given_name ; admin ; confirmed ; status = Active ; created_at = now ; updated_at = now }) hash ;;
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl/src/core_app.ml
let log_src = Logs.Src.create "sihl.core.app" module Logger = (val Logs.src_log log_src : Logs.LOG) exception Exception of string type t = { services : Core_container.Service.t list ; before_start : unit -> unit Lwt.t ; after_stop : unit -> unit Lwt.t } let empty = { services = [] ; before_start = (fun _ -> Lwt.return ()) ; after_stop = (fun _ -> Lwt.return ()) } ;; let with_services services app = { app with services } let before_start before_start app = { app with before_start } let after_stop after_stop app = { app with after_stop } (* TODO [jerben] 0. store ref to current app and start ctx 1. loop forever (in Lwt_main.run) 2. when command finishes, exit loop 3. when SIGINT comes, exit loop 4. call stop app let stop app ctx = let%lwt () = app.before_stop ctx in print_endline "CORE: Stop services"; let%lwt () = Core_container.stop_services ctx app.services in print_endline "CORE: Services stopped"; app.after_stop ctx *) let run_forever () = let p, _ = Lwt.wait () in p ;; let start_cmd services = Core_command.make ~name:"server" ~description: "Starts the Sihl app including all registered services and the HTTP \ server." (fun _ -> let normal_services = List.filter (fun service -> not (Core_container.Service.server service)) services in let server_services = List.filter Core_container.Service.server services in match server_services with | [ server ] -> let%lwt _ = Core_container.start_services normal_services in let%lwt () = Core_container.Service.start server in run_forever () | [] -> Logger.err (fun m -> m "No 'server' service registered. Make sure that you have one server \ service registered in your 'run.ml' such as a HTTP service"); raise (Exception "No server service registered") | servers -> let names = List.map Core_container.Service.name servers in let names = String.concat ", " names in Logger.err (fun m -> m "Multiple server services registered: '%s', you can only have one \ service registered that is a 'server' service." names); raise (Exception "Multiple server services registered")) ;; let run' ?(commands = []) ?(log_reporter = Core_log.default_reporter) ?args app = (* Set the logger up as first thing so we can log *) Logs.set_reporter log_reporter; Logger.info (fun m -> m "Setting up..."); Logger.debug (fun m -> m "Setup configurations"); let configurations = List.map Core_container.Service.configuration app.services in let () = Core_configuration.load () in let%lwt () = app.before_start () in let configuration_commands = Core_configuration.commands configurations in Logger.debug (fun m -> m "Setup service commands"); let service_commands = app.services |> List.map Core_container.Service.commands |> List.concat in let start_sihl_cmd = start_cmd app.services in let commands = List.concat [ [ start_sihl_cmd ] ; [ Core_random.random_cmd ] ; configuration_commands ; service_commands ; commands ; Gen.commands ] in (* Make sure that the secret is valid *) let _ = Core_configuration.read_secret () in Core_command.run commands args ;; let run ?(commands = []) ?(log_reporter = Core_log.default_reporter) ?args app = Lwt_main.run @@ match args with | Some args -> run' ~commands ~log_reporter ~args app | None -> run' ~commands ~log_reporter app ;;
sihl-email
3.0.5
Unknown
Unknown
Unknown
mli
sihl-3.0.5/sihl/src/core_app.mli
(** A module to create Sihl apps. *) (** An app is a thin convenience layer on top of the service container. It provides hooks that are executed at different stages in the app lifecycle. *) type t (** [empty] returns an app without any services. *) val empty : t (** [with_services services app] adds [services] to an [app]. *) val with_services : Core_container.Service.t list -> t -> t (** [before_start f app] registers a callback f with [app]. The callback is executed before any service is started. This means you must not use any services here! *) val before_start : (unit -> unit Lwt.t) -> t -> t (** [after_stop f app] registers a callback f with [app]. The callback is executed before after services are stopped. This means you must not use any services here! *) val after_stop : (unit -> unit Lwt.t) -> t -> t (** [run ?commands ?log_reporter app] is the main entry point to a Sihl app and starts the command line interface with [commands] merged with the commands provided by services. An optional [log_reporter] can be provided to change the logging behavior. The default log reporter logs to stdout. *) val run : ?commands:Core_command.t list -> ?log_reporter:Logs.reporter -> ?args:string list -> t -> unit (** [run' ?commands ?log_reporter app] is analogous to [run]. It is a helper to be used in tests that need [Lwt.t]. *) val run' : ?commands:Core_command.t list -> ?log_reporter:Logs.reporter -> ?args:string list -> t -> unit Lwt.t val log_src : Logs.src
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl/src/core_cleaner.ml
let registered_cleaners : (?ctx:(string * string) list -> unit -> unit Lwt.t) list ref = ref [] ;; let register_cleaner cleaner = registered_cleaners := List.cons cleaner !registered_cleaners ;; let register_cleaners cleaners = registered_cleaners := List.concat [ !registered_cleaners; cleaners ] ;; let clean_all ?ctx () = let cleaners = !registered_cleaners in let rec clean_repos ?ctx cleaners = match cleaners with | [] -> Lwt.return () | cleaner :: cleaners -> let%lwt () = cleaner ?ctx () in clean_repos cleaners in clean_repos ?ctx cleaners ;;
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl/src/core_command.ml
let log_src = Logs.Src.create "sihl.core.command" module Logs = (val Logs.src_log log_src : Logs.LOG) exception Exception of string type t = { name : string ; usage : string option ; description : string ; dependencies : Core_lifecycle.lifecycle list ; fn : string list -> unit option Lwt.t } let make ~name ?help ~description ?(dependencies = []) fn = { name; usage = help; description; dependencies; fn } ;; let find_command_by_args commands args = let ( let* ) = Option.bind in try let* name = CCList.head_opt args in List.find_opt (fun command -> String.equal command.name name) commands with | _ -> None ;; let print_all commands = let version = match Build_info.V1.version () with | None -> "" | Some version -> Build_info.V1.Version.to_string version in let command_list = commands |> List.map (fun command -> command.name) |> List.sort String.compare |> String.concat "\n" in print_endline @@ Printf.sprintf {| Sihl %s Run one of the following commands with the argument "help" for more information. %s |} version command_list ;; let print_help (command : t) = let usage = Option.map (Printf.sprintf "%s %s" command.name) command.usage in print_endline @@ match usage with | None -> String.concat "\n" [ command.name; command.description ] | Some usage -> String.concat "\n" [ usage; command.description ] ;; let run commands args = let args = match args with | Some args -> args | None -> (try Sys.argv |> Array.to_list |> List.tl with | _ -> []) in let command = find_command_by_args commands args in match command with | Some command -> (* We use the first argument to find the command, the command itself receives the rest arguments. *) let rest_args = try args |> List.tl with | _ -> [] in (match rest_args with | [ "help" ] -> Lwt.return @@ print_help command | rest_args -> let start = Mtime_clock.now () in Lwt.catch (fun () -> let%lwt _ = Lwt_list.iter_s (fun (lifecycle : Core_lifecycle.lifecycle) -> lifecycle.start ()) @@ Core_lifecycle.top_sort_lifecycles command.dependencies in let%lwt result = command.fn rest_args in match result with | Some () -> let stop = Mtime_clock.now () in let span = Mtime.span start stop in print_endline (Format.asprintf "Command '%s' ran successfully in %a" command.name Mtime.Span.pp span); Lwt.return () | None -> Lwt.return @@ print_help command) (fun exn -> let stop = Mtime_clock.now () in let span = Mtime.span start stop in let msg = Printexc.to_string exn in let stack = Printexc.get_backtrace () in print_endline (Format.asprintf "Command '%s' aborted after %a: '%s'" command.name Mtime.Span.pp span msg); print_endline stack; Lwt.return ())) | None -> print_all commands; Lwt.return () ;;
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl/src/core_configuration.ml
let log_src = Logs.Src.create "sihl.core.configuration" module Logs = (val Logs.src_log log_src : Logs.LOG) exception Exception of string type ('ctor, 'ty) schema = (string, 'ctor, 'ty) Conformist.t type data = (string * string) list type config = { name : string ; description : string ; type_ : string ; default : string option } type t = config list let make ?schema () = match schema with | Some schema -> Conformist.fold_left ~f:(fun res field -> let name = Conformist.Field.name field in let description = Option.value ~default:"-" (Conformist.Field.meta field) in let type_ = Conformist.Field.type_ field in let default = Conformist.Field.encode_default field in List.cons { name; description; type_; default = CCList.head_opt default } res) ~init:[] schema | None -> [] ;; let empty = [] (* We assume a total number of initial configurations of 100 *) let cache = Hashtbl.create 100 let memoize f arg = try Hashtbl.find cache arg with | Not_found -> let result = f arg in (* We don't want to fill up the cache with None *) if Option.is_some result then Hashtbl.add cache arg result; result ;; let store data = List.iter (fun (key, value) -> if String.equal "" value then () else ( Hashtbl.replace cache key (Some value); Unix.putenv key value)) data ;; let envs_to_kv envs = envs |> List.map (String.split_on_char '=') |> List.map (function | [] -> "", "" | [ key ] -> key, "" | [ key; value ] -> key, value | key :: values -> key, String.concat "" values) ;; (* .env file handling *) let root_path () = match Sys.getenv_opt "ROOT_PATH" with | None | Some "" -> let markers = [ ".git"; ".hg"; ".svn"; ".bzr"; "_darcs" ] in let rec find_markers path_els = let path = String.concat "/" path_els in if List.exists (fun marker -> Sys.file_exists (path ^ "/" ^ marker)) markers then ( (* Path found => Write it into the env var to "memoize" it *) Unix.putenv "ROOT_PATH" path; Some path) else ( match path_els with | [] -> None | _ -> find_markers @@ CCList.take (List.length path_els - 1) path_els) in find_markers @@ String.split_on_char '/' (Unix.getcwd ()) | Some path -> Some path ;; let env_files_path () = match Sys.getenv_opt "ENV_FILES_PATH" with | None | Some "" -> root_path () | Some path -> Some path ;; let read_env_file () = match env_files_path () with | Some path -> let is_test = match Sys.getenv_opt "SIHL_ENV" with | Some "test" -> true | _ -> false in let filename = path ^ "/" ^ if is_test then ".env.test" else ".env" in let exists = CCIO.File.exists filename in if exists then ( Logs.info (fun m -> m "Env file found: %s" filename); let envs = CCIO.read_lines_l (open_in filename) in Some (envs_to_kv envs)) else ( Logs.info (fun m -> m "Env file not found: %s. Continuing without it." filename); None) | None -> Logs.debug (fun m -> m "No env files directory found, please provide your own directory path \ with environment variable ENV_FILES_PATH if you would like to use env \ files"); None ;; let file_was_read = ref false let load_env_file () = if !file_was_read then (* Nothing to do, the file was read already *) () else ( let file_configuration = read_env_file () in file_was_read := true; store (Option.value file_configuration ~default:[])) ;; let environment_variables () = load_env_file (); Unix.environment () |> Array.to_list |> envs_to_kv ;; let read schema = let data = environment_variables () in let data = List.map (fun (k, v) -> k, [ v ]) data in match Conformist.decode_and_validate schema data with | Ok value -> value | Error errors -> let errors = List.map (fun (field, input, msg) -> match CCList.head_opt input with | None -> Format.sprintf "Failed to read configuration '%s': %s" field msg | Some input -> Format.sprintf "Failed to read configuration '%s' for '%s': %s" input field msg) errors in List.iter (fun error -> Logs.err (fun m -> m "%s" error)) errors; raise (Exception "Invalid configuration provided") ;; let read_string' key = load_env_file (); Sys.getenv_opt key ;; let read_string = memoize read_string' let load () = load_env_file (); match read_string "SIHL_ENV" with | None -> Logs.info (fun m -> m "SIHL_ENV not found. Set it to one of the following values: \ development, production, test"); failwith "SIHL_ENV not found" | Some env -> Logs.info (fun m -> m "SIHL_ENV: %s" env) ;; let is_test () = match read_string "SIHL_ENV" with | Some "test" -> true | _ -> false ;; let is_development () = match read_string "SIHL_ENV" with | Some "development" -> true | _ -> false ;; let is_production () = match read_string "SIHL_ENV" with | Some "production" -> true | _ -> false ;; let read_secret () = match is_production (), read_string "SIHL_SECRET" with | true, Some secret -> (* TODO [jerben] provide proper security policy (entropy or smth) *) if String.length secret > 10 then secret else ( Logs.err (fun m -> m "SIHL_SECRET has to be longer than 10"); failwith "Insecure secret provided") | false, Some secret -> secret | true, None -> Logs.err (fun m -> m "Set SIHL_SECRET before deploying Sihl to production"); failwith "No secret provided" (* In testing and local dev we don't have to use real security *) | false, None -> "secret" ;; let read_int key = match read_string key with | Some value -> int_of_string_opt value | None -> None ;; let read_bool key = match read_string key with | Some "1" | Some "true" | Some "True" -> Some true | Some "0" | Some "false" | Some "False" -> Some false | _ -> None ;; let require schema = read schema |> ignore (* Displaying configurations *) let configuration_to_string (configurations : t) : string = configurations |> List.map (fun { name; description; type_; default } -> match default with | Some default -> Format.sprintf {| %s %s Type: %s Default: %s |} name description type_ default | None -> Format.sprintf {| %s %s Type: %s Required |} name description type_) |> String.concat "" ;; let print_cmd (configurations : t list) : Core_command.t = Core_command.make ~name:"config" ~description:"Prints a list of configurations that are known to Sihl." (fun _ -> configurations |> List.filter (fun configuration -> List.length configuration > 0) |> List.concat |> List.sort (fun c1 c2 -> (* We want to show required configurations first. *) match c1.default, c2.default with | Some _, Some _ -> 0 | Some _, None -> 1 | None, Some _ -> -1 | None, None -> 0) |> configuration_to_string |> print_endline |> Option.some |> Lwt.return) ;; let commands configurations = [ print_cmd configurations ]
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl/src/core_container.ml
include Core_lifecycle module Service = Core_service let start_services = Core_service.start_services let stop_services = Core_service.stop_services
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl/src/core_lifecycle.ml
let log_src = Logs.Src.create "sihl.core.container" let () = Printexc.record_backtrace true module Logs = (val Logs.src_log log_src : Logs.LOG) exception Exception (* TODO [aerben] rename to t *) type lifecycle = { type_name : string ; implementation_name : string ; id : int ; dependencies : unit -> lifecycle list ; start : unit -> unit Lwt.t ; stop : unit -> unit Lwt.t } let counter = ref 0 let create_lifecycle ?(dependencies = fun () -> []) ?(start = fun () -> Lwt.return ()) ?(stop = fun () -> Lwt.return ()) ?implementation_name type_name = (* Give all lifecycles unique names *) counter := !counter + 1; let implementation_name = Option.value implementation_name ~default:type_name in { type_name; implementation_name; id = !counter; dependencies; start; stop } ;; let human_name lifecycle = Format.asprintf "%s %s" lifecycle.type_name lifecycle.implementation_name ;; module Map = Map.Make (Int) let collect_all_lifecycles lifecycles = let rec collect_lifecycles lifecycle = match lifecycle.dependencies () with | [] -> [ lifecycle ] | lifecycles -> List.cons lifecycle (lifecycles |> List.map (fun lifecycle -> collect_lifecycles lifecycle) |> List.concat) in lifecycles |> List.map collect_lifecycles |> List.concat |> List.map (fun lifecycle -> lifecycle.id, lifecycle) |> List.to_seq |> Map.of_seq ;; let top_sort_lifecycles lifecycles = let lifecycles = collect_all_lifecycles lifecycles in let lifecycle_graph = lifecycles |> Map.to_seq |> List.of_seq |> List.map (fun (id, lifecycle) -> let dependencies = lifecycle.dependencies () |> List.map (fun dep -> dep.id) in id, dependencies) in match Tsort.sort lifecycle_graph with | Tsort.Sorted sorted -> sorted |> List.map (fun id -> match Map.find_opt id lifecycles with | Some l -> l | None -> Logs.err (fun m -> m "Failed to sort lifecycles."); raise Exception) | Tsort.ErrorCycle remaining_ids -> let remaining_names = List.map (fun id -> lifecycles |> Map.find_opt id |> Option.map human_name) remaining_ids |> CCList.all_some in let msg = "Cycle detected while starting lifecycles." in let remaining_msg = Option.map (fun r -> Format.asprintf "%s These are the lifecycles after the cycle: %s" msg (String.concat ", " r)) remaining_names in Logs.err (fun m -> m "%s" @@ Option.value remaining_msg ~default:msg); raise Exception ;;
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl/src/core_log.ml
let get_log_level () = match Sys.getenv_opt "LOG_LEVEL" with | Some "debug" -> Some Logs.Debug | Some "error" -> Some Logs.Error | Some "warning" -> Some Logs.Warning | _ -> Some Logs.Info ;; let logs_dir () = match Core_configuration.root_path (), Core_configuration.read_string "LOGS_DIR" with | _, Some logs_dir -> logs_dir | Some root, None -> root ^ "/logs" | None, None -> "logs" ;; let lwt_file_reporter () = let logs_dir = logs_dir () in let buf () = let b = Buffer.create 512 in ( b , fun () -> let m = Buffer.contents b in Buffer.reset b; m ) in let app, app_flush = buf () in let err, err_flush = buf () in let report src level ~over k msgf = let k _ = k () in let write () = let name = match level with | Logs.Error -> logs_dir ^ "/error.log" | _ -> logs_dir ^ "/app.log" in let%lwt log = Lwt_io.open_file ~flags:[ Unix.O_WRONLY; Unix.O_CREAT; Unix.O_APPEND ] ~perm:0o777 ~mode:Lwt_io.Output name in let%lwt () = match level with | Logs.Error -> Lwt_io.write log (err_flush ()) | _ -> Lwt_io.write log (app_flush ()) in Lwt_io.close log in let unblock () = over (); Lwt.return_unit in Lwt.finalize write unblock |> Lwt.ignore_result; msgf @@ fun ?header:_ ?tags:_ fmt -> let now = Ptime_clock.now () |> Ptime.to_rfc3339 in match level with | Logs.Error -> let ppf = Format.formatter_of_buffer err in Format.kfprintf k ppf ("%s [%s]: @[" ^^ fmt ^^ "@]@.") now (Logs.Src.name src) | _ -> let ppf = Format.formatter_of_buffer app in Format.kfprintf k ppf ("%s [%a] [%s]: @[" ^^ fmt ^^ "@]@.") now Logs.pp_level level (Logs.Src.name src) in { Logs.report } ;; let app_style = `Cyan let err_style = `Red let warn_style = `Yellow let info_style = `Blue let debug_style = `Green let source_style = `Magenta let pp_header ~pp_h ppf (l, h) = match l with | Logs.App -> (match h with | None -> () | Some h -> Fmt.pf ppf "[%a] " Fmt.(styled app_style string) h) | Logs.Error -> pp_h ppf err_style (match h with | None -> "ERROR" | Some h -> h) | Logs.Warning -> pp_h ppf warn_style (match h with | None -> "WARNING" | Some h -> h) | Logs.Info -> pp_h ppf info_style (match h with | None -> "INFO" | Some h -> h) | Logs.Debug -> pp_h ppf debug_style (match h with | None -> "DEBUG" | Some h -> h) ;; let pp_source = Fmt.(styled source_style string) let pp_exec_header src = let pp_h ppf style h = let src = Logs.Src.name src in let now = Ptime_clock.now () |> Ptime.to_rfc3339 in Fmt.pf ppf "%s [%a] [%a]: " now Fmt.(styled style string) h pp_source src in pp_header ~pp_h ;; let format_reporter ?(pp_header = pp_exec_header) ?(app = Format.std_formatter) ?(dst = Format.err_formatter) () = let report src level ~over k msgf = let k _ = over (); k () in msgf @@ fun ?header ?tags:_ fmt -> let ppf = if level = Logs.App then app else dst in Format.kfprintf k ppf ("%a@[" ^^ fmt ^^ "@]@.") (pp_header src) (level, header) in { Logs.report } ;; let cli_reporter ?(pp_header = pp_exec_header) ?app ?dst () = Fmt_tty.setup_std_outputs (); format_reporter ~pp_header ?app ?dst () ;; let combine r1 r2 = let report src level ~over k msgf = let v = r1.Logs.report src level ~over:(fun () -> ()) k msgf in r2.Logs.report src level ~over (fun () -> v) msgf in { Logs.report } ;; let default_reporter = Logs.set_level (get_log_level ()); let r1 = lwt_file_reporter () in let r2 = cli_reporter () in combine r1 r2 ;;
sihl-email
3.0.5
Unknown
Unknown
Unknown
mli
sihl-3.0.5/sihl/src/core_log.mli
val get_log_level : unit -> Logs.level option val logs_dir : unit -> string val lwt_file_reporter : unit -> Logs.reporter val format_reporter : ?pp_header: (Logs.src -> Format.formatter -> Logs.level * string option -> unit) -> ?app:Format.formatter -> ?dst:Format.formatter -> unit -> Logs.reporter val cli_reporter : ?pp_header: (Logs.src -> Format.formatter -> Logs.level * string option -> unit) -> ?app:Format.formatter -> ?dst:Format.formatter -> unit -> Logs.reporter val default_reporter : Logs.reporter
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl/src/core_random.ml
let () = Caml.Random.self_init () let rec chars result n = if n > 0 then chars (List.cons (Char.chr (Caml.Random.int 255)) result) (n - 1) else result |> List.to_seq |> String.of_seq ;; let bytes nr = chars [] nr let base64 nr = Base64.encode_string ~alphabet:Base64.uri_safe_alphabet (bytes nr) ;; exception Exception of string let random_cmd = Core_command.make ~name:"random" ~help:"<number of bytes>" ~description: "Generates a random string with the given length in bytes. The string is \ base64 encoded. Use the generated value for SIHL_SECRET." (function | [ n ] -> (match int_of_string_opt n with | Some n -> print_endline @@ base64 n; Lwt.return @@ Some () | None -> failwith "Invalid number of bytes provided") | _ -> Lwt.return None) ;;
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl/src/core_schedule.ml
type scheduled_time = Every of Core_time.duration [@@deriving eq, show] type t = { label : string ; scheduled_time : scheduled_time ; fn : unit -> unit Lwt.t } type stop_schedule = unit -> unit let get_function schedule = schedule.fn let run_in schedule ~now:_ = let scheduled_time = schedule.scheduled_time in match scheduled_time with | Every duration -> duration |> Core_time.duration_to_span |> Ptime.Span.to_float_s ;; let scheduled_function schedule = schedule.fn let create scheduled_time f label = { label; scheduled_time; fn = f } let every_second = Every Core_time.OneSecond let every_hour = Every Core_time.OneHour let log_src = Logs.Src.create "sihl.service.schedule" module Logs = (val Logs.src_log log_src : Logs.LOG) let registered_schedules : t list ref = ref [] let schedule schedule = let should_stop = ref false in let stop_schedule () = should_stop := true in Logs.info (fun m -> m "Schedule %s" schedule.label); let scheduled_function = scheduled_function schedule in let rec loop () = let now = Ptime_clock.now () in let duration = run_in schedule ~now in Logs.debug (fun m -> m "Run schedule %s in %f seconds" schedule.label duration); let%lwt () = Lwt.catch (fun () -> scheduled_function ()) (fun exn -> Logs.err (fun m -> m "Exception caught while running schedule, this is a bug in your \ scheduled function. %s" (Printexc.to_string exn)); Lwt.return ()) in let%lwt () = Lwt_unix.sleep duration in if !should_stop then ( let () = Logs.debug (fun m -> m "Stop schedule %s" schedule.label) in Lwt.return ()) else loop () in loop () |> ignore; stop_schedule ;; let start ctx = List.iter (fun s -> schedule s ()) !registered_schedules; Lwt.return ctx ;; let stop _ = Lwt.return () let lifecycle = Core_container.create_lifecycle "schedule" ~start ~stop let register schedules = registered_schedules := schedules; Core_container.Service.create lifecycle ;;
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl/src/core_service.ml
module type Sig = sig val lifecycle : Core_lifecycle.lifecycle end type t = { lifecycle : Core_lifecycle.lifecycle ; configuration : Core_configuration.t ; commands : Core_command.t list ; server : bool } let commands (service : t) = service.commands let configuration service = service.configuration let create ?(commands = []) ?(configuration = Core_configuration.empty) ?(server = false) lifecycle = { lifecycle; configuration; commands; server } ;; let server t = t.server let start t = t.lifecycle.start () let stop t = t.lifecycle.stop () let id t = t.lifecycle.id let name t = Core_lifecycle.human_name t.lifecycle let start_services services = Logs.info (fun m -> m "Starting..."); let lifecycles = List.map (fun service -> service.lifecycle) services in let lifecycles = lifecycles |> Core_lifecycle.top_sort_lifecycles in let%lwt () = Lwt_list.iter_s (fun (lifecycle : Core_lifecycle.lifecycle) -> Logs.debug (fun m -> m "Starting service: %s" @@ Core_lifecycle.human_name lifecycle); lifecycle.start ()) lifecycles in Logs.info (fun m -> m "All services started."); Lwt.return lifecycles ;; let stop_services services = Logs.info (fun m -> m "Stopping..."); let lifecycles = List.map (fun service -> service.lifecycle) services in let lifecycles = lifecycles |> Core_lifecycle.top_sort_lifecycles in let%lwt () = Lwt_list.iter_s (fun (lifecycle : Core_lifecycle.lifecycle) -> Logs.debug (fun m -> m "Stopping service: %s" @@ Core_lifecycle.human_name lifecycle); lifecycle.stop ()) lifecycles in Logs.info (fun m -> m "Stopped, Good Bye!"); Lwt.return () ;;
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl/src/core_time.ml
type duration = | OneSecond | OneMinute | TenMinutes | OneHour | OneDay | OneWeek | OneMonth | OneYear [@@deriving yojson, show, eq] let duration_to_span duration = let duration_s = match duration with | OneSecond -> 1. | OneMinute -> 60. | TenMinutes -> 60. *. 10. | OneHour -> 60. *. 60. | OneDay -> 60. *. 60. *. 24. | OneWeek -> 60. *. 60. *. 24. *. 7. | OneMonth -> 60. *. 60. *. 24. *. 30. | OneYear -> 60. *. 60. *. 24. *. 365. in match Ptime.of_float_s duration_s with | Some ptime -> Ptime.to_span ptime | None -> failwith "Invalid ptime provided" ;; let date_from_now now duration = match duration |> duration_to_span |> Ptime.add_span now with | Some expiration_date -> expiration_date | None -> failwith "Could not determine date in the future" ;; let ptime_to_yojson ptime = `String (Ptime.to_rfc3339 ptime) let ptime_of_yojson yojson = match yojson |> Yojson.Safe.to_string |> Ptime.of_rfc3339 |> Ptime.rfc3339_error_to_msg with | Ok (ptime, _, _) -> Ok ptime | Error (`Msg msg) -> Error msg ;; let ptime_of_date_string date = let date = date |> String.split_on_char '-' |> List.map int_of_string_opt |> List.map (Option.to_result ~none: "Invalid date string provided, make sure that year, month and \ date are ints") |> List.fold_left (fun result item -> match item with | Ok item -> Result.map (List.cons item) result | Error msg -> Error msg) (Ok []) |> Result.map List.rev in match date with | Ok [ year; month; day ] -> Ptime.of_date (year, month, day) |> Option.to_result ~none:"Invalid date provided, only format 1990-12-01 is accepted" | Ok _ -> Error "Invalid date provided, only format 1990-12-01 is accepted" | Error msg -> Error msg ;; let ptime_to_date_string ptime = let year, month, day = Ptime.to_date ptime in let month = if month < 10 then Printf.sprintf "0%d" month else Printf.sprintf "%d" month in let day = if day < 10 then Printf.sprintf "0%d" day else Printf.sprintf "%d" day in Printf.sprintf "%d-%s-%s" year month day ;; module Span = struct let seconds n = Ptime.Span.of_int_s n let minutes n = Ptime.Span.of_int_s (60 * n) let hours n = Ptime.Span.of_int_s (60 * 60 * n) let days n = Ptime.Span.of_int_s (24 * 60 * 60 * n) let weeks n = Ptime.Span.of_int_s (7 * 24 * 60 * 60 * n) end
sihl-email
3.0.5
Unknown
Unknown
Unknown
mli
sihl-3.0.5/sihl/src/core_time.mli
type duration = | OneSecond | OneMinute | TenMinutes | OneHour | OneDay | OneWeek | OneMonth | OneYear [@@ocaml.deprecation "Sihl.Time.duration is deprecated, use [Sihl.Time.Span] instead"] val duration_to_yojson : duration -> Yojson.Safe.t [@@ocaml.deprecation "Sihl.Time.duration is deprecated, use [Sihl.Time.Span] instead"] val duration_of_yojson : Yojson.Safe.t -> duration Ppx_deriving_yojson_runtime.error_or [@@ocaml.deprecation "Sihl.Time.duration is deprecated, use [Sihl.Time.Span] instead"] val pp_duration : Format.formatter -> duration -> unit [@@ocaml.deprecation "Sihl.Time.duration is deprecated, use [Sihl.Time.Span] instead"] val show_duration : duration -> string [@@ocaml.deprecation "Sihl.Time.duration is deprecated, use [Sihl.Time.Span] instead"] val equal_duration : duration -> duration -> bool [@@ocaml.deprecation "Sihl.Time.duration is deprecated, use [Sihl.Time.Span] instead"] val duration_to_span : duration -> Ptime.span [@@ocaml.deprecation "Sihl.Time.duration is deprecated, use [Sihl.Time.Span] instead"] val date_from_now : Ptime.t -> duration -> Ptime.t [@@ocaml.deprecation "Sihl.Time.duration is deprecated, use [Sihl.Time.Span] instead"] val ptime_to_yojson : Ptime.t -> [> `String of string ] [@@ocaml.deprecation "Sihl.Time.duration is deprecated, use [Sihl.Time.Span] instead"] val ptime_of_yojson : Yojson.Safe.t -> (Ptime.t, string) result [@@ocaml.deprecation "Sihl.Time.ptime* are deprecated"] val ptime_of_date_string : string -> (Ptime.t, string) result [@@ocaml.deprecation "Sihl.Time.ptime* are deprecated"] val ptime_to_date_string : Ptime.t -> string [@@ocaml.deprecation "Sihl.Time.ptime* are deprecated"] module Span : sig val seconds : int -> Ptime.span val minutes : int -> Ptime.span val hours : int -> Ptime.span val days : int -> Ptime.span val weeks : int -> Ptime.span end
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl/src/database.ml
include Contract_database let log_src = Logs.Src.create "sihl.service.database" module Logs = (val Logs.src_log log_src : Logs.LOG) let main_pool_ref : (Caqti_lwt.connection, Caqti_error.t) Caqti_lwt.Pool.t option ref = ref None ;; let pools : (string, (Caqti_lwt.connection, Caqti_error.t) Caqti_lwt.Pool.t) Hashtbl.t = Hashtbl.create 100 ;; type 'a prepared_search_request = { asc_request : (int * int, int * 'a, [ `Many | `One | `Zero ]) Caqti_request.t ; desc_request : (int * int, int * 'a, [ `Many | `One | `Zero ]) Caqti_request.t ; filter_asc_request : (string * int * int, int * 'a, [ `Many | `One | `Zero ]) Caqti_request.t ; filter_desc_request : (string * int * int, int * 'a, [ `Many | `One | `Zero ]) Caqti_request.t ; format_filter : string -> string } let prepare_requests _ _ _ = failwith "prepare_requests deprecated" let default_format_filter keyword = "%" ^ keyword ^ "%" let prepare_search_request ~search_query ~filter_fragment ?(sort_by_field = "id") ?(format_filter = default_format_filter) output_type : 'a prepared_search_request = let open Caqti_request.Infix in let output_type = Caqti_type.(tup2 int output_type) in let asc_request = let input_type = Caqti_type.(tup2 int int) in let query = Printf.sprintf "%s ORDER BY %s ASC %s" search_query sort_by_field "LIMIT $1 OFFSET $2" in query |> input_type ->* output_type in let desc_request = let input_type = Caqti_type.(tup2 int int) in let query = Printf.sprintf "%s ORDER BY %s DESC %s" search_query sort_by_field "LIMIT $1 OFFSET $2" in query |> input_type ->* output_type in let filter_asc_request = let input_type = Caqti_type.(tup3 string int int) in let query = Printf.sprintf "%s %s ORDER BY %s ASC %s" search_query filter_fragment sort_by_field "LIMIT $2 OFFSET $3" in query |> input_type ->* output_type in let filter_desc_request = let input_type = Caqti_type.(tup3 string int int) in let query = Printf.sprintf "%s %s ORDER BY %s DESC %s" search_query filter_fragment sort_by_field "LIMIT $2 OFFSET $3" in query |> input_type ->* output_type in { asc_request ; desc_request ; filter_asc_request ; filter_desc_request ; format_filter } ;; let run_request _ _ _ _ _ = failwith "prepare_requests deprecated" type config = { url : string ; pool_size : int option ; skip_default_pool_creation : bool option ; choose_pool : string option } let config url pool_size skip_default_pool_creation choose_pool = { url; pool_size; skip_default_pool_creation; choose_pool } ;; let schema = let open Conformist in make [ string ~meta: "The database connection url. This is the only string that Sihl \ needs to connect to a database." "DATABASE_URL" ; optional ~meta: "The amount of connections in the database connection pool that Sihl \ manages. If the number is too high, the server might struggle. If \ the number is too low, your Sihl app performs badly. This can be \ configured using DATABASE_POOL_SIZE and the default is 5." (int ~default:5 "DATABASE_POOL_SIZE") ; optional ~meta: "By default, Sihl assumes one database connection pool to connect to \ one default application database. This value can be set to [true] \ to skip the creation of the default connection pool, which is \ configured using env variables. This is useful if an application \ uses multiple databases. By default, the value is [false]." (bool ~default:false "DATABASE_SKIP_DEFAULT_POOL_CREATION") ; optional ~meta: "The database connection pool name that should be used by default. \ The main pool is used if no value is set. This value can be \ overriden by using the pool name in the service context." (string "DATABASE_CHOOSE_POOL") ] config ;; let print_pool_usage pool = let n_connections = Caqti_lwt.Pool.size pool in let max_connections = Option.value (Core_configuration.read schema).pool_size ~default:10 in Logs.debug (fun m -> m "Pool usage: %i/%i" n_connections max_connections) ;; let fetch_pool ?(ctx = []) () = let chosen_pool_name_ctx = CCList.assoc_opt ~eq:String.equal "pool" ctx in let chosen_pool_name_env = (Core_configuration.read schema).choose_pool in let chosen_pool_name = match chosen_pool_name_ctx, chosen_pool_name_env with | Some chosen_pool_name, _ -> Some chosen_pool_name | None, Some chosen_pool_name -> Some chosen_pool_name | None, None -> None in let chosen_pool = Option.bind chosen_pool_name (Hashtbl.find_opt pools) in match chosen_pool, !main_pool_ref with | Some pool, _ -> pool | None, Some pool -> Logs.debug (fun m -> m "Skipping pool creation, re-using existing pool"); pool | None, None -> if Option.value (Core_configuration.read schema).skip_default_pool_creation ~default:false then Logs.warn (fun m -> m "DATABASE_SKIP_DEFAULT_POOL_CREATION was set to true, but no pool \ was defined for querying."); let pool_size = Option.value (Core_configuration.read schema).pool_size ~default:10 in Logs.info (fun m -> m "Create pool with size %i" pool_size); (Core_configuration.read schema).url |> Uri.of_string |> Caqti_lwt.connect_pool ~max_size:pool_size |> (function | Ok pool -> main_pool_ref := Some pool; pool | Error err -> let msg = "Failed to connect to DB pool" in Logs.err (fun m -> m "%s %s" msg (Caqti_error.show err)); raise (Contract_database.Exception ("Failed to create pool: " ^ msg))) ;; let add_pool ?(pool_size = 10) name database_url = database_url |> Uri.of_string |> Caqti_lwt.connect_pool ~max_size:pool_size |> function | Ok pool -> if Option.is_some (Hashtbl.find_opt pools name) then ( let msg = Format.sprintf "Connection pool with name '%s' exists already" name in Logs.err (fun m -> m "%s" msg); raise (Contract_database.Exception ("Failed to create pool: " ^ msg))) else Hashtbl.add pools name pool | Error err -> let msg = "Failed to connect to DB pool" in Logs.err (fun m -> m "%s %s" msg (Caqti_error.show err)); raise (Contract_database.Exception ("Failed to create pool: " ^ msg)) ;; let raise_error err = match err with | Error err -> raise @@ Contract_database.Exception (Caqti_error.show err) | Ok result -> result ;; let transaction ?ctx f = let pool = fetch_pool ?ctx () in print_pool_usage pool; let%lwt result = Caqti_lwt.Pool.use (fun connection -> Logs.debug (fun m -> m "Fetched connection from pool"); let (module Connection : Caqti_lwt.CONNECTION) = connection in let%lwt start_result = Connection.start () in match start_result with | Error msg -> Logs.debug (fun m -> m "Failed to start transaction: %s" (Caqti_error.show msg)); Lwt.return @@ Error msg | Ok () -> Logs.debug (fun m -> m "Started transaction"); Lwt.catch (fun () -> let%lwt result = f connection in let%lwt commit_result = Connection.commit () in match commit_result with | Ok () -> Logs.debug (fun m -> m "Successfully committed transaction"); Lwt.return @@ Ok result | Error error -> Logs.err (fun m -> m "Failed to commit transaction: %s" (Caqti_error.show error)); Lwt.fail @@ Contract_database.Exception "Failed to commit transaction") (fun e -> let%lwt rollback_result = Connection.rollback () in match rollback_result with | Ok () -> Logs.debug (fun m -> m "Successfully rolled back transaction"); Lwt.fail e | Error error -> Logs.err (fun m -> m "Failed to rollback transaction: %s" (Caqti_error.show error)); Lwt.fail @@ Contract_database.Exception "Failed to rollback transaction")) pool in match result with | Ok result -> Lwt.return result | Error error -> let msg = Caqti_error.show error in Logs.err (fun m -> m "%s" msg); Lwt.fail (Contract_database.Exception msg) ;; let transaction' ?ctx f = transaction ?ctx f |> Lwt.map raise_error let run_search_request ?ctx (r : 'a prepared_search_request) (sort : [ `Asc | `Desc ]) (filter : string option) ~(limit : int) ~(offset : int) = transaction' ?ctx (fun connection -> let module Connection = (val connection : Caqti_lwt.CONNECTION) in let%lwt result = match sort, filter with | `Asc, None -> Connection.collect_list r.asc_request (limit, offset) | `Desc, None -> Connection.collect_list r.desc_request (limit, offset) | `Asc, Some filter -> Connection.collect_list r.filter_asc_request (r.format_filter filter, limit, offset) | `Desc, Some filter -> Connection.collect_list r.filter_desc_request (r.format_filter filter, limit, offset) in let things = Result.map (List.map snd) result in let total = Result.map (fun e -> e |> List.map fst |> CCList.head_opt |> Option.value ~default:0) result in CCResult.both things total |> Lwt.return) ;; let query ?ctx f = let pool = fetch_pool ?ctx () in print_pool_usage pool; let%lwt result = Caqti_lwt.Pool.use (fun connection -> let module Connection = (val connection : Caqti_lwt.CONNECTION) in f connection |> Lwt.map Result.ok) pool in match result with | Ok result -> Lwt.return result | Error error -> let msg = Caqti_error.show error in Logs.err (fun m -> m "%s" msg); Lwt.fail (Contract_database.Exception msg) ;; let query' ?ctx f = query ?ctx f |> Lwt.map raise_error let find_opt ?ctx request input = query' ?ctx (fun connection -> let module Connection = (val connection : Caqti_lwt.CONNECTION) in Connection.find_opt request input) ;; let find ?ctx request input = query' ?ctx (fun connection -> let module Connection = (val connection : Caqti_lwt.CONNECTION) in Connection.find request input) ;; let collect ?ctx request input = query' ?ctx (fun connection -> let module Connection = (val connection : Caqti_lwt.CONNECTION) in Connection.collect_list request input) ;; let exec ?ctx request input = query' ?ctx (fun connection -> let module Connection = (val connection : Caqti_lwt.CONNECTION) in Connection.exec request input) ;; let used_database () = let host = (Core_configuration.read schema).url |> Uri.of_string |> Uri.host in match host with | Some "mariadb" -> Some Contract_database.MariaDb | Some "mysql" -> Some Contract_database.MariaDb | Some "postgresql" | Some "postgres" | Some "pg" -> Some Contract_database.PostgreSql | Some not_supported -> Logs.warn (fun m -> m "Unsupported database %s found" not_supported); None | None -> None ;; (* Service lifecycle *) let start () = let skip_default_pool_creation = Option.value (Core_configuration.read schema).skip_default_pool_creation ~default:false in if skip_default_pool_creation then Lwt.return () else ( (* Make sure the default database is online when starting service. *) let _ = fetch_pool () in Lwt.return ()) ;; let stop () = Lwt.return () let lifecycle = Core_container.create_lifecycle Contract_database.name ~start ~stop ;; let register () = let configuration = Core_configuration.make ~schema () in Core_container.Service.create ~configuration lifecycle ;;
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl/src/database_migration.ml
include Contract_migration let log_src = Logs.Src.create ("sihl.service." ^ Contract_migration.name) module Logs = (val Logs.src_log log_src : Logs.LOG) module Map = Map.Make (String) let registered_migrations : Contract_migration.steps Map.t ref = ref Map.empty module Make (Repo : Database_migration_repo.Sig) : Contract_migration.Sig = struct type config = { migration_state_table : string option } let config migration_state_table = { migration_state_table } let schema = let open Conformist in make [ optional (string ~default:"core_migration_state" "MIGRATION_STATE_TABLE") ] config ;; let table () = Option.value ~default:"core_migration_state" (Core_configuration.read schema).migration_state_table ;; let setup ?ctx () = Logs.debug (fun m -> m "Setting up table if not exists"); Repo.create_table_if_not_exists ?ctx (table ()) ;; let has ?ctx namespace = Repo.get ?ctx (table ()) ~namespace |> Lwt.map Option.is_some ;; let get ?ctx namespace = let%lwt state = Repo.get ?ctx (table ()) ~namespace in Lwt.return @@ match state with | Some state -> state | None -> raise (Contract_migration.Exception (Printf.sprintf "Could not get migration state for %s" namespace)) ;; let upsert ?ctx state = Repo.upsert ?ctx (table ()) state let mark_dirty ?ctx namespace = let%lwt state = get ?ctx namespace in let dirty_state = Repo.Migration.mark_dirty state in let%lwt () = upsert ?ctx dirty_state in Lwt.return dirty_state ;; let mark_clean ?ctx namespace = let%lwt state = get ?ctx namespace in let clean_state = Repo.Migration.mark_clean state in let%lwt () = upsert ?ctx clean_state in Lwt.return clean_state ;; let increment ?ctx namespace = let%lwt state = get ?ctx namespace in let updated_state = Repo.Migration.increment state in let%lwt () = upsert ?ctx updated_state in Lwt.return updated_state ;; let register_migration migration = let label, _ = migration in let found = Map.find_opt label !registered_migrations in match found with | Some _ -> Logs.debug (fun m -> m "Found duplicate migration '%s', ignoring it" label) | None -> registered_migrations := Map.add label (snd migration) !registered_migrations ;; let register_migrations migrations = List.iter register_migration migrations let set_fk_check_request = let open Caqti_request.Infix in "SET FOREIGN_KEY_CHECKS = ?" |> Caqti_type.(bool ->. unit) ;; let with_disabled_fk_check ?ctx f = Database.query ?ctx (fun connection -> let module Connection = (val connection : Caqti_lwt.CONNECTION) in let%lwt () = Connection.exec set_fk_check_request false |> Lwt.map Database.raise_error in Lwt.finalize (fun () -> f connection) (fun () -> Connection.exec set_fk_check_request true |> Lwt.map Database.raise_error)) ;; let execute_steps ?ctx migration = let open Caqti_request.Infix in let namespace, steps = migration in let rec run steps = match steps with | [] -> Lwt.return () | Contract_migration.{ label; statement; check_fk = true } :: steps -> Logs.debug (fun m -> m "Running %s" label); let query (module Connection : Caqti_lwt.CONNECTION) = let req = statement |> Caqti_type.(unit ->. unit) ~oneshot:true in Connection.exec req () |> Lwt.map Database.raise_error in let%lwt () = Database.query ?ctx query in Logs.debug (fun m -> m "Ran %s" label); let%lwt _ = increment ?ctx namespace in run steps | { label; statement; check_fk = false } :: steps -> let%lwt () = with_disabled_fk_check ?ctx (fun connection -> Logs.debug (fun m -> m "Running %s without fk checks" label); let query (module Connection : Caqti_lwt.CONNECTION) = let req = statement |> Caqti_type.(unit ->. unit) ~oneshot:true in Connection.exec req () |> Lwt.map Database.raise_error in query connection) in Logs.debug (fun m -> m "Ran %s" label); let%lwt _ = increment ?ctx namespace in run steps in let () = match List.length steps with | 0 -> Logs.debug (fun m -> m "No migrations to apply for %s" namespace) | n -> Logs.debug (fun m -> m "Applying %i migrations for %s" n namespace) in run steps ;; let execute_migration ?ctx migration = let namespace, _ = migration in let%lwt () = setup ?ctx () in let%lwt has_state = has ?ctx namespace in let%lwt state = if has_state then ( let%lwt state = get ?ctx namespace in if Repo.Migration.dirty state then ( Logs.err (fun m -> m "Dirty migration found for %s, this has to be fixed manually" namespace); Logs.info (fun m -> m "Set the column 'dirty' from 1/true to 0/false after you have \ fixed the database state."); raise Contract_migration.Dirty_migration) else mark_dirty ?ctx namespace) else ( Logs.debug (fun m -> m "Setting up table for %s" namespace); let state = Repo.Migration.create ~namespace in let%lwt () = upsert ?ctx state in Lwt.return state) in let migration_to_apply = Repo.Migration.steps_to_apply migration state in let n_migrations = List.length (snd migration_to_apply) in if n_migrations > 0 then Logs.info (fun m -> m "Executing %d migrations for '%s'..." (List.length (snd migration_to_apply)) namespace) else Logs.info (fun m -> m "No migrations to execute for '%s'" namespace); let%lwt () = Lwt.catch (fun () -> execute_steps ?ctx migration_to_apply) (fun exn -> let err = Printexc.to_string exn in Logs.err (fun m -> m "Error while running migration '%a': %s" pp migration err); raise (Contract_migration.Exception err)) in let%lwt _ = mark_clean ?ctx namespace in Lwt.return () ;; let execute ?ctx migrations = let n = List.length migrations in if n > 0 then Logs.info (fun m -> m "Looking at %i migrations" (List.length migrations)) else Logs.info (fun m -> m "No migrations to execute"); let rec run migrations = match migrations with | [] -> Lwt.return () | migration :: migrations -> let%lwt () = execute_migration ?ctx migration in run migrations in run migrations ;; let run_all ?ctx () = let steps = !registered_migrations |> Map.to_seq |> List.of_seq in execute ?ctx steps ;; let migrations_status ?ctx ?migrations () = let migrations_to_check = match migrations with | Some migrations -> migrations |> List.to_seq |> Map.of_seq | None -> !registered_migrations in let%lwt migrations_states = Repo.get_all ?ctx (table ()) in let migration_states_namespaces = migrations_states |> List.map (fun migration_state -> migration_state.Database_migration_repo.Migration.namespace) in let registered_migrations_namespaces = Map.to_seq migrations_to_check |> List.of_seq |> List.map fst in let namespaces_to_check = List.concat [ migration_states_namespaces; registered_migrations_namespaces ] |> CCList.uniq ~eq:String.equal in Lwt.return @@ List.map (fun namespace -> let migrations = Map.find_opt namespace migrations_to_check in let migration_state = List.find_opt (fun migration_state -> String.equal migration_state.Database_migration_repo.Migration.namespace namespace) migrations_states in match migrations, migration_state with | None, None -> namespace, None | None, Some migration_state -> ( namespace , Some (-migration_state.Database_migration_repo.Migration.version) ) | Some migrations, Some migration_state -> let unapplied_migrations_count = List.length migrations - migration_state.Database_migration_repo.Migration.version in namespace, Some unapplied_migrations_count | Some migrations, None -> namespace, Some (List.length migrations)) namespaces_to_check ;; let pending_migrations ?ctx () = let%lwt unapplied = migrations_status ?ctx () in let rec find_pending result = function | (namespace, Some n) :: xs -> if n > 0 then ( let result = List.cons (namespace, n) result in find_pending result xs) else find_pending result xs | (_, None) :: xs -> find_pending result xs | [] -> result in Lwt.return @@ find_pending [] unapplied ;; let check_migrations_status ?ctx ?migrations () = let%lwt unapplied = migrations_status ?ctx ?migrations () in List.iter (fun (namespace, count) -> match count with | None -> Logs.warn (fun m -> m "Could not find registered migrations for namespace '%s'. This \ implies you removed all migrations of that namespace. \ Migrations should be append-only. If you intended to remove \ those migrations, make sure to remove the migration state in \ your database/other persistence layer." namespace) | Some count -> if count > 0 then Logs.info (fun m -> m "Unapplied migrations for namespace '%s' detected. Found %s \ unapplied migrations, run command 'migrate'." namespace (Int.to_string count)) else if count < 0 then Logs.warn (fun m -> m "Fewer registered migrations found than migration state \ indicates for namespace '%s'. Current migration state version \ is ahead of registered migrations by %s. This implies you \ removed migrations, which should be append-only." namespace (Int.to_string @@ Int.abs count)) else ()) unapplied; Lwt.return () ;; let start () = Core_configuration.require schema; let%lwt () = setup () in let skip_default_pool_creation = Option.value ~default:false (Core_configuration.read_bool "DATABASE_SKIP_DEFAULT_POOL_CREATION") in if Core_configuration.is_test () || skip_default_pool_creation then Lwt.return () else check_migrations_status () ;; let stop () = Lwt.return () let migrate_cmd = Core_command.make ~name:"migrate" ~description:"Runs all pending migrations." (fun _ -> let%lwt () = Database.start () in let%lwt () = start () in run_all () |> Lwt.map Option.some) ;; let lifecycle = Core_container.create_lifecycle Contract_migration.name ~dependencies:(fun () -> [ Database.lifecycle ]) ~start ~stop ;; let register migrations = register_migrations migrations; Core_container.Service.create ~commands:[ migrate_cmd ] lifecycle ;; end module PostgreSql = Make (Database_migration_repo.PostgreSql) module MariaDb = Make (Database_migration_repo.MariaDb)
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl/src/database_migration_repo.ml
module Migration = struct type t = { namespace : string ; version : int ; dirty : bool } [@@deriving fields] let create ~namespace = { namespace; version = 0; dirty = true } let mark_dirty state = { state with dirty = true } let mark_clean state = { state with dirty = false } let increment state = { state with version = state.version + 1 } let steps_to_apply (namespace, steps) { version; _ } = namespace, CCList.drop version steps ;; let of_tuple (namespace, version, dirty) = { namespace; version; dirty } let to_tuple state = state.namespace, state.version, state.dirty let dirty state = state.dirty end module type Sig = sig module Migration = Migration val create_table_if_not_exists : ?ctx:(string * string) list -> string -> unit Lwt.t val get : ?ctx:(string * string) list -> string -> namespace:string -> Migration.t option Lwt.t val get_all : ?ctx:(string * string) list -> string -> Migration.t list Lwt.t val upsert : ?ctx:(string * string) list -> string -> Migration.t -> unit Lwt.t end (* Common functions *) let get_request table = let open Caqti_request.Infix in Format.sprintf {sql| SELECT namespace, version, dirty FROM %s WHERE namespace = ? |sql} table |> Caqti_type.(string ->? tup3 string int bool) ;; let get ?ctx table ~namespace = Database.find_opt ?ctx (get_request table) namespace |> Lwt.map (Option.map Migration.of_tuple) ;; let get_all_request table = let open Caqti_request.Infix in Format.sprintf {sql| SELECT namespace, version, dirty FROM %s |sql} table |> Caqti_type.(unit ->* tup3 string int bool) ;; let get_all ?ctx table = Database.collect ?ctx (get_all_request table) () |> Lwt.map (List.map Migration.of_tuple) ;; module MariaDb : Sig = struct module Migration = Migration let create_request table = let open Caqti_request.Infix in Format.sprintf {sql| CREATE TABLE IF NOT EXISTS %s ( namespace VARCHAR(128) NOT NULL, version INTEGER, dirty BOOL NOT NULL, PRIMARY KEY (namespace) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci |sql} table |> Caqti_type.(unit ->. unit) ;; let create_table_if_not_exists ?ctx table = Database.exec ?ctx (create_request table) () ;; let get = get let get_all = get_all let upsert_request table = let open Caqti_request.Infix in Format.sprintf {sql| INSERT INTO %s ( namespace, version, dirty ) VALUES ( ?, ?, ? ) ON DUPLICATE KEY UPDATE version = VALUES(version), dirty = VALUES(dirty) |sql} table |> Caqti_type.(tup3 string int bool ->. unit) ;; let upsert ?ctx table state = Database.exec ?ctx (upsert_request table) (Migration.to_tuple state) ;; end module PostgreSql : Sig = struct module Migration = Migration let create_request table = let open Caqti_request.Infix in Format.sprintf {sql| CREATE TABLE IF NOT EXISTS %s ( namespace VARCHAR(128) NOT NULL PRIMARY KEY, version INTEGER, dirty BOOL NOT NULL ) |sql} table |> Caqti_type.(unit ->. unit) ;; let create_table_if_not_exists ?ctx table = Database.exec ?ctx (create_request table) () ;; let get = get let get_all = get_all let upsert_request table = let open Caqti_request.Infix in Format.sprintf {sql| INSERT INTO %s ( namespace, version, dirty ) VALUES ( ?, ?, ? ) ON CONFLICT (namespace) DO UPDATE SET version = EXCLUDED.version, dirty = EXCLUDED.dirty |sql} table |> Caqti_type.(tup3 string int bool ->. unit) ;; let upsert ?ctx table state = Database.exec ?ctx (upsert_request table) (Migration.to_tuple state) ;; end
sihl-email
3.0.5
Unknown
Unknown
Unknown
dune
sihl-3.0.5/sihl/src/dune
(library (name sihl) (public_name sihl) (libraries sexplib fmt fmt.tty logs logs.fmt lwt lwt.unix tsort conformist base64 yojson ppx_deriving_yojson.runtime safepass ptime ptime.clock.os jwto uuidm opium caqti-lwt str dune-build-info bos containers nocrypto nocrypto.unix cstruct) (preprocess (pps ppx_fields_conv ppx_deriving_yojson ppx_deriving.eq ppx_deriving.show ppx_deriving.make ppx_sexp_conv lwt_ppx))) (documentation (package sihl))
sihl-email
3.0.5
Unknown
Unknown
Unknown
ml
sihl-3.0.5/sihl/src/gen.ml
let service = Core_command.make ~name:"gen.model" ~help: "<database> <service name> <name>:<type> <name>:<type> <name>:<type> ... \n\ Supported types are: int | float | bool | string | datetime \n\ Supported databases are: mariadb | postgresql" ~description: "Generates a model consisting of a service, an entityt, a repository, \ tests and migrations." (function | database :: model_name :: schema -> (match Gen_core.schema_of_string schema with | Ok schema -> Gen_model.generate database model_name schema; Lwt.return @@ Some () | Error msg -> print_endline msg; raise @@ Core_command.Exception "") | _ -> Lwt.return None) ;; let view = Core_command.make ~name:"gen.view" ~help: "<model name> <name>:<type> <name>:<type> <name>:<type> ... \n\ Supported types are: int, float, bool, string, datetime" ~description: "Generates an HTML view that contains a form to create and update a \ resource." (function | name :: schema -> (match Gen_core.schema_of_string schema with | Ok schema -> Gen_view.generate name schema; Lwt.return @@ Some () | Error msg -> print_endline msg; raise @@ Core_command.Exception "") | [] -> Lwt.return None) ;; let html_help model_name module_name = Format.sprintf {| Resource '%ss' created. To finalize the generation: 1.) Copy this route let %s = Sihl.Web.choose ~middlewares: [ Sihl.Web.Middleware.csrf () ; Sihl.Web.Middleware.flash () ] Sihl.Web.Rest.( resource_of_service "%ss" %s.schema ~view:(module View_%s : VIEW with type t = %s.t) (module %s : SERVICE with type t = %s.t)) ;; into your `routes/routes.ml` and mount it with the HTTP service. Don't forget to add '%s' and 'view_%s' to `routes/dune`. 2.) Add the migration Database.%s.migration to the list of migrations in `run/run.ml` before running `sihl migrate`. 3.) You should also run `make format` to apply your styling rules. 4.) Visit http://localhost:3000/%ss |} model_name model_name model_name module_name model_name module_name module_name module_name model_name model_name module_name model_name ;; let html = Core_command.make ~name:"gen.html" ~help: "<database> <service name> <name>:<type> <name>:<type> <name>:<type> ... \n\ Supported types are: int, float, bool, string, datetime \n\ Supported databases are: mariadb | postgresql" ~description: "Generates a controller, HTML views, a service, tests and migrations for \ an HTML resource. This generator is a combination of gen.service and \ gen.view." (function | database :: model_name :: schema -> (match Gen_core.schema_of_string schema with | Ok schema -> let module_name = String.capitalize_ascii model_name in Gen_model.generate database model_name schema; Gen_view.generate model_name schema; print_endline @@ html_help model_name module_name; Lwt.return @@ Some () | Error msg -> print_endline msg; raise @@ Core_command.Exception "") | _ -> Lwt.return None) ;; let commands = [ service; view; html ]