From 09e0a5d0b813743c8a584671c4db720e0d74a612 Mon Sep 17 00:00:00 2001 From: Godefroy Ponsinet Date: Fri, 30 Nov 2018 13:47:03 +0100 Subject: [PATCH] feat(gql): fetch entities when event received Signed-off-by: Godefroy Ponsinet --- .../common/components/Screens/Chats/Add.js | 28 +- .../common/components/Screens/Chats/List.js | 2 +- .../graphql/mutations/ContactRequest.js | 10 +- .../graphql/mutations/ConversationCreate.js | 19 +- .../graphql/mutations/ConversationInvite.js | 19 +- .../common/graphql/queries/Conversation.js | 27 ++ .../graphql/queries/ConversationList.js | 2 +- .../subscriptions/ConversationInvite.js | 12 +- .../subscriptions/ConversationNewMessage.js | 9 +- .../graphql/updaters/conversationList.js | 10 +- .../common/relay/genericUpdater.js | 3 +- core/Makefile | 6 +- .../jsonclient/berty.node.service.gen.go | 8 +- core/api/node/graphql/resolver.go | 46 +-- .../api/node/graphql/service.gen.graphql.tmpl | 173 ++++----- core/api/node/service.proto | 10 +- core/api/p2p/event_test.go | 3 +- core/api/p2p/kind_test.go | 3 +- .../p2p/service/provider/provider.pb.go | 358 ------------------ core/node/event_handlers.go | 2 +- core/node/nodeapi.go | 14 +- 21 files changed, 197 insertions(+), 567 deletions(-) create mode 100644 client/react-native/common/graphql/queries/Conversation.js delete mode 100644 core/network/p2p/service/provider/provider.pb.go diff --git a/client/react-native/common/components/Screens/Chats/Add.js b/client/react-native/common/components/Screens/Chats/Add.js index 65c93ea8e7..90f509f136 100644 --- a/client/react-native/common/components/Screens/Chats/Add.js +++ b/client/react-native/common/components/Screens/Chats/Add.js @@ -151,19 +151,21 @@ export default class ListScreen extends Component { variables={queries.ContactList.defaultVariables} fragment={fragments.ContactList} alias='ContactList' - renderItem={props => ( - { - console.log(props) - const index = contactsID.lastIndexOf(props.data.id) - index < 0 - ? contactsID.push(props.data.id) - : contactsID.splice(index, 1) - this.setState({ contactsID }) - }} - /> - )} + renderItem={props => + props.data.status !== 42 ? ( + { + console.log(props) + const index = contactsID.lastIndexOf(props.data.id) + index < 0 + ? contactsID.push(props.data.id) + : contactsID.splice(index, 1) + this.setState({ contactsID }) + }} + /> + ) : null + } /> ) diff --git a/client/react-native/common/components/Screens/Chats/List.js b/client/react-native/common/components/Screens/Chats/List.js index 474749671e..fd18c3273e 100644 --- a/client/react-native/common/components/Screens/Chats/List.js +++ b/client/react-native/common/components/Screens/Chats/List.js @@ -34,7 +34,7 @@ const Item = fragments.Conversation(({ data, navigation }) => { {isRead ? 'No new message' : isInvite - ? 'You have been invited' + ? 'New conversation' : 'You have a new message'} diff --git a/client/react-native/common/graphql/mutations/ContactRequest.js b/client/react-native/common/graphql/mutations/ContactRequest.js index 8fe968d073..082e0d0e8d 100644 --- a/client/react-native/common/graphql/mutations/ContactRequest.js +++ b/client/react-native/common/graphql/mutations/ContactRequest.js @@ -1,6 +1,6 @@ import { graphql } from 'react-relay' -import { commit, genericUpdater } from '../../relay' +import { commit } from '../../relay' import { contact } from '../../utils' const ContactRequestMutation = graphql` @@ -42,11 +42,9 @@ export default context => (input, configs) => }, { updater: (store, data) => - genericUpdater(context.fragments.ContactList, 'ContactList', { - ...context.queries.ContactList.defaultVariables, - count: undefined, - cursor: undefined, - })(store, data.ContactRequest), + context.updaters.contactList.forEach(updater => + updater(store, data.ContactRequest) + ), ...configs, } ) diff --git a/client/react-native/common/graphql/mutations/ConversationCreate.js b/client/react-native/common/graphql/mutations/ConversationCreate.js index e0714d4691..a95236c3f3 100644 --- a/client/react-native/common/graphql/mutations/ConversationCreate.js +++ b/client/react-native/common/graphql/mutations/ConversationCreate.js @@ -53,15 +53,12 @@ export default context => (input, configs) => ConversationCreateMutation, 'ConversationCreate', input, - // { - // updater: (store, data) => { - // updaters.conversationList.forEach(updater => - // updater(store) - // .add('ConversationEdge', data.ConversationCreate.id) - // .after() - // ) - // }, - // ...configs, - // } - configs + { + updater: (store, data) => + console.log(data) || + context.updaters.conversationList.forEach(updater => + updater(store, data.ConversationCreate) + ), + ...configs, + } ) diff --git a/client/react-native/common/graphql/mutations/ConversationInvite.js b/client/react-native/common/graphql/mutations/ConversationInvite.js index 860427af02..a294ab52e0 100644 --- a/client/react-native/common/graphql/mutations/ConversationInvite.js +++ b/client/react-native/common/graphql/mutations/ConversationInvite.js @@ -1,7 +1,6 @@ import { graphql } from 'react-relay' import { commit } from '../../relay' -// import { updaters } from '..' const ConversationInviteMutation = graphql` mutation ConversationInviteMutation( @@ -52,15 +51,11 @@ export default context => (input, configs) => ConversationInviteMutation, 'ConversationInvite', input, - // { - // updater: (store, data) => { - // updaters.conversationList.forEach(updater => - // updater(store) - // .add('ConversationEdge', data.ConversationInvite.id) - // .after() - // ) - // }, - // ...configs, - // } - configs, + { + updater: (store, data) => + context.updaters.conversationList.forEach(updater => + updater(store, data.ConversationInvite) + ), + ...configs, + } ) diff --git a/client/react-native/common/graphql/queries/Conversation.js b/client/react-native/common/graphql/queries/Conversation.js new file mode 100644 index 0000000000..8ba7ee962b --- /dev/null +++ b/client/react-native/common/graphql/queries/Conversation.js @@ -0,0 +1,27 @@ +import { fetchQuery, graphql } from 'react-relay' + +import { merge } from '../../helpers' + +const query = graphql` + query ConversationQuery($id: ID!) { + GetConversation(id: $id) { + id + ...Conversation + } + } +` + +const defaultVariables = { + id: '', +} + +export default context => ({ + graphql: query, + defaultVariables, + fetch: variables => + fetchQuery( + context.environment, + query, + merge([defaultVariables, variables]) + ), +}) diff --git a/client/react-native/common/graphql/queries/ConversationList.js b/client/react-native/common/graphql/queries/ConversationList.js index a2b57a8d61..0baf16728d 100644 --- a/client/react-native/common/graphql/queries/ConversationList.js +++ b/client/react-native/common/graphql/queries/ConversationList.js @@ -24,7 +24,7 @@ const query = graphql` const defaultVariables = { filter: null, orderBy: 'updated_at', - orderDesc: false, + orderDesc: true, count: 50, cursor: '', } diff --git a/client/react-native/common/graphql/subscriptions/ConversationInvite.js b/client/react-native/common/graphql/subscriptions/ConversationInvite.js index d1ad175ebe..4041dfeb72 100644 --- a/client/react-native/common/graphql/subscriptions/ConversationInvite.js +++ b/client/react-native/common/graphql/subscriptions/ConversationInvite.js @@ -1,7 +1,8 @@ import { btoa } from 'b64-lite' -import EventStream from './EventStream' import { parseEmbedded } from '../../helpers/json' +import { queries } from '..' +import EventStream from './EventStream' export default context => ({ ...EventStream(context), @@ -9,13 +10,18 @@ export default context => ({ EventStream(context).subscribe({ updater: updater && - ((store, data) => { + (async (store, data) => { if (data.EventStream.kind === 301) { const attributes = parseEmbedded(data.EventStream.attributes) attributes.conversation.id = btoa( 'conversation:' + attributes.conversation.id ) - return updater && updater(store, attributes.conversation) + const conversation = await queries(context).Conversation.fetch({ + id: attributes.conversation.id, + }) + + console.log('ConversationInvite: conversation: ', conversation) + return updater && updater(store, conversation) } }), }), diff --git a/client/react-native/common/graphql/subscriptions/ConversationNewMessage.js b/client/react-native/common/graphql/subscriptions/ConversationNewMessage.js index ec916bd89c..c75e30a77f 100644 --- a/client/react-native/common/graphql/subscriptions/ConversationNewMessage.js +++ b/client/react-native/common/graphql/subscriptions/ConversationNewMessage.js @@ -1,4 +1,5 @@ import EventStream from './EventStream' +import { queries } from '..' export default context => ({ ...EventStream(context), @@ -6,9 +7,13 @@ export default context => ({ EventStream(context).subscribe({ updater: updater && - ((store, data) => { + (async (store, data) => { if (data.EventStream.kind === 302) { - return updater(store, data.EventStream) + const conversation = await queries(context).Conversation.fetch({ + id: data.EventStream.conversationId, + }) + console.log('ConversationNewMessage: conversation:', conversation) + return updater(store, conversation) } }), }), diff --git a/client/react-native/common/graphql/updaters/conversationList.js b/client/react-native/common/graphql/updaters/conversationList.js index b31b3730a1..fb0818134b 100644 --- a/client/react-native/common/graphql/updaters/conversationList.js +++ b/client/react-native/common/graphql/updaters/conversationList.js @@ -1 +1,9 @@ -export default context => [] +import { genericUpdater } from '../../relay' + +export default context => [ + genericUpdater(context.fragments.ConversationList, 'ConversationList', { + ...context.queries.ConversationList.defaultVariables, + count: undefined, + cursor: undefined, + }), +] diff --git a/client/react-native/common/relay/genericUpdater.js b/client/react-native/common/relay/genericUpdater.js index 4431e31a78..1467972f69 100644 --- a/client/react-native/common/relay/genericUpdater.js +++ b/client/react-native/common/relay/genericUpdater.js @@ -47,7 +47,8 @@ export default (fragment, alias, args) => { ConnectionHandler.deleteNode(connection, data.id) return } - + console.log(args) + // get all edges const edges = connection.getLinkedRecords('edges') const field = Case.camel(args.orderBy || args.sortBy || 'id') const cursor = diff --git a/core/Makefile b/core/Makefile index 21d42b3f78..33e7eb6d31 100644 --- a/core/Makefile +++ b/core/Makefile @@ -15,10 +15,10 @@ GENERATED_FILES = \ $(call rwildcard $(CODE_PATHS), *.gen.js) \ $(call rwildcard $(CODE_PATHS), *.gen.graphql) GENERATION_TARGETS = \ + .kind.generated \ .client.generated \ + .pb.generated \ .gql.generated \ - .kind.generated \ - .pb.generated CGO_LDFLAGS ?= -L/usr/local/opt/openssl/lib CGO_CPPFLAGS ?= -I/usr/local/opt/openssl/include @@ -166,7 +166,7 @@ dev-deps: .gql.generated: $(PROTOS) .pb.generated mkdir -p ./api/node/graphql - $(PROTOC) $(PROTOC_OPTS) --gotemplate_out=debug=false,all=true,template_dir=./api/node:./api/node ./api/node/*.proto + $(PROTOC) $(PROTOC_OPTS) --gotemplate_out=debug=false,all=true,template_dir=./api/node:./api/node ./api/node/service.proto goimports -w ./api/node/*.gen.go ./api/node/graphql/*.gen.go cd ./api/node/graphql && $(GQLGEN) -c gqlgen.gen.yml -v gen cp ./api/node/graphql/service.gen.graphql ../client/react-native/common/schema.graphql diff --git a/core/api/client/jsonclient/berty.node.service.gen.go b/core/api/client/jsonclient/berty.node.service.gen.go index dd35eadb05..148b9e8cd5 100644 --- a/core/api/client/jsonclient/berty.node.service.gen.go +++ b/core/api/client/jsonclient/berty.node.service.gen.go @@ -125,7 +125,7 @@ func NodeGetEvent(client *client.Client, ctx context.Context, jsonInput []byte) zap.String("method", "GetEvent"), zap.String("input", string(jsonInput)), ) - var typedInput p2p.Event + var typedInput graphql.Node if err := json.Unmarshal(jsonInput, &typedInput); err != nil { return nil, err } @@ -225,7 +225,7 @@ func NodeGetContact(client *client.Client, ctx context.Context, jsonInput []byte zap.String("method", "GetContact"), zap.String("input", string(jsonInput)), ) - var typedInput entity.Contact + var typedInput graphql.Node if err := json.Unmarshal(jsonInput, &typedInput); err != nil { return nil, err } @@ -313,7 +313,7 @@ func NodeGetConversation(client *client.Client, ctx context.Context, jsonInput [ zap.String("method", "GetConversation"), zap.String("input", string(jsonInput)), ) - var typedInput entity.Conversation + var typedInput graphql.Node if err := json.Unmarshal(jsonInput, &typedInput); err != nil { return nil, err } @@ -325,7 +325,7 @@ func NodeGetConversationMember(client *client.Client, ctx context.Context, jsonI zap.String("method", "GetConversationMember"), zap.String("input", string(jsonInput)), ) - var typedInput entity.ConversationMember + var typedInput graphql.Node if err := json.Unmarshal(jsonInput, &typedInput); err != nil { return nil, err } diff --git a/core/api/node/graphql/resolver.go b/core/api/node/graphql/resolver.go index 0ad06c0194..1f8889ae66 100644 --- a/core/api/node/graphql/resolver.go +++ b/core/api/node/graphql/resolver.go @@ -8,9 +8,6 @@ import ( "strings" "time" - "github.com/golang/protobuf/protoc-gen-go/descriptor" - "go.uber.org/zap" - "berty.tech/core/api/node" "berty.tech/core/api/node/graphql/graph/generated" "berty.tech/core/api/node/graphql/models" @@ -19,6 +16,8 @@ import ( "berty.tech/core/entity" "berty.tech/core/network" "berty.tech/core/pkg/deviceinfo" + "github.com/golang/protobuf/protoc-gen-go/descriptor" + "go.uber.org/zap" ) type Resolver struct { @@ -36,21 +35,12 @@ func (r *Resolver) GqlNode() generated.GqlNodeResolver { func (r *Resolver) BertyEntityContact() generated.BertyEntityContactResolver { return &bertyEntityContactResolver{r} } -func (r *Resolver) BertyEntityContactPayload() generated.BertyEntityContactPayloadResolver { - return &bertyEntityContactResolver{r} -} func (r *Resolver) BertyEntityConversation() generated.BertyEntityConversationResolver { return &bertyEntityConversationResolver{r} } func (r *Resolver) BertyEntityConversationMember() generated.BertyEntityConversationMemberResolver { return &bertyEntityConversationMemberResolver{r} } -func (r *Resolver) BertyEntityConversationMemberPayload() generated.BertyEntityConversationMemberPayloadResolver { - return &bertyEntityConversationMemberResolver{r} -} -func (r *Resolver) BertyEntityConversationPayload() generated.BertyEntityConversationPayloadResolver { - return &bertyEntityConversationResolver{r} -} func (r *Resolver) BertyEntityDevice() generated.BertyEntityDeviceResolver { return &bertyEntityDeviceResolver{r} } @@ -61,12 +51,6 @@ func (r *Resolver) BertyP2pEvent() generated.BertyP2pEventResolver { // func (r *Resolver) BertyP2pPeer() generated.BertyP2pPeerResolver { // return &bertyP2pPeerResolver{r} // } -// func (r *Resolver) BertyP2pPeerPayload() generated.BertyP2pPeerPayloadResolver { -// return &bertyP2pPeerResolver{r} -// } -func (r *Resolver) BertyP2pEventPayload() generated.BertyP2pEventPayloadResolver { - return &bertyP2pEventResolver{r} -} func (r *Resolver) GoogleProtobufFieldDescriptorProto() generated.GoogleProtobufFieldDescriptorProtoResolver { return &googleProtobufFieldDescriptorProtoResolver{r} } @@ -93,7 +77,7 @@ func (r *Resolver) Subscription() generated.SubscriptionResolver { type gqlNodeResolver struct{ *Resolver } func (r *gqlNodeResolver) ID(ctx context.Context, obj *gql.Node) (string, error) { - // TODO: find the id in db to define the table + // TODO: update entity id in db to have unique IDs in whole database return "unknown:" + obj.ID, nil } @@ -264,13 +248,13 @@ func (r *queryResolver) Node(ctx context.Context, id string) (models.Node, error gID := strings.SplitN(id, ":", 2) switch gID[0] { case "contact": - return r.client.GetContact(ctx, &entity.Contact{ID: id}) + return r.GetContact(ctx, id) case "conversation": - return r.client.GetConversation(ctx, &entity.Conversation{ID: id}) + return r.GetConversation(ctx, id) case "conversation_member": - return r.client.GetConversationMember(ctx, &entity.ConversationMember{ID: id}) + return r.GetConversationMember(ctx, id) case "event": - return r.client.GetEvent(ctx, &p2p.Event{ID: id}) + return r.GetEvent(ctx, id) default: logger().Warn("unknown node type", zap.String("node_type", gID[0])) return nil, nil @@ -390,8 +374,8 @@ func (r *queryResolver) EventList(ctx context.Context, filter *p2p.Event, rawOnl return output, nil } -func (r *queryResolver) GetEvent(ctx context.Context, id string, senderID string, createdAt *time.Time, updatedAt *time.Time, sentAt *time.Time, receivedAt *time.Time, ackedAt *time.Time, direction *int32, senderAPIVersion uint32, receiverAPIVersion uint32, receiverID string, kind *int32, attributes []byte, conversationID string, seenAt *time.Time, metadata []*p2p.MetadataKeyValue) (*p2p.Event, error) { - return r.client.GetEvent(ctx, &p2p.Event{ +func (r *queryResolver) GetEvent(ctx context.Context, id string) (*p2p.Event, error) { + return r.client.GetEvent(ctx, &gql.Node{ ID: strings.SplitN(id, ":", 2)[1], }) } @@ -472,8 +456,8 @@ func (r *queryResolver) ContactList(ctx context.Context, filter *entity.Contact, output.PageInfo.HasNextPage = hasNextPage return output, nil } -func (r *queryResolver) GetContact(ctx context.Context, id string, createdAt *time.Time, updatedAt *time.Time, sigchain []byte, status *int32, devices []*entity.Device, displayName string, displayStatus string, overrideDisplayName string, overrideDisplayStatus string) (*entity.Contact, error) { - return r.client.GetContact(ctx, &entity.Contact{ID: id}) +func (r *queryResolver) GetContact(ctx context.Context, id string) (*entity.Contact, error) { + return r.client.GetContact(ctx, &gql.Node{ID: strings.SplitN(id, ":", 2)[1]}) } func (r *queryResolver) ConversationList(ctx context.Context, filter *entity.Conversation, orderBy string, orderDesc bool, first *int32, after *string, last *int32, before *string) (*node.ConversationListConnection, error) { if filter != nil && filter.ID != "" { @@ -551,11 +535,11 @@ func (r *mutationResolver) ConversationRead(ctx context.Context, id string) (*en }) } -func (r *queryResolver) GetConversation(ctx context.Context, id string, createdAt *time.Time, updatedAt *time.Time, readAt *time.Time, title string, topic string, members []*entity.ConversationMember) (*entity.Conversation, error) { - return r.client.GetConversation(ctx, &entity.Conversation{ID: id}) +func (r *queryResolver) GetConversation(ctx context.Context, id string) (*entity.Conversation, error) { + return r.client.GetConversation(ctx, &gql.Node{ID: strings.SplitN(id, ":", 2)[1]}) } -func (r *queryResolver) GetConversationMember(ctx context.Context, id string, createdAt *time.Time, updatedAt *time.Time, status *int32, contact *entity.Contact, conversationID string, contactID string) (*entity.ConversationMember, error) { - return r.client.GetConversationMember(ctx, &entity.ConversationMember{ID: id}) +func (r *queryResolver) GetConversationMember(ctx context.Context, id string) (*entity.ConversationMember, error) { + return r.client.GetConversationMember(ctx, &gql.Node{ID: strings.SplitN(id, ":", 2)[1]}) } func (r *queryResolver) DeviceInfos(ctx context.Context, T bool) (*deviceinfo.DeviceInfos, error) { return r.client.DeviceInfos(ctx, &node.Void{T: true}) diff --git a/core/api/node/graphql/service.gen.graphql.tmpl b/core/api/node/graphql/service.gen.graphql.tmpl index f10f57101c..e51e98b612 100644 --- a/core/api/node/graphql/service.gen.graphql.tmpl +++ b/core/api/node/graphql/service.gen.graphql.tmpl @@ -35,7 +35,6 @@ interface Node { {{- range .File.EnumType}} {{/* - template "Enum" . */}} {{- end}} - {{- range .File.MessageType}} {{- if .EnumType}} {{- setStore "message_name" .Name}} @@ -65,19 +64,54 @@ interface Node { {{- end}} {{- end}} +{{- define "MessageField"}} + {{- $type := getStore .TypeName}} + {{- $typeName := .TypeName | replace "." "_" | camelCase | replace "_" ""}} + + {{- if (boolFieldExtension 53006 .)}} + {{- template "Fields" $type.Field}} + {{- else}} + + {{- if eq (boolFieldExtension 53009 .) true}} + {{.JsonName}}: {{if isFieldRepeated .}}[{{$typeName}}!]{{else}}{{$typeName}}!{{end}} + {{- else}} + {{.JsonName}}: {{if isFieldRepeated .}}[{{$typeName}}]{{else}}{{$typeName}}{{end}} + {{- end}} + {{- end}} +{{- end}} + +{{- define "InputMessageField"}} + {{- $type := getStore .TypeName}} + {{- $typeName := .TypeName}} + + {{- if (boolFieldExtension 53006 .)}} + {{- template "InputFields" $type.Field}} + {{- else}} + + {{- if eq (boolFieldExtension 53009 .) true}} + {{.JsonName}}: {{if isFieldRepeated .}}[{{template "InputName" $typeName}}!]{{else}}{{template "InputName" $typeName}}!{{end}} + {{- else}} + {{.JsonName}}: {{if isFieldRepeated .}}[{{template "InputName" $typeName}}]{{else}}{{template "InputName" $typeName}}{{end}} + {{- end}} + {{- end}} +{{- end}} + {{- define "ScalarField"}} {{- if (boolFieldExtension 53004 .)}} {{.JsonName}}: ID! {{- else}} + {{- $typeName := .Type | string | replace "TYPE_" "" | lower | camelCase}} + {{- $isFieldRepeated := isFieldRepeated .}} + {{- $isFieldNullable := boolFieldExtension 53008 .}} {{- if eq (.Type | string) "TYPE_BYTES"}} - {{.JsonName}}: [Byte!], + {{- $typeName = "Byte"}} + {{- $isFieldRepeated = true}} + {{- $isFieldNullable = true}} + {{- end}} + {{- if $isFieldNullable}} + {{.JsonName}}: {{if $isFieldRepeated}}[{{$typeName}}!]{{else}}{{$typeName}}{{end}} {{- else}} - {{- $typeName := .Type | string | replace "TYPE_" "" | lower | camelCase}} - {{- if (boolFieldExtension 53008 .) true}} - {{.JsonName}}: {{if isFieldRepeated .}}[{{$typeName}}!]{{else}}{{$typeName}}{{end}} - {{- else}} - {{.JsonName}}: {{if isFieldRepeated .}}[{{$typeName}}!]{{else}}{{$typeName}}!{{end}} - {{- end}} + {{.JsonName}}: {{if $isFieldRepeated}}[{{$typeName}}!]{{else}}{{$typeName}}!{{end}} {{- end}} {{- end}} {{- end}} @@ -88,66 +122,40 @@ interface Node { {{- end}} {{- define "Field"}} - {{- $messageName := getStore "message_name"}} - - {{- if .}} - {{- range .}} - {{- if (eq (.Type | string) "TYPE_MESSAGE")}} - {{- if (boolFieldExtension 53006 .)}} - {{- template "Field" (getStore .TypeName).Field}} - {{- else}} - {{- $typeName := .TypeName | replace "." "_" | camelCase | replace "_" ""}} - {{- if eq (boolFieldExtension 53009 .) true}} - {{.JsonName}}: {{if isFieldRepeated .}}[{{$typeName}}!]{{else}}{{$typeName}}!{{end}} - {{- else}} - {{.JsonName}}: {{if isFieldRepeated .}}[{{$typeName}}]{{else}}{{$typeName}}{{end}} - {{- end}} - {{- end}} - {{- else if (eq (.Type | string) "TYPE_ENUM")}} - {{- template "EnumField" .}} - {{- else }} - {{- template "ScalarField" .}} - {{- end}} - {{- end}} + {{- if (eq (.Type | string) "TYPE_MESSAGE")}} + {{- template "MessageField" .}} + {{- else if (eq (.Type | string) "TYPE_ENUM")}} + {{- template "EnumField" .}} {{- else}} - T: Boolean + {{- template "ScalarField" .}} {{- end}} {{- end}} -{{- define "ArgumentScalarField"}} - {{- if (boolFieldExtension 53004 .)}} - {{.JsonName}}: ID! - {{- else}} - {{- if eq (.Type | string) "TYPE_BYTES"}} - {{.JsonName}}: [Byte!], - {{- else}} - {{- $typeName := .Type | string | replace "TYPE_" "" | lower | camelCase}} - {{.JsonName}}: {{if isFieldRepeated .}}[{{$typeName}}!]{{else}}{{$typeName}}{{end}} - {{- end}} +{{- define "InputField"}} + {{- if (eq (.Type | string) "TYPE_MESSAGE")}} + {{- template "InputMessageField" .}} + {{- else if (eq (.Type | string) "TYPE_ENUM")}} + {{- template "EnumField" .}} + {{- else }} + {{- template "ScalarField" .}} {{- end}} {{- end}} -{{- define "InputField"}} +{{- define "Fields"}} {{- $messageName := getStore "message_name"}} + {{- if .}} + {{- range .}} + {{- template "Field" .}} + {{- end}} + {{- else}} + T: Boolean + {{- end}} +{{- end}} +{{- define "InputFields"}} {{- if .}} {{- range .}} - {{- if (eq (.Type | string) "TYPE_MESSAGE")}} - {{- if (boolFieldExtension 53006 .)}} - {{- template "InputField" (getStore .TypeName).Field}} - {{- else}} - {{- $typeName := .TypeName | replace "." "_" | camelCase | replace "_" ""}} - {{- if eq (boolFieldExtension 53009 .) true}} - {{.JsonName}}: {{if isFieldRepeated .}}[{{template "InputName" .TypeName}}!]{{else}}{{template "InputName" .TypeName}}!{{end}} - {{- else}} - {{.JsonName}}: {{if isFieldRepeated .}}[{{template "InputName" .TypeName}}]{{else}}{{template "InputName" .TypeName}}{{end}} - {{- end}} - {{- end}} - {{- else if (eq (.Type | string) "TYPE_ENUM")}} - {{- template "EnumField" .}} - {{- else }} - {{- template "ScalarField" .}} - {{- end}} + {{- template "InputField" .}} {{- end}} {{- else}} T: Boolean @@ -169,9 +177,9 @@ enum {{$file.Package | replace "." "_" | camelCase}}{{$messageName}}{{.Name}} { {{- $file := getStore "file"}} {{- $messageName := getStore "message_name"}} {{- if eq (concat .Name "") "Timestamp"}} - {{- else if (and (eq (.Name | regexMatch ".*Input") false) (eq (.Name | regexMatch ".*Output") false)) }} + {{- else if (eq (.Name | regexMatch ".*Input") false) }} type {{$file.Package | replace "." "_" | camelCase}}{{$messageName}}{{.Name}} {{template "ImplementNode" .}} { - {{- template "Field" .Field}} + {{- template "Fields" .Field}} } {{- end}} {{- end}} @@ -182,20 +190,7 @@ type {{$file.Package | replace "." "_" | camelCase}}{{$messageName}}{{.Name}} {{ {{- if eq (concat $type.Name "") "Timestamp"}} {{- else}} input {{template "InputName" .}} { - {{- template "InputField" $type.Field}} -} - {{- end}} - {{- end}} -{{- end}} - -{{- define "Payload"}} - {{- $type := getStore .}} - {{- if $type}} - {{- if eq (concat $type.Name "") "Timestamp"}} - {{- else }} - {{- template "ImplementNode"}} -type {{template "PayloadName" .}} {{- template "ImplementNode"}} { - {{- template "Field" $type.Field}} + {{- template "InputFields" $type.Field}} } {{- end}} {{- end}} @@ -217,13 +212,7 @@ type {{template "PayloadName" .}} {{- template "ImplementNode"}} { {{- $type := getStore .}} {{- if $type}} {{- $typeName := . | replace "." "_" | camelCase | replace "_" ""}} - {{- if $typeName | regexMatch ".*Connection"}} - {{- $typeName}} - {{- else if $typeName | regexMatch ".*Output"}} - {{- $typeName | replace "Output" "Payload"}} - {{- else}} - {{- $typeName}}Payload - {{- end}} + {{- $typeName}} {{- end}} {{- end}} @@ -255,28 +244,6 @@ type {{template "PayloadName" .}} {{- template "ImplementNode"}} { {{- if .InputType}} {{- template "RecursiveInput" .InputType}} {{- end}} - {{- if (stringMethodOptionsExtension 53007 .)}} - {{- if eq ((stringMethodOptionsExtension 53007 .) | regexMatch ".*(Payload|Connection)$") false}} - {{- $type := getStore (stringMethodOptionsExtension 53007 .)}} - {{- $alreadyDefinedKey := concat (stringMethodOptionsExtension 53007 .) ".PayloadAlreadyDefined"}} - {{- $alreadyDefined := getStore $alreadyDefinedKey}} - {{- if $alreadyDefined}} - {{- else}} - {{- template "Payload" (stringMethodOptionsExtension 53007 .)}} - {{- end}} - {{- setStore $alreadyDefinedKey true}} - {{- end}} - {{- else if .OutputType}} - {{- if eq (.OutputType | regexMatch ".*(Payload|Connection)$") false}} - {{- $alreadyDefinedKey := concat .OutputType ".PayloadAlreadyDefined"}} - {{- $alreadyDefined := getStore $alreadyDefinedKey}} - {{- if $alreadyDefined}} - {{- else}} - {{- template "Payload" .OutputType}} - {{- end}} - {{- setStore $alreadyDefinedKey true}} - {{- end}} - {{- end}} {{- end}} {{- end}} {{- end}} @@ -285,7 +252,7 @@ type {{template "PayloadName" .}} {{- template "ImplementNode"}} { {{.Name}} {{- if .InputType -}} ( - {{- template "Arguments" (getStore .InputType).Field}} + {{- template "InputFields" (getStore .InputType).Field}} ) {{- end}} {{- if (stringMethodOptionsExtension 53007 .) -}} diff --git a/core/api/node/service.proto b/core/api/node/service.proto index fb1e19eba7..09c5afd915 100644 --- a/core/api/node/service.proto +++ b/core/api/node/service.proto @@ -37,12 +37,12 @@ service Service { option (gql.graphql_output) = ".berty.node.EventListConnection"; option (gql.graphql_type) = "Query"; }; - rpc GetEvent (berty.p2p.Event) returns (berty.p2p.Event) { + rpc GetEvent (gql.Node) returns (berty.p2p.Event) { option (gql.graphql_type) = "Query"; }; rpc EventSeen (EventIDInput) returns (berty.p2p.Event) { option (gql.graphql_type) = "Mutation"; - }; + } // // Contacts @@ -64,7 +64,7 @@ service Service { option (gql.graphql_output) = ".berty.node.ContactListConnection"; option (gql.graphql_type) = "Query"; }; - rpc GetContact (berty.entity.Contact) returns (berty.entity.Contact) { + rpc GetContact (gql.Node) returns (berty.entity.Contact) { option (gql.graphql_type) = "Query"; }; @@ -88,10 +88,10 @@ service Service { rpc ConversationAddMessage (ConversationAddMessageInput) returns (berty.p2p.Event) { option (gql.graphql_type) = "Mutation"; }; - rpc GetConversation (berty.entity.Conversation) returns (berty.entity.Conversation) { + rpc GetConversation (gql.Node) returns (berty.entity.Conversation) { option (gql.graphql_type) = "Query"; }; - rpc GetConversationMember (berty.entity.ConversationMember) returns (berty.entity.ConversationMember) { + rpc GetConversationMember (gql.Node) returns (berty.entity.ConversationMember) { option (gql.graphql_type) = "Query"; }; rpc ConversationRead (gql.Node) returns (berty.entity.Conversation) { diff --git a/core/api/p2p/event_test.go b/core/api/p2p/event_test.go index a21cfbd480..a71a0fb5dd 100644 --- a/core/api/p2p/event_test.go +++ b/core/api/p2p/event_test.go @@ -5,9 +5,8 @@ import ( "testing" "time" - "github.com/jinzhu/gorm" - "berty.tech/core/test/mock" + "github.com/jinzhu/gorm" ) func setupNonAcknowledgedEventDestinations() (string, *gorm.DB, time.Time, time.Time, time.Time) { diff --git a/core/api/p2p/kind_test.go b/core/api/p2p/kind_test.go index 45e86c51d7..b59b558e8e 100644 --- a/core/api/p2p/kind_test.go +++ b/core/api/p2p/kind_test.go @@ -3,9 +3,8 @@ package p2p import ( "testing" - . "github.com/smartystreets/goconvey/convey" - "berty.tech/core/entity" + . "github.com/smartystreets/goconvey/convey" ) func TestEvent_GetAttrs(t *testing.T) { diff --git a/core/network/p2p/service/provider/provider.pb.go b/core/network/p2p/service/provider/provider.pb.go deleted file mode 100644 index 09f65e70dc..0000000000 --- a/core/network/p2p/service/provider/provider.pb.go +++ /dev/null @@ -1,358 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: network/p2p/protocol/service/provider/provider.proto - -/* - Package provider is a generated protocol buffer package. - - It is generated from these files: - network/p2p/protocol/service/provider/provider.proto - - It has these top-level messages: - ProviderInfo -*/ -package provider - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -import io "io" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type ProviderInfo struct { - PeerId string `protobuf:"bytes,1,opt,name=peer_id,json=peerId,proto3" json:"peer_id,omitempty"` - PeerInfo []byte `protobuf:"bytes,2,opt,name=peer_info,json=peerInfo,proto3" json:"peer_info,omitempty"` -} - -func (m *ProviderInfo) Reset() { *m = ProviderInfo{} } -func (m *ProviderInfo) String() string { return proto.CompactTextString(m) } -func (*ProviderInfo) ProtoMessage() {} -func (*ProviderInfo) Descriptor() ([]byte, []int) { return fileDescriptorProvider, []int{0} } - -func (m *ProviderInfo) GetPeerId() string { - if m != nil { - return m.PeerId - } - return "" -} - -func (m *ProviderInfo) GetPeerInfo() []byte { - if m != nil { - return m.PeerInfo - } - return nil -} - -func init() { - proto.RegisterType((*ProviderInfo)(nil), "provider.ProviderInfo") -} -func (m *ProviderInfo) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalTo(dAtA) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *ProviderInfo) MarshalTo(dAtA []byte) (int, error) { - var i int - _ = i - var l int - _ = l - if len(m.PeerId) > 0 { - dAtA[i] = 0xa - i++ - i = encodeVarintProvider(dAtA, i, uint64(len(m.PeerId))) - i += copy(dAtA[i:], m.PeerId) - } - if len(m.PeerInfo) > 0 { - dAtA[i] = 0x12 - i++ - i = encodeVarintProvider(dAtA, i, uint64(len(m.PeerInfo))) - i += copy(dAtA[i:], m.PeerInfo) - } - return i, nil -} - -func encodeVarintProvider(dAtA []byte, offset int, v uint64) int { - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return offset + 1 -} -func (m *ProviderInfo) Size() (n int) { - var l int - _ = l - l = len(m.PeerId) - if l > 0 { - n += 1 + l + sovProvider(uint64(l)) - } - l = len(m.PeerInfo) - if l > 0 { - n += 1 + l + sovProvider(uint64(l)) - } - return n -} - -func sovProvider(x uint64) (n int) { - for { - n++ - x >>= 7 - if x == 0 { - break - } - } - return n -} -func sozProvider(x uint64) (n int) { - return sovProvider(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *ProviderInfo) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProvider - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: ProviderInfo: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: ProviderInfo: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PeerId", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProvider - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProvider - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.PeerId = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PeerInfo", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProvider - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthProvider - } - postIndex := iNdEx + byteLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.PeerInfo = append(m.PeerInfo[:0], dAtA[iNdEx:postIndex]...) - if m.PeerInfo == nil { - m.PeerInfo = []byte{} - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProvider(dAtA[iNdEx:]) - if err != nil { - return err - } - if skippy < 0 { - return ErrInvalidLengthProvider - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipProvider(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowProvider - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowProvider - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - return iNdEx, nil - case 1: - iNdEx += 8 - return iNdEx, nil - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowProvider - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - iNdEx += length - if length < 0 { - return 0, ErrInvalidLengthProvider - } - return iNdEx, nil - case 3: - for { - var innerWire uint64 - var start int = iNdEx - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowProvider - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - innerWire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - innerWireType := int(innerWire & 0x7) - if innerWireType == 4 { - break - } - next, err := skipProvider(dAtA[start:]) - if err != nil { - return 0, err - } - iNdEx = start + next - } - return iNdEx, nil - case 4: - return iNdEx, nil - case 5: - iNdEx += 4 - return iNdEx, nil - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - } - panic("unreachable") -} - -var ( - ErrInvalidLengthProvider = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowProvider = fmt.Errorf("proto: integer overflow") -) - -func init() { - proto.RegisterFile("network/p2p/protocol/service/provider/provider.proto", fileDescriptorProvider) -} - -var fileDescriptorProvider = []byte{ - // 178 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x32, 0xc9, 0x4b, 0x2d, 0x29, - 0xcf, 0x2f, 0xca, 0xd6, 0x2f, 0x30, 0x2a, 0xd0, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0xce, 0xcf, - 0xd1, 0x2f, 0x4e, 0x2d, 0x2a, 0xcb, 0x4c, 0x4e, 0x05, 0x09, 0x94, 0x65, 0xa6, 0xa4, 0x16, 0xc1, - 0x19, 0x7a, 0x60, 0x25, 0x42, 0x1c, 0x30, 0xbe, 0x92, 0x0b, 0x17, 0x4f, 0x00, 0x94, 0xed, 0x99, - 0x97, 0x96, 0x2f, 0x24, 0xce, 0xc5, 0x5e, 0x90, 0x9a, 0x5a, 0x14, 0x9f, 0x99, 0x22, 0xc1, 0xa8, - 0xc0, 0xa8, 0xc1, 0x19, 0xc4, 0x06, 0xe2, 0x7a, 0xa6, 0x08, 0x49, 0x73, 0x71, 0x42, 0x24, 0xf2, - 0xd2, 0xf2, 0x25, 0x98, 0x14, 0x18, 0x35, 0x78, 0x82, 0x38, 0xc0, 0x52, 0x79, 0x69, 0xf9, 0x4e, - 0x5e, 0x27, 0x1e, 0xc9, 0x31, 0x5e, 0x78, 0x24, 0xc7, 0xf8, 0xe0, 0x91, 0x1c, 0xe3, 0x8c, 0xc7, - 0x72, 0x0c, 0x51, 0x16, 0xe9, 0x99, 0x25, 0x19, 0xa5, 0x49, 0x7a, 0xc9, 0xf9, 0xb9, 0xfa, 0x49, - 0xa9, 0x45, 0x25, 0x95, 0x50, 0x32, 0x39, 0xbf, 0x28, 0x55, 0x1f, 0xd9, 0xcd, 0xe8, 0x4e, 0x4d, - 0x62, 0x03, 0x3b, 0xd1, 0x18, 0x10, 0x00, 0x00, 0xff, 0xff, 0xdc, 0x85, 0x35, 0xfe, 0xda, 0x00, - 0x00, 0x00, -} diff --git a/core/node/event_handlers.go b/core/node/event_handlers.go index 5758861dab..5daeffd1aa 100644 --- a/core/node/event_handlers.go +++ b/core/node/event_handlers.go @@ -138,7 +138,7 @@ func (n *Node) handleConversationNewMessage(ctx context.Context, input *p2p.Even } // say that conversation has not been read - n.sql.Save(&entity.Conversation{ID: input.ConversationID, ReadAt: time.Time{}}) + n.sql(ctx).Save(&entity.Conversation{ID: input.ConversationID, ReadAt: time.Time{}}) return nil } diff --git a/core/node/nodeapi.go b/core/node/nodeapi.go index c49b23fdc1..6d184a396a 100644 --- a/core/node/nodeapi.go +++ b/core/node/nodeapi.go @@ -102,21 +102,21 @@ func (n *Node) EventSeen(ctx context.Context, input *gql.Node) (*p2p.Event, erro func (n *Node) ConversationRead(ctx context.Context, input *gql.Node) (*entity.Conversation, error) { // get conversation conversation := &entity.Conversation{ID: input.ID} - if err := n.sql.Model(conversation).Where(conversation).First(conversation).Error; err != nil { + if err := n.sql(ctx).Model(conversation).Where(conversation).First(conversation).Error; err != nil { return nil, err } // check if last message has been read event := &p2p.Event{ConversationID: conversation.ID} count := 0 - n.sql.Model(event).Where(event).Order("created_at").Count(&count).Last(event) + n.sql(ctx).Model(event).Where(event).Order("created_at").Count(&count).Last(event) if count > 0 && event.SeenAt == nil { return conversation, nil } // set conversation as read conversation.ReadAt = time.Now().UTC() - if err := n.sql.Save(conversation).Error; err != nil { + if err := n.sql(ctx).Save(conversation).Error; err != nil { return nil, errors.Wrap(err, "cannot update conversation") } @@ -124,7 +124,7 @@ func (n *Node) ConversationRead(ctx context.Context, input *gql.Node) (*entity.C } // GetEvent implements berty.node.GetEvent -func (n *Node) GetEvent(ctx context.Context, input *p2p.Event) (*p2p.Event, error) { +func (n *Node) GetEvent(ctx context.Context, input *gql.Node) (*p2p.Event, error) { var span opentracing.Span span, ctx = tracing.EnterFunc(ctx, input) defer span.Finish() @@ -330,7 +330,7 @@ func (n *Node) ContactList(input *node.ContactListInput, stream node.Service_Con } // GetContact implements berty.node.GetContact -func (n *Node) GetContact(ctx context.Context, input *entity.Contact) (*entity.Contact, error) { +func (n *Node) GetContact(ctx context.Context, input *gql.Node) (*entity.Contact, error) { var span opentracing.Span span, ctx = tracing.EnterFunc(ctx, input) defer span.Finish() @@ -510,7 +510,7 @@ func (n *Node) ConversationAddMessage(ctx context.Context, input *node.Conversat } // GetConversation implements berty.node.GetConversation -func (n *Node) GetConversation(ctx context.Context, input *entity.Conversation) (*entity.Conversation, error) { +func (n *Node) GetConversation(ctx context.Context, input *gql.Node) (*entity.Conversation, error) { var span opentracing.Span span, ctx = tracing.EnterFunc(ctx, input) defer span.Finish() @@ -526,7 +526,7 @@ func (n *Node) GetConversation(ctx context.Context, input *entity.Conversation) } // GetConversationMember implements berty.node.GetConversationMember -func (n *Node) GetConversationMember(ctx context.Context, input *entity.ConversationMember) (*entity.ConversationMember, error) { +func (n *Node) GetConversationMember(ctx context.Context, input *gql.Node) (*entity.ConversationMember, error) { var span opentracing.Span span, ctx = tracing.EnterFunc(ctx, input) defer span.Finish()