mirror of
https://github.com/higherkindness/mu-haskell.git
synced 2024-09-11 14:36:01 +03:00
Optics for schema and gRPC clients (#102)
This commit is contained in:
parent
48a9d0ef73
commit
22f7f740a0
@ -1,6 +1,7 @@
|
||||
packages: compendium-client/
|
||||
core/schema/
|
||||
core/rpc/
|
||||
core/optics/
|
||||
adapter/avro/
|
||||
adapter/protobuf/
|
||||
adapter/persistent/
|
||||
|
202
core/optics/LICENSE
Normal file
202
core/optics/LICENSE
Normal file
@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright © 2019-2020 47 Degrees. <http://47deg.com>
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
1
core/optics/hie.yaml
Normal file
1
core/optics/hie.yaml
Normal file
@ -0,0 +1 @@
|
||||
cradle: { stack: { component: "mu-optics:lib" } }
|
31
core/optics/mu-optics.cabal
Normal file
31
core/optics/mu-optics.cabal
Normal file
@ -0,0 +1,31 @@
|
||||
cabal-version: >=1.10
|
||||
name: mu-optics
|
||||
version: 0.1.0.0
|
||||
synopsis: Optics for @mu-schema@ terms
|
||||
description: With @mu-schema@ you can describe schemas using type-level constructs, and derive serializers from those. This package provides convenient access using @optics@.
|
||||
license: Apache-2.0
|
||||
license-file: LICENSE
|
||||
author: Alejandro Serrano
|
||||
maintainer: alejandro.serrano@47deg.com
|
||||
copyright: Copyright © 2019-2020 <http://47deg.com 47 Degrees>
|
||||
category: Network
|
||||
build-type: Simple
|
||||
homepage: https://higherkindness.io/mu-haskell/
|
||||
bug-reports: https://github.com/higherkindness/mu-haskell/issues
|
||||
|
||||
source-repository head
|
||||
type: git
|
||||
location: https://github.com/higherkindness/mu-haskell
|
||||
|
||||
library
|
||||
exposed-modules: Mu.Schema.Optics
|
||||
-- other-modules:
|
||||
-- other-extensions:
|
||||
build-depends: base >=4.12 && <5
|
||||
, sop-core
|
||||
, optics-core
|
||||
, mu-schema
|
||||
, containers
|
||||
hs-source-dirs: src
|
||||
default-language: Haskell2010
|
||||
ghc-options: -Wall
|
163
core/optics/src/Mu/Schema/Optics.hs
Normal file
163
core/optics/src/Mu/Schema/Optics.hs
Normal file
@ -0,0 +1,163 @@
|
||||
{-# language DataKinds #-}
|
||||
{-# language FlexibleInstances #-}
|
||||
{-# language FunctionalDependencies #-}
|
||||
{-# language GADTs #-}
|
||||
{-# language KindSignatures #-}
|
||||
{-# language ScopedTypeVariables #-}
|
||||
{-# language TypeApplications #-}
|
||||
{-# language TypeOperators #-}
|
||||
{-# language UndecidableInstances #-}
|
||||
{-# OPTIONS_GHC -fno-warn-orphans #-}
|
||||
{-|
|
||||
Description : Optics-based interface for @mu-schema@ terms
|
||||
|
||||
This module provides instances of 'LabelOptic' to be
|
||||
used in conjunction with the @optics@ package.
|
||||
In particular, there are two kind of optics to access
|
||||
different parts of a 'Term':
|
||||
|
||||
* With @#field@ you obtain the lens (that is, a getter
|
||||
and a setter) for the corresponding field in a record.
|
||||
* With @#choice@ you obtain the prism for the
|
||||
desired choice in an enumeration. You can use then
|
||||
'review' to construct a term with the value.
|
||||
|
||||
In addition, we provide a utility function 'record' to
|
||||
build a record out of the inner values. We intend the
|
||||
interface to be very simple, so this function is overloaded
|
||||
to take tuples of different size, with as many components
|
||||
as values in the schema type.
|
||||
-}
|
||||
module Mu.Schema.Optics (
|
||||
-- * Build a term
|
||||
record
|
||||
-- * Re-exported for convenience.
|
||||
, module Optics.Core
|
||||
) where
|
||||
|
||||
import Data.Functor.Identity
|
||||
import Data.Kind
|
||||
import Data.Map
|
||||
import Data.Proxy
|
||||
import GHC.TypeLits
|
||||
import Optics.Core
|
||||
|
||||
import Mu.Schema
|
||||
|
||||
instance {-# OVERLAPS #-}
|
||||
(FieldLabel Identity sch args fieldName r)
|
||||
=> LabelOptic fieldName A_Lens
|
||||
(Term Identity sch ('DRecord name args))
|
||||
(Term Identity sch ('DRecord name args))
|
||||
r r where
|
||||
labelOptic = lens (\(TRecord r) -> runIdentity $ fieldLensGet (Proxy @fieldName) r)
|
||||
(\(TRecord r) x -> TRecord $ fieldLensSet (Proxy @fieldName) r (Identity x))
|
||||
instance {-# OVERLAPPABLE #-}
|
||||
(FieldLabel w sch args fieldName r, t ~ w r)
|
||||
=> LabelOptic fieldName A_Lens
|
||||
(Term w sch ('DRecord name args))
|
||||
(Term w sch ('DRecord name args))
|
||||
t t where
|
||||
labelOptic = lens (\(TRecord r) -> fieldLensGet (Proxy @fieldName) r)
|
||||
(\(TRecord r) x -> TRecord $ fieldLensSet (Proxy @fieldName) r x)
|
||||
|
||||
record :: BuildRecord w sch args r => r -> Term w sch ('DRecord name args)
|
||||
record values = TRecord $ buildR values
|
||||
|
||||
class BuildRecord (w :: Type -> Type)
|
||||
(sch :: Schema Symbol Symbol)
|
||||
(args :: [FieldDef Symbol Symbol])
|
||||
(r :: Type) | w sch args -> r where
|
||||
buildR :: r -> NP (Field w sch) args
|
||||
instance BuildRecord w sch '[] () where
|
||||
buildR _ = Nil
|
||||
instance (Functor w, TypeLabel w sch t1 r1)
|
||||
=> BuildRecord w sch '[ 'FieldDef x1 t1 ] (w r1) where
|
||||
buildR v = Field (typeLensSet <$> v) :* Nil
|
||||
instance (Functor w, TypeLabel w sch t1 r1, TypeLabel w sch t2 r2)
|
||||
=> BuildRecord w sch '[ 'FieldDef x1 t1, 'FieldDef x2 t2 ] (w r1, w r2) where
|
||||
buildR (v1, v2) = Field (typeLensSet <$> v1)
|
||||
:* Field (typeLensSet <$> v2) :* Nil
|
||||
instance (Functor w, TypeLabel w sch t1 r1, TypeLabel w sch t2 r2, TypeLabel w sch t3 r3)
|
||||
=> BuildRecord w sch
|
||||
'[ 'FieldDef x1 t1, 'FieldDef x2 t2, 'FieldDef x3 t3 ]
|
||||
(w r1, w r2, w r3) where
|
||||
buildR (v1, v2, v3) = Field (typeLensSet <$> v1)
|
||||
:* Field (typeLensSet <$> v2)
|
||||
:* Field (typeLensSet <$> v3) :* Nil
|
||||
|
||||
|
||||
class FieldLabel (w :: Type -> Type)
|
||||
(sch :: Schema Symbol Symbol)
|
||||
(args :: [FieldDef Symbol Symbol])
|
||||
(fieldName :: Symbol) (r :: Type)
|
||||
| w sch args fieldName -> r where
|
||||
fieldLensGet :: Proxy fieldName -> NP (Field w sch) args -> w r
|
||||
fieldLensSet :: Proxy fieldName -> NP (Field w sch) args -> w r -> NP (Field w sch) args
|
||||
|
||||
{- Removed due to FunDeps
|
||||
instance TypeError ('Text "cannot find field " ':<>: 'ShowType f)
|
||||
=> FieldLabel w sch '[] f t where
|
||||
fieldLensGet = error "this should never be run"
|
||||
fieldLensSet = error "this should never be run"
|
||||
-}
|
||||
instance {-# OVERLAPS #-} (Functor w, TypeLabel w sch t r)
|
||||
=> FieldLabel w sch ('FieldDef f t ': rest) f r where
|
||||
fieldLensGet _ (Field x :* _) = typeLensGet <$> x
|
||||
fieldLensSet _ (_ :* r) new = Field (typeLensSet <$> new) :* r
|
||||
instance {-# OVERLAPPABLE #-} FieldLabel w sch rest g t
|
||||
=> FieldLabel w sch (f ': rest) g t where
|
||||
fieldLensGet p (_ :* r) = fieldLensGet p r
|
||||
fieldLensSet p (x :* r) new = x :* fieldLensSet p r new
|
||||
|
||||
class TypeLabel w (sch :: Schema Symbol Symbol) (t :: FieldType Symbol) (r :: Type)
|
||||
| w sch t -> r where
|
||||
typeLensGet :: FieldValue w sch t -> r
|
||||
typeLensSet :: r -> FieldValue w sch t
|
||||
|
||||
instance TypeLabel w sch ('TPrimitive t) t where
|
||||
typeLensGet (FPrimitive x) = x
|
||||
typeLensSet = FPrimitive
|
||||
instance (r ~ (sch :/: t)) => TypeLabel w sch ('TSchematic t) (Term w sch r) where
|
||||
typeLensGet (FSchematic x) = x
|
||||
typeLensSet = FSchematic
|
||||
instance (TypeLabel w sch o r', r ~ Maybe r')
|
||||
=> TypeLabel w sch ('TOption o) r where
|
||||
typeLensGet (FOption x) = typeLensGet <$> x
|
||||
typeLensSet new = FOption (typeLensSet <$> new)
|
||||
instance (TypeLabel w sch o r', r ~ [r'])
|
||||
=> TypeLabel w sch ('TList o) r where
|
||||
typeLensGet (FList x) = typeLensGet <$> x
|
||||
typeLensSet new = FList (typeLensSet <$> new)
|
||||
instance ( TypeLabel w sch k k', TypeLabel w sch v v'
|
||||
, r ~ Map k' v', Ord k', Ord (FieldValue w sch k) )
|
||||
=> TypeLabel w sch ('TMap k v) r where
|
||||
typeLensGet (FMap x) = mapKeys typeLensGet (typeLensGet <$> x)
|
||||
typeLensSet new = FMap (mapKeys typeLensSet (typeLensSet <$> new))
|
||||
|
||||
instance (EnumLabel choices choiceName, r ~ ())
|
||||
=> LabelOptic choiceName A_Prism
|
||||
(Term w sch ('DEnum name choices))
|
||||
(Term w sch ('DEnum name choices))
|
||||
r r where
|
||||
labelOptic = prism' (\_ -> TEnum $ enumPrismBuild (Proxy @choiceName))
|
||||
(\(TEnum r) -> enumPrismMatch (Proxy @choiceName) r)
|
||||
|
||||
class EnumLabel (choices :: [ChoiceDef Symbol])
|
||||
(choiceName :: Symbol) where
|
||||
enumPrismBuild :: Proxy choiceName -> NS Proxy choices
|
||||
enumPrismMatch :: Proxy choiceName -> NS Proxy choices -> Maybe ()
|
||||
|
||||
instance TypeError ('Text "cannot find choice " ':<>: 'ShowType c)
|
||||
=> EnumLabel '[] c where
|
||||
enumPrismBuild = error "this should never be run"
|
||||
enumPrismMatch = error "this should never be run"
|
||||
instance {-# OVERLAPS #-} EnumLabel ('ChoiceDef c ': rest) c where
|
||||
enumPrismBuild _ = Z Proxy
|
||||
enumPrismMatch _ (Z _) = Just ()
|
||||
enumPrismMatch _ _ = Nothing
|
||||
instance {-# OVERLAPPABLE #-} EnumLabel rest c
|
||||
=> EnumLabel (d ': rest) c where
|
||||
enumPrismBuild p = S (enumPrismBuild p)
|
||||
enumPrismMatch _ (Z _) = Nothing
|
||||
enumPrismMatch p (S x) = enumPrismMatch p x
|
@ -86,6 +86,19 @@ class FromSchema (w :: Type -> Type) (sch :: Schema typeName fieldName) (sty ::
|
||||
=> Term w sch (sch :/: sty) -> t
|
||||
fromSchema x = to (fromSchemaTypeDef (Proxy @'[]) x)
|
||||
|
||||
instance (sch :/: sty ~ 'DRecord sty fields)
|
||||
=> ToSchema w sch sty (Term w sch ('DRecord sty fields)) where
|
||||
toSchema = id
|
||||
instance (sch :/: sty ~ 'DEnum sty choices)
|
||||
=> ToSchema w sch sty (Term w sch ('DEnum sty choices)) where
|
||||
toSchema = id
|
||||
instance (sch :/: sty ~ 'DRecord sty fields)
|
||||
=> FromSchema w sch sty (Term w sch ('DRecord sty fields)) where
|
||||
fromSchema = id
|
||||
instance (sch :/: sty ~ 'DEnum sty choices)
|
||||
=> FromSchema w sch sty (Term w sch ('DEnum sty choices)) where
|
||||
fromSchema = id
|
||||
|
||||
-- | Conversion from Haskell type to schema term.
|
||||
-- This version is intended for usage with @TypeApplications@:
|
||||
-- > toSchema' @MySchema myValue
|
||||
|
@ -135,6 +135,15 @@ data FieldTypeB builtin typeName
|
||||
-- | Represents a choice between types.
|
||||
| TUnion [FieldTypeB builtin typeName]
|
||||
|
||||
instance KnownName n => KnownName ('DRecord n fields) where
|
||||
nameVal _ = nameVal (Proxy @n)
|
||||
instance KnownName n => KnownName ('DEnum n choices) where
|
||||
nameVal _ = nameVal (Proxy @n)
|
||||
instance KnownName n => KnownName ('ChoiceDef n) where
|
||||
nameVal _ = nameVal (Proxy @n)
|
||||
instance KnownName n => KnownName ('FieldDef n t) where
|
||||
nameVal _ = nameVal (Proxy @n)
|
||||
|
||||
-- | Lookup a type in a schema by its name.
|
||||
type family (sch :: Schema t f) :/: (name :: t) :: TypeDef t f where
|
||||
'[] :/: name = TypeError ('Text "Cannot find type " ':<>: 'ShowType name ':<>: 'Text " in the schema")
|
||||
|
@ -21,4 +21,5 @@ in {
|
||||
mu-protobuf = hnPkgs.mu-protobuf.components.all;
|
||||
mu-rpc = hnPkgs.mu-rpc.components.library;
|
||||
mu-schema = hnPkgs.mu-schema.components.library;
|
||||
mu-optics = hnPkgs.mu-optics.components.library;
|
||||
}
|
||||
|
@ -36,7 +36,7 @@ import System.Environment
|
||||
main :: IO ()
|
||||
main = do
|
||||
let config = grpcClientConfigSimple "127.0.0.1" 8080 False
|
||||
Right client <- setupGrpcClient' config
|
||||
Right client <- setup config
|
||||
args <- getArgs
|
||||
case args of
|
||||
["watch"] -> watching client
|
||||
@ -45,11 +45,53 @@ main = do
|
||||
_ -> putStrLn "unknown command"
|
||||
```
|
||||
|
||||
Where `watch`, `get` and `add` are the only valid 3 commands that our CLI is going to accept and call each respective service.
|
||||
Where `watch`, `get` and `add` are the only valid 3 commands that our CLI is going to accept and call each respective service. The `setup` function is responsible from initializing the
|
||||
|
||||
### Using optics
|
||||
|
||||
The simplest way to call methods is to use the `optics`-based API. In that case, your setup is done using `initGRpc`, which receives the configuration.
|
||||
|
||||
```haskell
|
||||
main :: IO ()
|
||||
main = do ...
|
||||
where setup config = initGRpc config
|
||||
```
|
||||
|
||||
To call a method, you use the corresponding getter (for those familiar with optics, a version of a lens which does not allow to set). This means that your code reads `client ^. #method`, where `client` is the value obtained previously in the call to `initGRpc`.
|
||||
|
||||
```haskell
|
||||
{-# language OverloadedLabels #-}
|
||||
import Text.Read (readMaybe)
|
||||
|
||||
get :: GRpcConnection QuickstartService -> String -> IO ()
|
||||
get client idPerson = do
|
||||
let req = record (readMaybe idPerson)
|
||||
putStrLn $ "GET: is there some person with id: " ++ idPerson ++ "?"
|
||||
res <- (client ^. #getPerson) req
|
||||
putStrLn $ "GET: response was: " ++ show res
|
||||
```
|
||||
|
||||
Notice the use of `readMaybe` to convert the strings to the appropiate type in a safe manner! 👆🏼
|
||||
|
||||
Using this approach you must also use the optics-based interface to the terms. As a quick reminder: you use `record` to build new values, and use `value ^. #field` to access a field. The rest of the methods look as follows:
|
||||
|
||||
```haskell
|
||||
add :: GRpcConnection QuickstartService -> String -> String -> IO ()
|
||||
add client nm ag = do
|
||||
let p = record (Nothing, Just $ T.pack nm, readMaybe ag)
|
||||
putStrLn $ "ADD: creating new person " ++ nm ++ " with age " ++ ag
|
||||
res <- (client ^. #newPerson) p
|
||||
putStrLn $ "ADD: was creating successful? " ++ show res
|
||||
|
||||
watching :: GRpcConnection QuickstartService -> IO ()
|
||||
watching client = do
|
||||
replies <- client ^. #allPeople
|
||||
runConduit $ replies .| C.mapM_ print
|
||||
```
|
||||
|
||||
### Using records
|
||||
|
||||
This option is a bit more verbose but it's also more explicit with the types and _"a bit more magic"_ than the one with `TypeApplications` (due to the use of Generics).
|
||||
This option is a bit more verbose but it's also more explicit with the types. Furthermore, it allows us to use our Haskell data types, we are not forced to use plain terms. As discussed several times, this is important to ensure that Haskell types are not mere shadows of the schema types.
|
||||
|
||||
We need to define a new record type (hence the name) that declares the services our client is going to consume. The names of the fields **must** match the names of the methods in the service, optionally prefixed by a **common** string. The prefix may also be empty, which means that the names in the record are exactly those in the service definition. In this case, we are prepending `call_` to each of them:
|
||||
|
||||
@ -64,36 +106,28 @@ data Call = Call
|
||||
} deriving Generic
|
||||
```
|
||||
|
||||
Note that we had to derive `Generic`. We also need to tweak our `main` function a little bit:
|
||||
Note that we had to derive `Generic`. We also need to tweak our `setup` function a little bit:
|
||||
|
||||
```haskell
|
||||
{-# language TypeApplications #-}
|
||||
|
||||
```diff
|
||||
main :: IO ()
|
||||
main = do
|
||||
let config = grpcClientConfigSimple "127.0.0.1" 1234 False
|
||||
- Right client <- setupGrpcClient' config
|
||||
+ Right grpcClient <- setupGrpcClient' config
|
||||
+ let client = buildService @Service @"call_" grpcClient
|
||||
args <- getArgs
|
||||
main = do ...
|
||||
where setup config = buildService @Service @"call_" <$> setupGrpcClient' config
|
||||
```
|
||||
|
||||
Instead of building our client directly, we need to call `buildService` (and enable `TypeApplications`) to create the actual gRPC client. There are two type arguments to be explicitly given: the first one is the `Service` definition we want a client for, and the second one is the prefix in the record (in our case, this is `call_`). In the case you want an empty prefix, you write `@""` in that second position.
|
||||
|
||||
After that, let's have a look at an example implementation of the three service calls:
|
||||
After that, let's have a look at an example implementation of the three service calls. Almost as before, except that we use `call_` followed by the name of the method.
|
||||
|
||||
```haskell
|
||||
import Text.Read (readMaybe)
|
||||
|
||||
get :: Call -> String -> IO ()
|
||||
get client idPerson = do
|
||||
let req = MPersonRequest $ readMaybe idPerson
|
||||
putStrLn $ "GET: is there some person with id: " ++ idPerson ++ "?"
|
||||
res <- call_getPerson client req
|
||||
putStrLn $ "GET: response was: " ++ show res
|
||||
```
|
||||
|
||||
Notice the use of `readMaybe` to convert the strings to the appropiate type in a safe manner! 👆🏼
|
||||
|
||||
```haskell
|
||||
add :: Call -> String -> String -> IO ()
|
||||
add client nm ag = do
|
||||
let p = MPerson Nothing (Just $ T.pack nm) (readMaybe ag)
|
||||
@ -117,6 +151,9 @@ If you are not familiar with `TypeApplications`, you can check [this](https://ww
|
||||
```haskell
|
||||
import Mu.GRpc.Client.TyApps
|
||||
|
||||
main = do ...
|
||||
where setup config = setupGrpcClient' config
|
||||
|
||||
get :: GrpcClient -> String -> IO ()
|
||||
get client idPerson = do
|
||||
let req = MPersonRequest $ readMaybe idPerson
|
||||
|
@ -23,7 +23,7 @@ The main goal of Mu-Haskell is to allow you to focus on your domain logic, inste
|
||||
|
||||
1. Create a new project with `stack new`.
|
||||
2. Define your schema and your services in the `.proto` file.
|
||||
3. Write your Haskell data types in `src/Schema.hs`.
|
||||
3. Map to your Haskell data types in `src/Schema.hs`, or use optics.
|
||||
4. Implement the server in `src/Main.hs`.
|
||||
|
||||
### Step by step
|
||||
@ -53,7 +53,9 @@ The first step to get your project running is defining the right schema and serv
|
||||
|
||||
#### Data type definition
|
||||
|
||||
The second step is to define some Haskell data type corresponding to the message types in the gRPC definition. Although in some cases those data types can be inferred from the schema itself, we have made the design choice of having to write them explicitly, but check for compatibility at compile-time. The main goal is to discourage from making your domain types simple copies of the protocol types.
|
||||
The second step is to define Haskell types corresponding to the message types in the gRPC definition. The recommended route is to create new Haskell data types and check for compatibility at compile-time. The goal is to discourage from making your domain types simple copies of the protocol types. Another possibility is to use the `optics` bridge and work with lenses for the fields.
|
||||
|
||||
##### Using Haskell types
|
||||
|
||||
The aforementioned `.proto` file defines two messages. The corresponding data types are as follows:
|
||||
|
||||
@ -81,6 +83,17 @@ You can give the data types and their constructors any name you like. However, k
|
||||
* The name between quotes in each `deriving` clause defines the message type in the `.proto` file each data type corresponds to.
|
||||
* To use the automatic-mapping functionality, it is required to also derive `Generic`, don't forget it!
|
||||
|
||||
##### Using optics
|
||||
|
||||
As we mentioned above, you may decide to not introduce new Haskell types, at the expense of losing some automatic checks against the current version of the schema. However, you gain access to a set of lenses and optics which can be used to inspect the values. In the Mu jargon, values from a schema which are not Haskell types are called *terms*, and we usually define type synonyms for each of them.
|
||||
|
||||
```haskell
|
||||
type HelloRequestMessage' = Term Maybe TheSchema (TheSchema :/: "HelloRequest")
|
||||
type HelloReplyMessage' = Term Maybe TheSchema (TheSchema :/: "HelloReply")
|
||||
```
|
||||
|
||||
The arguments to `Term` closely correspond to those in `FromSchema` and `ToSchema` described above.
|
||||
|
||||
#### Server implementation
|
||||
|
||||
If you try to compile the project right now by means of `stack build`, you will receive an error about `server` not having the right type. This is because you haven't yet defined any implementation for your service. This is one of the advantages of making the compiler aware of your service definitions: if the `.proto` file changes, you need to adapt your code correspondingly, or otherwise the project doesn't even compile!
|
||||
@ -95,7 +108,7 @@ server :: (MonadServer m) => ServerT Maybe Service m _
|
||||
server = Server H0
|
||||
```
|
||||
|
||||
The simplest way to provide an implementation for a service is to define one function for each method. You define those functions completely in terms of Haskell data types; in our case `HelloRequestMessage` and `HelloReplyMessage`. Here is an example definition:
|
||||
The simplest way to provide an implementation for a service is to define one function for each method. You can define those functions completely in terms of Haskell data types; in our case `HelloRequestMessage` and `HelloReplyMessage`. Here is an example definition:
|
||||
|
||||
```haskell
|
||||
sayHello :: (MonadServer m) => HelloRequestMessage -> m HelloReplyMessage
|
||||
@ -105,7 +118,17 @@ sayHello (HelloRequestMessage nm)
|
||||
|
||||
The `MonadServer` portion in the type is mandated by `mu-rpc`; it tells us that in a method we can perform any `IO` actions and additionally throw server errors (for conditions such as *not found*). We do not make use of any of those here, so we simply use `return` with a value. We could even make the definition a bit more polymorphic by replacing `MonadServer` by `Monad`.
|
||||
|
||||
How does `server` know that `sayHello` is part of the implementation of the service? We have to tell it, by adding `sayHello` to the list of methods. Unfortunately, we cannot use a normal list, so we use `(:<|>:)` to join them, and `H0` to finish it.
|
||||
Another possibility is to use the `optics`-based API in `Mu.Schema.Optics`. In that case, you access the value of the fields using `(^.)` followed by the name of the field after `#`, and build messages by using `record` followed by a tuple of the components. The previous example would then be written:
|
||||
|
||||
```haskell
|
||||
{-# language OverloadedLabels #-}
|
||||
|
||||
sayHello :: (MonadServer m) => HelloRequestMessage' -> m HelloReplyMessage'
|
||||
sayHello (HelloRequestMessage nm)
|
||||
= return $ record (("hi, " <>) <$> (nm ^. #name))
|
||||
```
|
||||
|
||||
How does `server` know that `sayHello` (any of the two versions) is part of the implementation of the service? We have to tell it, by adding `sayHello` to the list of methods. Unfortunately, we cannot use a normal list, so we use `(:<|>:)` to join them, and `H0` to finish it.
|
||||
|
||||
```haskell
|
||||
server = Server (sayHello :<|>: H0)
|
||||
|
@ -28,3 +28,20 @@ executable seed-server
|
||||
, mu-grpc-server
|
||||
, text
|
||||
, stm
|
||||
|
||||
executable seed-server-optics
|
||||
hs-source-dirs: src
|
||||
main-is: Optics.hs
|
||||
other-modules: Schema
|
||||
default-language: Haskell2010
|
||||
build-depends: base >= 4.12 && < 5
|
||||
, conduit
|
||||
, monad-logger
|
||||
, mu-schema
|
||||
, mu-rpc
|
||||
, mu-protobuf
|
||||
, mu-optics
|
||||
, mu-grpc-server
|
||||
, text
|
||||
, stm
|
||||
ghc-options: -Wall -fprint-potential-instances
|
||||
|
@ -1,3 +1,7 @@
|
||||
{-# language DataKinds #-}
|
||||
{-# language DeriveAnyClass #-}
|
||||
{-# language DeriveGeneric #-}
|
||||
{-# language DuplicateRecordFields #-}
|
||||
{-# language FlexibleContexts #-}
|
||||
{-# language OverloadedStrings #-}
|
||||
{-# language PartialTypeSignatures #-}
|
||||
@ -10,12 +14,34 @@ import Control.Monad.IO.Class (liftIO)
|
||||
import Control.Monad.Logger
|
||||
import Data.Conduit
|
||||
import Data.Conduit.Combinators as C
|
||||
import Data.Int
|
||||
import Data.Text as T
|
||||
import GHC.Generics
|
||||
import Mu.GRpc.Server
|
||||
import Mu.Schema
|
||||
import Mu.Server
|
||||
|
||||
import Schema
|
||||
|
||||
data Person = Person
|
||||
{ name :: Maybe T.Text
|
||||
, age :: Maybe Int32
|
||||
} deriving ( Eq, Show, Ord, Generic
|
||||
, ToSchema Maybe SeedSchema "Person"
|
||||
, FromSchema Maybe SeedSchema "Person" )
|
||||
|
||||
newtype PeopleRequest = PeopleRequest
|
||||
{ name :: Maybe T.Text
|
||||
} deriving ( Eq, Show, Ord, Generic
|
||||
, ToSchema Maybe SeedSchema "PeopleRequest"
|
||||
, FromSchema Maybe SeedSchema "PeopleRequest" )
|
||||
|
||||
newtype PeopleResponse = PeopleResponse
|
||||
{ person :: Maybe Person
|
||||
} deriving ( Eq, Show, Ord, Generic
|
||||
, ToSchema Maybe SeedSchema "PeopleResponse"
|
||||
, FromSchema Maybe SeedSchema "PeopleResponse" )
|
||||
|
||||
main :: IO ()
|
||||
main = do
|
||||
putStrLn "running seed application"
|
||||
|
55
examples/seed/src/Optics.hs
Normal file
55
examples/seed/src/Optics.hs
Normal file
@ -0,0 +1,55 @@
|
||||
{-# language DataKinds #-}
|
||||
{-# language DuplicateRecordFields #-}
|
||||
{-# language FlexibleContexts #-}
|
||||
{-# language OverloadedLabels #-}
|
||||
{-# language OverloadedStrings #-}
|
||||
{-# language PartialTypeSignatures #-}
|
||||
{-# language TypeOperators #-}
|
||||
{-# OPTIONS_GHC -fno-warn-partial-type-signatures #-}
|
||||
|
||||
module Main where
|
||||
|
||||
import Control.Concurrent (threadDelay)
|
||||
import Control.Monad.IO.Class (liftIO)
|
||||
import Control.Monad.Logger
|
||||
import Data.Conduit
|
||||
import Data.Conduit.Combinators as C
|
||||
import Data.Text as T
|
||||
import Mu.GRpc.Server
|
||||
import Mu.Schema
|
||||
import Mu.Schema.Optics
|
||||
import Mu.Server
|
||||
|
||||
import Schema
|
||||
|
||||
type Person = Term Maybe SeedSchema (SeedSchema :/: "Person")
|
||||
type PeopleRequest = Term Maybe SeedSchema (SeedSchema :/: "PeopleRequest")
|
||||
type PeopleResponse = Term Maybe SeedSchema (SeedSchema :/: "PeopleResponse")
|
||||
|
||||
main :: IO ()
|
||||
main = do
|
||||
putStrLn "running seed application"
|
||||
runGRpcAppTrans 8080 runStderrLoggingT server
|
||||
|
||||
-- Server implementation
|
||||
-- https://github.com/higherkindness/mu/blob/master/modules/examples/seed/server/modules/process/src/main/scala/example/seed/server/process/ProtoPeopleServiceHandler.scala
|
||||
|
||||
server :: (MonadServer m, MonadLogger m) => ServerT Maybe PeopleService m _
|
||||
server = Server (getPerson :<|>: getPersonStream :<|>: H0)
|
||||
|
||||
evolvePerson :: PeopleRequest -> PeopleResponse
|
||||
evolvePerson req = record (Just $ record (req ^. #name, Just 18))
|
||||
|
||||
getPerson :: Monad m => PeopleRequest -> m PeopleResponse
|
||||
getPerson = pure . evolvePerson
|
||||
|
||||
getPersonStream :: (MonadServer m, MonadLogger m)
|
||||
=> ConduitT () PeopleRequest m ()
|
||||
-> ConduitT PeopleResponse Void m ()
|
||||
-> m ()
|
||||
getPersonStream source sink = runConduit $ source .| C.mapM reStream .| sink
|
||||
where
|
||||
reStream req = do
|
||||
liftIO $ threadDelay (2 * 1000 * 1000) -- 2 sec
|
||||
logDebugN $ T.pack $ "stream request: " ++ show req
|
||||
pure $ evolvePerson req
|
@ -1,8 +1,5 @@
|
||||
{-# language CPP #-}
|
||||
{-# language DataKinds #-}
|
||||
{-# language DeriveAnyClass #-}
|
||||
{-# language DeriveGeneric #-}
|
||||
{-# language DuplicateRecordFields #-}
|
||||
{-# language FlexibleContexts #-}
|
||||
{-# language FlexibleInstances #-}
|
||||
{-# language MultiParamTypeClasses #-}
|
||||
@ -13,34 +10,10 @@
|
||||
|
||||
module Schema where
|
||||
|
||||
import Data.Int (Int32)
|
||||
import Data.Text as T
|
||||
import GHC.Generics
|
||||
|
||||
import Mu.Quasi.GRpc
|
||||
import Mu.Schema
|
||||
|
||||
#if __GHCIDE__
|
||||
grpc "SeedSchema" id "examples/seed/seed.proto"
|
||||
#else
|
||||
grpc "SeedSchema" id "seed.proto"
|
||||
#endif
|
||||
|
||||
data Person = Person
|
||||
{ name :: Maybe T.Text
|
||||
, age :: Maybe Int32
|
||||
} deriving ( Eq, Show, Ord, Generic
|
||||
, ToSchema Maybe SeedSchema "Person"
|
||||
, FromSchema Maybe SeedSchema "Person" )
|
||||
|
||||
newtype PeopleRequest = PeopleRequest
|
||||
{ name :: Maybe T.Text
|
||||
} deriving ( Eq, Show, Ord, Generic
|
||||
, ToSchema Maybe SeedSchema "PeopleRequest"
|
||||
, FromSchema Maybe SeedSchema "PeopleRequest" )
|
||||
|
||||
newtype PeopleResponse = PeopleResponse
|
||||
{ person :: Maybe Person
|
||||
} deriving ( Eq, Show, Ord, Generic
|
||||
, ToSchema Maybe SeedSchema "PeopleResponse"
|
||||
, FromSchema Maybe SeedSchema "PeopleResponse" )
|
||||
|
@ -65,3 +65,21 @@ executable persistent-client-record
|
||||
hs-source-dirs: src
|
||||
default-language: Haskell2010
|
||||
ghc-options: -Wall
|
||||
|
||||
executable persistent-client-optics
|
||||
main-is: ClientOptics.hs
|
||||
other-modules: Schema
|
||||
build-depends: base >=4.12 && <5
|
||||
, conduit
|
||||
, mu-schema
|
||||
, mu-rpc
|
||||
, mu-persistent
|
||||
, mu-protobuf
|
||||
, mu-grpc-client
|
||||
, persistent
|
||||
, persistent-sqlite
|
||||
, persistent-template
|
||||
, text
|
||||
hs-source-dirs: src
|
||||
default-language: Haskell2010
|
||||
ghc-options: -Wall
|
||||
|
42
examples/with-persistent/src/ClientOptics.hs
Normal file
42
examples/with-persistent/src/ClientOptics.hs
Normal file
@ -0,0 +1,42 @@
|
||||
{-# language DataKinds #-}
|
||||
{-# language OverloadedLabels #-}
|
||||
|
||||
module Main where
|
||||
|
||||
import Data.Conduit
|
||||
import qualified Data.Conduit.Combinators as C
|
||||
import qualified Data.Text as T
|
||||
import Mu.GRpc.Client.Optics
|
||||
import System.Environment
|
||||
import Text.Read (readMaybe)
|
||||
|
||||
import Schema
|
||||
|
||||
main :: IO ()
|
||||
main = do
|
||||
Right client <- initGRpc (grpcClientConfigSimple "127.0.0.1" 1234 False)
|
||||
args <- getArgs
|
||||
case args of
|
||||
["watch"] -> watching client
|
||||
["get", idp] -> get client idp
|
||||
["add", nm, ag] -> add client nm ag
|
||||
_ -> putStrLn "unknown command"
|
||||
|
||||
get :: GRpcConnection PersistentService -> String -> IO ()
|
||||
get client idPerson = do
|
||||
let req = readMaybe idPerson
|
||||
putStrLn $ "GET: is there some person with id: " ++ idPerson ++ "?"
|
||||
response <- (client ^. #getPerson) (record req)
|
||||
putStrLn $ "GET: response was: " ++ show response
|
||||
|
||||
add :: GRpcConnection PersistentService -> String -> String -> IO ()
|
||||
add client nm ag = do
|
||||
let p = record (Nothing, Just (T.pack nm), readMaybe ag)
|
||||
putStrLn $ "ADD: creating new person " ++ nm ++ " with age " ++ ag
|
||||
response <- (client ^. #newPerson) p
|
||||
putStrLn $ "ADD: was creating successful? " ++ show response
|
||||
|
||||
watching :: GRpcConnection PersistentService -> IO ()
|
||||
watching client = do
|
||||
replies <- client ^. #allPeople
|
||||
runConduit $ replies .| C.mapM_ print
|
@ -21,6 +21,7 @@ source-repository head
|
||||
library
|
||||
exposed-modules: Mu.GRpc.Client.TyApps,
|
||||
Mu.GRpc.Client.Record,
|
||||
Mu.GRpc.Client.Optics,
|
||||
Mu.GRpc.Client.Examples
|
||||
other-modules: Mu.GRpc.Client.Internal
|
||||
build-depends: base >=4.12 && <5
|
||||
@ -31,9 +32,11 @@ library
|
||||
, http2-client
|
||||
, http2-client-grpc
|
||||
, http2-grpc-proto3-wire
|
||||
, mu-optics
|
||||
, mu-protobuf
|
||||
, mu-rpc
|
||||
, mu-schema
|
||||
, optics-core
|
||||
, sop-core
|
||||
, stm
|
||||
, stm-chans
|
||||
|
@ -101,7 +101,7 @@ instance ( KnownName name, FromProtoBufTypeRef rref r
|
||||
rpc = RPC pkgName srvName methodName
|
||||
|
||||
instance ( KnownName name, FromProtoBufTypeRef rref r
|
||||
, handler ~ (IO (ConduitT () (GRpcReply r) IO ())) )
|
||||
, handler ~ IO (ConduitT () (GRpcReply r) IO ()) )
|
||||
=> GRpcMethodCall ('Method name anns '[ ] ('RetStream rref)) handler where
|
||||
gRpcMethodCall pkgName srvName _ client
|
||||
= do -- Create a new TMChan
|
||||
|
132
grpc/client/src/Mu/GRpc/Client/Optics.hs
Normal file
132
grpc/client/src/Mu/GRpc/Client/Optics.hs
Normal file
@ -0,0 +1,132 @@
|
||||
{-# language AllowAmbiguousTypes #-}
|
||||
{-# language DataKinds #-}
|
||||
{-# language FlexibleInstances #-}
|
||||
{-# language FunctionalDependencies #-}
|
||||
{-# language GADTs #-}
|
||||
{-# language KindSignatures #-}
|
||||
{-# language RankNTypes #-}
|
||||
{-# language ScopedTypeVariables #-}
|
||||
{-# language TypeApplications #-}
|
||||
{-# language TypeOperators #-}
|
||||
{-# language UndecidableInstances #-}
|
||||
{-|
|
||||
Description : Client for gRPC services using optics and labels
|
||||
|
||||
For further information over initialization of the connection,
|
||||
consult the <http://hackage.haskell.org/package/http2-client-grpc http2-client-grpc docs>.
|
||||
-}
|
||||
module Mu.GRpc.Client.Optics (
|
||||
-- * Initialization of the gRPC client
|
||||
GRpcConnection
|
||||
, initGRpc
|
||||
, G.GrpcClientConfig
|
||||
, G.grpcClientConfigSimple
|
||||
-- * Request arguments and responses
|
||||
, CompressMode
|
||||
, GRpcReply(..)
|
||||
-- * Re-exported for convenience
|
||||
, module Optics.Core
|
||||
, module Mu.Schema.Optics
|
||||
) where
|
||||
|
||||
import Data.ByteString (ByteString)
|
||||
import qualified Data.ByteString.Char8 as BS
|
||||
import Data.Conduit
|
||||
import Data.Proxy
|
||||
import GHC.TypeLits
|
||||
import Network.GRPC.Client (CompressMode)
|
||||
import qualified Network.GRPC.Client.Helpers as G
|
||||
import Network.HTTP2.Client (ClientError)
|
||||
import Optics.Core
|
||||
|
||||
import Mu.GRpc.Client.Internal
|
||||
import Mu.Rpc
|
||||
import Mu.Schema
|
||||
import Mu.Schema.Optics
|
||||
|
||||
-- | Represents a connection to the service @s@.
|
||||
newtype GRpcConnection (s :: Service Symbol Symbol)
|
||||
= GRpcConnection { gcClient :: G.GrpcClient }
|
||||
|
||||
-- | Initializes a connection to a gRPC server.
|
||||
-- Usually the service you are connecting to is
|
||||
-- inferred from the usage later on.
|
||||
-- However, it can also be made explicit by using
|
||||
--
|
||||
-- > initGRpc config @Service
|
||||
--
|
||||
initGRpc :: G.GrpcClientConfig -- ^ gRPC configuration
|
||||
-> forall s. IO (Either ClientError (GRpcConnection s))
|
||||
initGRpc config = do
|
||||
setup <- setupGrpcClient' config
|
||||
case setup of
|
||||
Left e -> return $ Left e
|
||||
Right c -> return $ Right $ GRpcConnection c
|
||||
|
||||
instance forall (serviceName :: Symbol) anns (methods :: [Method Symbol]) (m :: Symbol) (t :: *).
|
||||
( SearchMethodOptic methods m t
|
||||
, KnownName serviceName
|
||||
, KnownName (FindPackageName anns))
|
||||
=> LabelOptic m A_Getter
|
||||
(GRpcConnection ('Service serviceName anns methods))
|
||||
(GRpcConnection ('Service serviceName anns methods))
|
||||
t t where
|
||||
labelOptic = to (searchMethodOptic (Proxy @methods) (Proxy @m) pkgName svrName . gcClient)
|
||||
where pkgName = BS.pack (nameVal (Proxy @(FindPackageName anns)))
|
||||
svrName = BS.pack (nameVal (Proxy @serviceName))
|
||||
|
||||
class SearchMethodOptic (methods :: [Method Symbol]) (m :: Symbol) t
|
||||
| methods m -> t where
|
||||
searchMethodOptic :: Proxy methods -> Proxy m -> ByteString -> ByteString -> G.GrpcClient -> t
|
||||
|
||||
{- Not possible due to functional dependency
|
||||
instance TypeError ('Text "could not find method " ':<>: ShowType m)
|
||||
=> SearchMethodOptic '[] m t where
|
||||
-}
|
||||
instance {-# OVERLAPS #-} MethodOptic ('Method name anns ins outs) t
|
||||
=> SearchMethodOptic ('Method name anns ins outs ': rest) name t where
|
||||
searchMethodOptic _ _ pkg srv = methodOptic pkg srv (Proxy @('Method name anns ins outs))
|
||||
instance {-# OVERLAPPABLE #-} SearchMethodOptic rest name t
|
||||
=> SearchMethodOptic ('Method other anns ins outs ': rest) name t where
|
||||
searchMethodOptic _ = searchMethodOptic (Proxy @rest)
|
||||
|
||||
class GRpcMethodCall method t => MethodOptic (method :: Method Symbol) t
|
||||
| method -> t where
|
||||
methodOptic :: ByteString -> ByteString -> Proxy method -> G.GrpcClient -> t
|
||||
methodOptic = gRpcMethodCall
|
||||
|
||||
-- No arguments
|
||||
instance forall (name :: Symbol) anns t.
|
||||
( GRpcMethodCall ('Method name anns '[ ] 'RetNothing) t
|
||||
, t ~ IO (GRpcReply ()) )
|
||||
=> MethodOptic ('Method name anns '[ ] 'RetNothing) t
|
||||
instance forall (name :: Symbol) (sch :: Schema Symbol Symbol) (r :: Symbol) anns t.
|
||||
( GRpcMethodCall ('Method name anns '[ ] ('RetSingle ('ViaSchema sch r))) t
|
||||
, t ~ IO (GRpcReply (Term Maybe sch (sch :/: r))) )
|
||||
=> MethodOptic ('Method name anns '[ ] ('RetSingle ('ViaSchema sch r))) t
|
||||
instance forall (name :: Symbol) (sch :: Schema Symbol Symbol) (r :: Symbol) anns t.
|
||||
( GRpcMethodCall ('Method name anns '[ ] ('RetStream ('ViaSchema sch r))) t
|
||||
, t ~ IO (ConduitT () (GRpcReply (Term Maybe sch (sch :/: r))) IO ()) )
|
||||
=> MethodOptic ('Method name anns '[ ] ('RetStream ('ViaSchema sch r))) t
|
||||
-- Simple arguments
|
||||
instance forall (name :: Symbol) (sch :: Schema Symbol Symbol) (v :: Symbol) anns t.
|
||||
( GRpcMethodCall ('Method name anns '[ 'ArgSingle ('ViaSchema sch v) ] 'RetNothing) t
|
||||
, t ~ (Term Maybe sch (sch :/: v) -> IO (GRpcReply ())) )
|
||||
=> MethodOptic ('Method name anns '[ 'ArgSingle ('ViaSchema sch v) ] 'RetNothing) t
|
||||
instance forall (name :: Symbol) (sch :: Schema Symbol Symbol) (v :: Symbol) (r :: Symbol) anns t.
|
||||
( GRpcMethodCall ('Method name anns '[ 'ArgSingle ('ViaSchema sch v) ] ('RetSingle ('ViaSchema sch r))) t
|
||||
, t ~ (Term Maybe sch (sch :/: v) -> IO (GRpcReply (Term Maybe sch (sch :/: r))) ) )
|
||||
=> MethodOptic ('Method name anns '[ 'ArgSingle ('ViaSchema sch v) ] ('RetSingle ('ViaSchema sch r))) t
|
||||
instance forall (name :: Symbol) (sch :: Schema Symbol Symbol) (v :: Symbol) (r :: Symbol) anns t.
|
||||
( GRpcMethodCall ('Method name anns '[ 'ArgSingle ('ViaSchema sch v) ] ('RetStream ('ViaSchema sch r))) t
|
||||
, t ~ (Term Maybe sch (sch :/: v) -> IO (ConduitT () (GRpcReply (Term Maybe sch (sch :/: r))) IO ()) ) )
|
||||
=> MethodOptic ('Method name anns '[ 'ArgSingle ('ViaSchema sch v) ] ('RetStream ('ViaSchema sch r))) t
|
||||
-- Stream arguments
|
||||
instance forall (name :: Symbol) (sch :: Schema Symbol Symbol) (v :: Symbol) (r :: Symbol) anns t.
|
||||
( GRpcMethodCall ('Method name anns '[ 'ArgStream ('ViaSchema sch v) ] ('RetSingle ('ViaSchema sch r))) t
|
||||
, t ~ (CompressMode -> IO (ConduitT (Term Maybe sch (sch :/: v)) Void IO (GRpcReply (Term Maybe sch (sch :/: r))))) )
|
||||
=> MethodOptic ('Method name anns '[ 'ArgStream ('ViaSchema sch v) ] ('RetSingle ('ViaSchema sch r))) t
|
||||
instance forall (name :: Symbol) (sch :: Schema Symbol Symbol) (v :: Symbol) (r :: Symbol) anns t.
|
||||
( GRpcMethodCall ('Method name anns '[ 'ArgStream ('ViaSchema sch v) ] ('RetStream ('ViaSchema sch r))) t
|
||||
, t ~ (CompressMode -> IO (ConduitT (Term Maybe sch (sch :/: v)) (GRpcReply (Term Maybe sch (sch :/: r))) IO ())) )
|
||||
=> MethodOptic ('Method name anns '[ 'ArgStream ('ViaSchema sch v) ] ('RetStream ('ViaSchema sch r))) t
|
@ -4,6 +4,7 @@ allow-newer: true
|
||||
packages:
|
||||
- core/schema
|
||||
- core/rpc
|
||||
- core/optics
|
||||
- adapter/avro
|
||||
- adapter/protobuf
|
||||
- adapter/persistent
|
||||
|
@ -4,6 +4,7 @@ allow-newer: true
|
||||
packages:
|
||||
- core/schema
|
||||
- core/rpc
|
||||
- core/optics
|
||||
- adapter/avro
|
||||
- adapter/protobuf
|
||||
- adapter/persistent
|
||||
@ -32,3 +33,5 @@ extra-deps:
|
||||
- stm-hamt-1.2.0.4
|
||||
- stm-containers-1.1.0.4
|
||||
- AC-Angle-1.0
|
||||
- optics-core-0.2
|
||||
- indexed-profunctors-0.1
|
||||
|
@ -25,12 +25,13 @@ executable {{name}}
|
||||
mu-grpc-server
|
||||
|
||||
{-# START_FILE stack.yaml #-}
|
||||
resolver: lts-14.21
|
||||
resolver: lts-14.22
|
||||
allow-newer: true
|
||||
extra-deps:
|
||||
# mu
|
||||
- mu-schema-0.1.0.0
|
||||
- mu-rpc-0.1.0.0
|
||||
- mu-optics-0.1.0.0
|
||||
- mu-protobuf-0.1.0.0
|
||||
- mu-grpc-server-0.1.0.1
|
||||
- compendium-client-0.1.0.1
|
||||
@ -87,12 +88,16 @@ import Mu.Schema
|
||||
|
||||
grpc "TheSchema" id "{{name}}.proto"
|
||||
|
||||
-- A. Map to Haskell types
|
||||
-- data Message
|
||||
-- = Message { ... }
|
||||
-- deriving ( Eq, Show, Generic
|
||||
-- , ToSchema Maybe TheSchema "Message"
|
||||
-- , FromSchema Maybe TheSchema "Message" )
|
||||
|
||||
-- B. Use optics
|
||||
type Message = Term Maybe TheSchema (TheSchema :/: "Message")
|
||||
|
||||
{-# START_FILE src/Main.hs #-}
|
||||
{-# language FlexibleContexts #-}
|
||||
{-# language PartialTypeSignatures #-}
|
||||
|
Loading…
Reference in New Issue
Block a user