-
Notifications
You must be signed in to change notification settings - Fork 230
/
client.go
182 lines (166 loc) · 4.9 KB
/
client.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
package ai
import (
"context"
"fmt"
"sync"
"github.com/cockroachdb/errors"
"github.com/hasura/go-graphql-client"
"github.com/hasura/go-graphql-client/pkg/jsonutil"
"encr.dev/pkg/fns"
)
// newLazySubClient wraps a graphql.SubscriptionClient and starts it when the first subscription is made.
func newLazySubClient(client *graphql.SubscriptionClient) *LazySubClient {
lazy := &LazySubClient{
SubscriptionClient: client,
notifiers: make(map[string]func([]byte, error) error),
}
client.OnDisconnected(func() {
lazy.mu.Lock()
defer lazy.mu.Unlock()
lazy.running = false
})
client.OnConnected(func() {
lazy.mu.Lock()
defer lazy.mu.Unlock()
lazy.running = true
})
client.OnSubscriptionComplete(func(sub graphql.Subscription) {
lazy.mu.Lock()
defer lazy.mu.Unlock()
delete(lazy.notifiers, sub.GetKey())
})
return lazy
}
// LazySubClient is a wrapper around graphql.SubscriptionClient that starts the client when the first subscription is made.
// It also stops the client when the last subscription is removed and reconnects when a subscription is added.
type LazySubClient struct {
*graphql.SubscriptionClient
mu sync.Mutex
running bool
notifiers map[string]func([]byte, error) error
}
// Subscribe subscribes to a query and calls notify with the result.
func (l *LazySubClient) Subscribe(query interface{}, variables map[string]interface{}, notify func([]byte, error) error) (string, error) {
l.mu.Lock()
defer l.mu.Unlock()
if !l.running {
go func() {
defer fns.CloseIgnore(l)
err := l.Run()
l.mu.Lock()
defer l.mu.Unlock()
if err != nil {
for _, n := range l.notifiers {
_ = n(nil, err)
}
}
l.notifiers = make(map[string]func([]byte, error) error)
}()
}
subID, err := l.SubscriptionClient.Subscribe(query, variables, notify)
if err != nil {
return "", err
}
key := l.GetSubscription(subID).GetKey()
l.notifiers[key] = notify
return subID, nil
}
type TaskMessage struct {
Type string `graphql:"__typename"`
ServiceUpdate `graphql:"... on ServiceUpdate"`
TypeUpdate `graphql:"... on TypeUpdate"`
TypeFieldUpdate `graphql:"... on TypeFieldUpdate"`
ErrorUpdate `graphql:"... on ErrorUpdate"`
EndpointUpdate `graphql:"... on EndpointUpdate"`
SessionUpdate `graphql:"... on SessionUpdate"`
TitleUpdate `graphql:"... on TitleUpdate"`
PathParamUpdate `graphql:"... on PathParamUpdate"`
}
func (u *TaskMessage) GetValue() AIUpdateType {
switch u.Type {
case "ServiceUpdate":
return u.ServiceUpdate
case "TypeUpdate":
return u.TypeUpdate
case "TypeFieldUpdate":
return u.TypeFieldUpdate
case "ErrorUpdate":
return u.ErrorUpdate
case "EndpointUpdate":
return u.EndpointUpdate
case "SessionUpdate":
return u.SessionUpdate
case "TitleUpdate":
return u.TitleUpdate
case "PathParamUpdate":
return u.PathParamUpdate
}
return nil
}
type AIStreamMessage struct {
Value TaskMessage
Error string
Finished bool
}
type aiTask struct {
Message *AIStreamMessage `graphql:"result"`
}
// startAITask is a helper function to intitiate an AI query to the encore platform. The query
// should be assembled to stream a 'result' graphql field that is a AIStreamMessage.
func startAITask[Query any](ctx context.Context, c *LazySubClient, params map[string]interface{}, notifier AINotifier) (string, error) {
var subId string
var errStrReply = func(error string, code any) error {
_ = notifier(ctx, &AINotification{
SubscriptionID: subId,
Error: &AIError{Message: error, Code: fmt.Sprintf("%v", code)},
Finished: true,
})
return graphql.ErrSubscriptionStopped
}
var errReply = func(err error) error {
var graphqlErr graphql.Errors
if errors.As(err, &graphqlErr) {
for _, e := range graphqlErr {
_ = errStrReply(e.Message, e.Extensions["code"])
}
return graphql.ErrSubscriptionStopped
}
return errStrReply(err.Error(), "")
}
var query Query
subId, err := c.Subscribe(&query, params, func(message []byte, err error) error {
if err != nil {
return errReply(err)
}
var result aiTask
err = jsonutil.UnmarshalGraphQL(message, &result)
if err != nil {
return errReply(err)
}
if result.Message.Error != "" {
return errStrReply(result.Message.Error, "")
}
err = notifier(ctx, &AINotification{
SubscriptionID: subId,
Value: result.Message.Value.GetValue(),
Finished: result.Message.Finished,
})
if err != nil {
return errReply(err)
}
return nil
})
return subId, err
}
// AINotification is a wrapper around messages and errors from the encore platform ai service
type AINotification struct {
SubscriptionID string `json:"subscriptionId,omitempty"`
Value any `json:"value,omitempty"`
Error *AIError `json:"error,omitempty"`
Finished bool `json:"finished,omitempty"`
}
type AIError struct {
Message string `json:"message"`
Code string `json:"code"`
}
type AINotifier func(context.Context, *AINotification) error