Dataset Viewer
Auto-converted to Parquet Duplicate
package_name
stringlengths
2
45
version
stringclasses
310 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) ;;
End of preview. Expand in Data Studio

This is a dataset automatically generated from ocaml/opam:archive. You can find more information about this dataset in this blogpost.

Downloads last month
696