-
Notifications
You must be signed in to change notification settings - Fork 2
/
cortex_creator.go
104 lines (85 loc) · 2.59 KB
/
cortex_creator.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
package neocortex
import (
"context"
"log"
"time"
"os"
"os/signal"
)
func newDefaultEngine(cognitive CognitiveService, channels ...CommunicationChannel) *Engine {
engine := &Engine{}
engine.channels = channels
engine.cognitive = cognitive
engine.registeredResolvers = map[CommunicationChannel]map[*Matcher]*HandleResolver{}
engine.generalResolver = map[CommunicationChannel]*HandleResolver{}
engine.registeredInjection = map[CommunicationChannel]map[*Matcher]*InInjection{}
engine.generalInjection = map[CommunicationChannel]*InInjection{}
engine.done = make(chan error, 1)
engine.Register = map[string]string{}
// engine.logger = logrus.StandardLogger() // In the future
engine.ActiveDialogs = map[*Context]*Dialog{}
engine.dialogPerformanceFunc = defaultPerformance
engine.secret = "neocortex2019"
return engine
}
// Default ...
func Default(repository Repository, cognitive CognitiveService, channels ...CommunicationChannel) (*Engine, error) {
var err error
engine := newDefaultEngine(cognitive, channels...)
engine.Repository = repository
engine.Analytics, err = newDefaultAnalytics(engine.Repository, defaultPerformance)
if err != nil {
return nil, err
}
engine.api = newCortexAPI(repository, engine.Analytics, "/api", ":4200")
fabric := func(ctx context.Context, info PersonInfo) *Context {
newContext := cognitive.CreateNewContext(&ctx, info)
return newContext
}
cognitive.OnContextIsDone(func(c *Context) {
engine.onContextIsDone(c)
})
for _, ch := range channels {
engine.registeredResolvers[ch] = map[*Matcher]*HandleResolver{}
ch.SetContextFabric(fabric)
err := ch.RegisterMessageEndpoint(func(c *Context, message *Input, response OutputResponse) error {
return engine.onMessage(ch, c, message, response)
})
if err != nil {
return nil, err
}
ch.OnNewContextCreated(func(c *Context) {
engine.onNewContextCreated(c)
})
ch.OnContextIsDone(func(c *Context) {
engine.onContextIsDone(c)
})
go func(ch *CommunicationChannel) {
err := (*ch).ToHear()
if err != nil {
engine.done <- err
}
}(&ch)
}
return engine, nil
}
func (engine *Engine) Run() error {
signalChan := make(chan os.Signal, 1)
signal.Notify(signalChan, os.Interrupt)
gc := defaultGarbageCollector(10 * time.Minute)
go func() {
<-signalChan
log.Println("Closing all dialogs, total: ", len(engine.ActiveDialogs))
for c := range engine.ActiveDialogs {
engine.onContextIsDone(c)
}
engine.done <- nil
}()
go func() {
if engine.api.repository != nil {
engine.done <- engine.api.Launch(engine)
}
}()
engine.runGarbageCollector(gc)
return <-engine.done
}