@agoric/cosmos 0.34.2-dev-c933898.0 → 0.34.2-dev-0c5823d.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/app/app.go CHANGED
@@ -230,6 +230,9 @@ type GaiaApp struct { // nolint: golint
230
230
  tkeys map[string]*storetypes.TransientStoreKey
231
231
  memKeys map[string]*storetypes.MemoryStoreKey
232
232
 
233
+ // manage communication from the VM to the ABCI app
234
+ AgdServer *vm.AgdServer
235
+
233
236
  // keepers
234
237
  AccountKeeper authkeeper.AccountKeeper
235
238
  BankKeeper bankkeeper.Keeper
@@ -298,14 +301,14 @@ func NewGaiaApp(
298
301
  return "", nil
299
302
  }
300
303
  return NewAgoricApp(
301
- defaultController,
304
+ defaultController, vm.NewAgdServer(),
302
305
  logger, db, traceStore, loadLatest, skipUpgradeHeights,
303
306
  homePath, invCheckPeriod, encodingConfig, appOpts, baseAppOptions...,
304
307
  )
305
308
  }
306
309
 
307
310
  func NewAgoricApp(
308
- sendToController func(context.Context, bool, string) (string, error),
311
+ sendToController func(context.Context, bool, string) (string, error), agdServer *vm.AgdServer,
309
312
  logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest bool, skipUpgradeHeights map[int64]bool,
310
313
  homePath string, invCheckPeriod uint, encodingConfig gaiaappparams.EncodingConfig, appOpts servertypes.AppOptions, baseAppOptions ...func(*baseapp.BaseApp),
311
314
  ) *GaiaApp {
@@ -331,6 +334,7 @@ func NewAgoricApp(
331
334
 
332
335
  app := &GaiaApp{
333
336
  BaseApp: bApp,
337
+ AgdServer: agdServer,
334
338
  legacyAmino: legacyAmino,
335
339
  appCodec: appCodec,
336
340
  interfaceRegistry: interfaceRegistry,
@@ -449,7 +453,7 @@ func NewAgoricApp(
449
453
  callToController := func(ctx sdk.Context, str string) (string, error) {
450
454
  app.CheckControllerInited(true)
451
455
  // We use SwingSet-level metering to charge the user for the call.
452
- defer vm.SetControllerContext(ctx)()
456
+ defer app.AgdServer.SetControllerContext(ctx)()
453
457
  return sendToController(sdk.WrapSDKContext(ctx), true, str)
454
458
  }
455
459
 
@@ -460,7 +464,7 @@ func NewAgoricApp(
460
464
  app.VstorageKeeper = vstorage.NewKeeper(
461
465
  keys[vstorage.StoreKey],
462
466
  )
463
- app.vstoragePort = vm.RegisterPortHandler("vstorage", vstorage.NewStorageHandler(app.VstorageKeeper))
467
+ app.vstoragePort = app.AgdServer.MustRegisterPortHandler("vstorage", vstorage.NewStorageHandler(app.VstorageKeeper))
464
468
 
465
469
  // The SwingSetKeeper is the Keeper from the SwingSet module
466
470
  app.SwingSetKeeper = swingset.NewKeeper(
@@ -469,7 +473,7 @@ func NewAgoricApp(
469
473
  app.VstorageKeeper, vbanktypes.ReservePoolName,
470
474
  callToController,
471
475
  )
472
- app.swingsetPort = vm.RegisterPortHandler("swingset", swingset.NewPortHandler(app.SwingSetKeeper))
476
+ app.swingsetPort = app.AgdServer.MustRegisterPortHandler("swingset", swingset.NewPortHandler(app.SwingSetKeeper))
473
477
 
474
478
  app.SwingStoreExportsHandler = *swingsetkeeper.NewSwingStoreExportsHandler(
475
479
  app.Logger(),
@@ -508,7 +512,7 @@ func NewAgoricApp(
508
512
 
509
513
  vibcModule := vibc.NewAppModule(app.VibcKeeper, app.BankKeeper)
510
514
  vibcIBCModule := vibc.NewIBCModule(app.VibcKeeper)
511
- app.vibcPort = vm.RegisterPortHandler("vibc", vibc.NewReceiver(app.VibcKeeper))
515
+ app.vibcPort = app.AgdServer.MustRegisterPortHandler("vibc", vibc.NewReceiver(app.VibcKeeper))
512
516
 
513
517
  app.VbankKeeper = vbank.NewKeeper(
514
518
  appCodec, keys[vbank.StoreKey], app.GetSubspace(vbank.ModuleName),
@@ -516,7 +520,7 @@ func NewAgoricApp(
516
520
  app.SwingSetKeeper.PushAction,
517
521
  )
518
522
  vbankModule := vbank.NewAppModule(app.VbankKeeper)
519
- app.vbankPort = vm.RegisterPortHandler("bank", vbank.NewPortHandler(vbankModule, app.VbankKeeper))
523
+ app.vbankPort = app.AgdServer.MustRegisterPortHandler("bank", vbank.NewPortHandler(vbankModule, app.VbankKeeper))
520
524
 
521
525
  // register the proposal types
522
526
  govRouter := govv1beta1.NewRouter()
@@ -613,7 +617,7 @@ func NewAgoricApp(
613
617
  app.BaseApp.MsgServiceRouter(),
614
618
  app.BaseApp.GRPCQueryRouter(),
615
619
  )
616
- app.vlocalchainPort = vm.RegisterPortHandler(
620
+ app.vlocalchainPort = app.AgdServer.MustRegisterPortHandler(
617
621
  "vlocalchain",
618
622
  vlocalchain.NewReceiver(app.VlocalchainKeeper),
619
623
  )
package/cmd/agd/main.go CHANGED
@@ -49,7 +49,6 @@ func makeShutdown(cmd *exec.Cmd, writer *os.File) func() error {
49
49
  }
50
50
  }
51
51
 
52
-
53
52
  // main is the entry point of the agd daemon. It determines whether to
54
53
  // initialize JSON-RPC communications with the separate `--split-vm` VM process,
55
54
  // or just to give up control entirely to another binary.
@@ -72,9 +71,9 @@ func main() {
72
71
  }
73
72
 
74
73
  msg := vm.Message{
75
- Port: nodePort,
74
+ Port: nodePort,
76
75
  NeedsReply: needReply,
77
- Data: str,
76
+ Data: str,
78
77
  }
79
78
  var reply string
80
79
  err := vmClient.Call(vm.ReceiveMessageMethod, msg, &reply)
@@ -82,7 +81,7 @@ func main() {
82
81
  }
83
82
 
84
83
  exitCode := 0
85
- launchVM := func(logger log.Logger, appOpts servertypes.AppOptions) error {
84
+ launchVM := func(agdServer *vm.AgdServer, logger log.Logger, appOpts servertypes.AppOptions) error {
86
85
  args := []string{"ag-chain-cosmos", "--home", gaia.DefaultNodeHome}
87
86
  args = append(args, os.Args[1:]...)
88
87
 
@@ -129,7 +128,7 @@ func main() {
129
128
 
130
129
  // Set up the VM server.
131
130
  vmServer := rpc.NewServer()
132
- if err := vmServer.RegisterName("agd", vm.NewAgdServer()); err != nil {
131
+ if err := vmServer.RegisterName("agd", agdServer); err != nil {
133
132
  return err
134
133
  }
135
134
  go vmServer.ServeCodec(jsonrpc.NewServerCodec(serverConn))
@@ -147,11 +146,11 @@ func main() {
147
146
  }
148
147
 
149
148
  daemoncmd.OnExportHook = launchVM
150
- daemoncmd.OnStartHook = func (logger log.Logger, appOpts servertypes.AppOptions) error {
149
+ daemoncmd.OnStartHook = func(agdServer *vm.AgdServer, logger log.Logger, appOpts servertypes.AppOptions) error {
151
150
  // We tried running start, which should never exit, so exit with non-zero
152
151
  // code if we do.
153
152
  exitCode = 99
154
- return launchVM(logger, appOpts)
153
+ return launchVM(agdServer, logger, appOpts)
155
154
  }
156
155
 
157
156
  daemon.RunWithController(sendToNode)
@@ -38,7 +38,7 @@ var agdServer *vm.AgdServer
38
38
  // ConnectVMClientCodec creates an RPC client codec and a sender to the
39
39
  // in-process implementation of the VM.
40
40
  func ConnectVMClientCodec(ctx context.Context, nodePort int, sendFunc func(int, int, string)) (*vm.ClientCodec, daemoncmd.Sender) {
41
- vmClientCodec = vm.NewClientCodec(context.Background(), sendFunc)
41
+ vmClientCodec = vm.NewClientCodec(ctx, sendFunc)
42
42
  vmClient := rpc.NewClientWithCodec(vmClientCodec)
43
43
 
44
44
  sendToNode := func(ctx context.Context, needReply bool, str string) (string, error) {
@@ -47,9 +47,9 @@ func ConnectVMClientCodec(ctx context.Context, nodePort int, sendFunc func(int,
47
47
  }
48
48
 
49
49
  msg := vm.Message{
50
- Port: nodePort,
50
+ Port: nodePort,
51
51
  NeedsReply: needReply,
52
- Data: str,
52
+ Data: str,
53
53
  }
54
54
  var reply string
55
55
  err := vmClient.Call(vm.ReceiveMessageMethod, msg, &reply)
@@ -83,7 +83,6 @@ func RunAgCosmosDaemon(nodePort C.int, toNode C.sendFunc, cosmosArgs []*C.char)
83
83
  int(nodePort),
84
84
  sendFunc,
85
85
  )
86
- agdServer = vm.NewAgdServer()
87
86
 
88
87
  args := make([]string, len(cosmosArgs))
89
88
  for i, s := range cosmosArgs {
@@ -96,7 +95,8 @@ func RunAgCosmosDaemon(nodePort C.int, toNode C.sendFunc, cosmosArgs []*C.char)
96
95
  // We run in the background, but exit when the job is over.
97
96
  // swingset.SendToNode("hello from Initial Go!")
98
97
  exitCode := 0
99
- daemoncmd.OnStartHook = func(logger log.Logger, appOpts servertypes.AppOptions) error {
98
+ daemoncmd.OnStartHook = func(srv *vm.AgdServer, logger log.Logger, appOpts servertypes.AppOptions) error {
99
+ agdServer = srv
100
100
  // We tried running start, which should never exit, so exit with non-zero
101
101
  // code if we ever stop.
102
102
  exitCode = 99
@@ -130,11 +130,11 @@ func SendToGo(port C.int, msg C.Body) C.Body {
130
130
  // fmt.Fprintln(os.Stderr, "Send to Go", msgStr)
131
131
  var respStr string
132
132
  message := &vm.Message{
133
- Port: int(port),
133
+ Port: int(port),
134
134
  NeedsReply: true,
135
- Data: msgStr,
135
+ Data: msgStr,
136
136
  }
137
-
137
+
138
138
  err := agdServer.ReceiveMessage(message, &respStr)
139
139
  if err == nil {
140
140
  return C.CString(respStr)
@@ -39,14 +39,15 @@ import (
39
39
 
40
40
  gaia "github.com/Agoric/agoric-sdk/golang/cosmos/app"
41
41
  "github.com/Agoric/agoric-sdk/golang/cosmos/app/params"
42
+ "github.com/Agoric/agoric-sdk/golang/cosmos/vm"
42
43
  )
43
44
 
44
45
  // Sender is a function that sends a request to the controller.
45
46
  type Sender func(ctx context.Context, needReply bool, str string) (string, error)
46
47
 
47
48
  var AppName = "agd"
48
- var OnStartHook func(log.Logger, servertypes.AppOptions) error
49
- var OnExportHook func(log.Logger, servertypes.AppOptions) error
49
+ var OnStartHook func(*vm.AgdServer, log.Logger, servertypes.AppOptions) error
50
+ var OnExportHook func(*vm.AgdServer, log.Logger, servertypes.AppOptions) error
50
51
 
51
52
  // NewRootCmd creates a new root command for simd. It is called once in the
52
53
  // main function.
@@ -129,8 +130,9 @@ func initRootCmd(sender Sender, rootCmd *cobra.Command, encodingConfig params.En
129
130
  cfg.Seal()
130
131
 
131
132
  ac := appCreator{
132
- encCfg: encodingConfig,
133
- sender: sender,
133
+ encCfg: encodingConfig,
134
+ sender: sender,
135
+ agdServer: vm.NewAgdServer(),
134
136
  }
135
137
 
136
138
  rootCmd.AddCommand(
@@ -249,8 +251,9 @@ func txCommand() *cobra.Command {
249
251
  }
250
252
 
251
253
  type appCreator struct {
252
- encCfg params.EncodingConfig
253
- sender Sender
254
+ encCfg params.EncodingConfig
255
+ sender Sender
256
+ agdServer *vm.AgdServer
254
257
  }
255
258
 
256
259
  func (ac appCreator) newApp(
@@ -260,7 +263,7 @@ func (ac appCreator) newApp(
260
263
  appOpts servertypes.AppOptions,
261
264
  ) servertypes.Application {
262
265
  if OnStartHook != nil {
263
- if err := OnStartHook(logger, appOpts); err != nil {
266
+ if err := OnStartHook(ac.agdServer, logger, appOpts); err != nil {
264
267
  panic(err)
265
268
  }
266
269
  }
@@ -305,7 +308,7 @@ func (ac appCreator) newApp(
305
308
  )
306
309
 
307
310
  return gaia.NewAgoricApp(
308
- ac.sender,
311
+ ac.sender, ac.agdServer,
309
312
  logger, db, traceStore, true, skipUpgradeHeights,
310
313
  homePath,
311
314
  cast.ToUint(appOpts.Get(server.FlagInvCheckPeriod)),
@@ -405,7 +408,7 @@ func (ac appCreator) appExport(
405
408
  appOpts servertypes.AppOptions,
406
409
  ) (servertypes.ExportedApp, error) {
407
410
  if OnExportHook != nil {
408
- if err := OnExportHook(logger, appOpts); err != nil {
411
+ if err := OnExportHook(ac.agdServer, logger, appOpts); err != nil {
409
412
  return servertypes.ExportedApp{}, err
410
413
  }
411
414
  }
@@ -421,7 +424,7 @@ func (ac appCreator) appExport(
421
424
  }
422
425
 
423
426
  gaiaApp := gaia.NewAgoricApp(
424
- ac.sender,
427
+ ac.sender, ac.agdServer,
425
428
  logger,
426
429
  db,
427
430
  traceStore,
package/git-revision.txt CHANGED
@@ -1 +1 @@
1
- c933898
1
+ 0c5823d
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agoric/cosmos",
3
- "version": "0.34.2-dev-c933898.0+c933898",
3
+ "version": "0.34.2-dev-0c5823d.0+0c5823d",
4
4
  "description": "Connect JS to the Cosmos blockchain SDK",
5
5
  "parsers": {
6
6
  "js": "mjs"
@@ -39,5 +39,5 @@
39
39
  "typeCoverage": {
40
40
  "atLeast": 0
41
41
  },
42
- "gitHead": "c93389889a10d9f14a7fdae21c150941e6e74a06"
42
+ "gitHead": "0c5823d285f8ba8655ec305c56a54c26de875328"
43
43
  }
package/vm/client_test.go CHANGED
@@ -20,7 +20,7 @@ type errorWrapper struct {
20
20
  // ConnectVMClientCodec creates an RPC client codec and a sender to the
21
21
  // in-process implementation of the VM.
22
22
  func ConnectVMClientCodec(ctx context.Context, nodePort int, sendFunc func(int, int, string)) (*vm.ClientCodec, Sender) {
23
- vmClientCodec := vm.NewClientCodec(context.Background(), sendFunc)
23
+ vmClientCodec := vm.NewClientCodec(ctx, sendFunc)
24
24
  vmClient := rpc.NewClientWithCodec(vmClientCodec)
25
25
 
26
26
  sendToNode := func(ctx context.Context, needReply bool, str string) (string, error) {
@@ -29,9 +29,9 @@ func ConnectVMClientCodec(ctx context.Context, nodePort int, sendFunc func(int,
29
29
  }
30
30
 
31
31
  msg := vm.Message{
32
- Port: nodePort,
32
+ Port: nodePort,
33
33
  NeedsReply: needReply,
34
- Data: str,
34
+ Data: str,
35
35
  }
36
36
  var reply string
37
37
  err := vmClient.Call(vm.ReceiveMessageMethod, msg, &reply)
@@ -43,33 +43,34 @@ func ConnectVMClientCodec(ctx context.Context, nodePort int, sendFunc func(int,
43
43
 
44
44
  type Fixture struct {
45
45
  SendToNode Sender
46
- SendToGo func (port int, msgStr string) string
47
- ReplyToGo func (replyPort int, isError bool, respStr string) int
46
+ SendToGo func(port int, msgStr string) string
47
+ ReplyToGo func(replyPort int, isError bool, respStr string) int
48
48
  }
49
49
 
50
- func NewFixture(t *testing.T) (*Fixture) {
50
+ func NewFixture(t *testing.T) *Fixture {
51
51
  nodePort := 42
52
52
 
53
53
  f := &Fixture{}
54
+ agdServer := vm.NewAgdServer()
54
55
 
55
56
  sendFunc := func(port int, reply int, str string) {
56
57
  switch str {
57
- case "ping":
58
- time.AfterFunc(100*time.Millisecond, func() {
59
- fmt.Printf("sendFunc: port=%d, reply=%d, str=%s\n", port, reply, str)
60
- if reply != 0 {
61
- f.ReplyToGo(reply, false, "pong")
62
- }
63
- })
64
- case "wait":
65
- time.AfterFunc(300*time.Millisecond, func() {
66
- fmt.Printf("sendFunc: port=%d, reply=%d, str=%s\n", port, reply, str)
67
- if reply != 0 {
68
- f.ReplyToGo(reply, false, "done-waiting")
69
- }
70
- })
71
- default:
72
- t.Errorf("Unexpected message %s", str)
58
+ case "ping":
59
+ time.AfterFunc(100*time.Millisecond, func() {
60
+ fmt.Printf("sendFunc: port=%d, reply=%d, str=%s\n", port, reply, str)
61
+ if reply != 0 {
62
+ f.ReplyToGo(reply, false, "pong")
63
+ }
64
+ })
65
+ case "wait":
66
+ time.AfterFunc(300*time.Millisecond, func() {
67
+ fmt.Printf("sendFunc: port=%d, reply=%d, str=%s\n", port, reply, str)
68
+ if reply != 0 {
69
+ f.ReplyToGo(reply, false, "done-waiting")
70
+ }
71
+ })
72
+ default:
73
+ t.Errorf("Unexpected message %s", str)
73
74
  }
74
75
  }
75
76
 
@@ -78,23 +79,22 @@ func NewFixture(t *testing.T) (*Fixture) {
78
79
  int(nodePort),
79
80
  sendFunc,
80
81
  )
81
- agdServer := vm.NewAgdServer()
82
82
 
83
83
  f.SendToNode = sendToNode
84
- f.SendToGo = func (port int, msgStr string) string {
84
+ f.SendToGo = func(port int, msgStr string) string {
85
85
  fmt.Println("Send to Go", msgStr)
86
86
  var respStr string
87
87
  message := &vm.Message{
88
- Port: int(port),
88
+ Port: int(port),
89
89
  NeedsReply: true,
90
- Data: msgStr,
90
+ Data: msgStr,
91
91
  }
92
-
92
+
93
93
  err := agdServer.ReceiveMessage(message, &respStr)
94
94
  if err == nil {
95
95
  return respStr
96
96
  }
97
-
97
+
98
98
  // fmt.Fprintln(os.Stderr, "Cannot receive from controller", err)
99
99
  errResp := errorWrapper{
100
100
  Error: err.Error(),
@@ -106,7 +106,7 @@ func NewFixture(t *testing.T) (*Fixture) {
106
106
  return string(respBytes)
107
107
  }
108
108
 
109
- f.ReplyToGo = func (replyPort int, isError bool, respStr string) int {
109
+ f.ReplyToGo = func(replyPort int, isError bool, respStr string) int {
110
110
  if err := vmClientCodec.Receive(replyPort, isError, respStr); err != nil {
111
111
  return 1
112
112
  }
package/vm/controller.go CHANGED
@@ -21,20 +21,10 @@ type ControllerAdmissionMsg interface {
21
21
  IsHighPriority(sdk.Context, interface{}) (bool, error)
22
22
  }
23
23
 
24
- var wrappedEmptySDKContext = sdk.WrapSDKContext(
25
- sdk.Context{}.WithContext(context.Background()),
26
- )
27
- var controllerContext context.Context = wrappedEmptySDKContext
28
-
29
24
  type PortHandler interface {
30
25
  Receive(context.Context, string) (string, error)
31
26
  }
32
27
 
33
- var portToHandler = make(map[int]PortHandler)
34
- var portToName = make(map[int]string)
35
- var nameToPort = make(map[string]int)
36
- var lastPort = 0
37
-
38
28
  type protectedPortHandler struct {
39
29
  inner PortHandler
40
30
  }
@@ -54,31 +44,3 @@ func (h protectedPortHandler) Receive(ctx context.Context, str string) (ret stri
54
44
  func NewProtectedPortHandler(inner PortHandler) PortHandler {
55
45
  return protectedPortHandler{inner}
56
46
  }
57
-
58
- func SetControllerContext(ctx sdk.Context) func() {
59
- // We are only called by the controller, so we assume that it is billing its
60
- // own meter usage.
61
- controllerContext = sdk.WrapSDKContext(ctx.WithGasMeter(sdk.NewInfiniteGasMeter()))
62
- return func() {
63
- controllerContext = wrappedEmptySDKContext
64
- }
65
- }
66
-
67
- func GetPort(name string) int {
68
- return nameToPort[name]
69
- }
70
-
71
- func RegisterPortHandler(name string, portHandler PortHandler) int {
72
- lastPort++
73
- portToHandler[lastPort] = NewProtectedPortHandler(portHandler)
74
- portToName[lastPort] = name
75
- nameToPort[name] = lastPort
76
- return lastPort
77
- }
78
- func UnregisterPortHandler(portNum int) error {
79
- delete(portToHandler, portNum)
80
- name := portToName[portNum]
81
- delete(portToName, portNum)
82
- delete(nameToPort, name)
83
- return nil
84
- }
package/vm/server.go CHANGED
@@ -1,23 +1,124 @@
1
1
  package vm
2
2
 
3
3
  import (
4
+ "context"
4
5
  "fmt"
6
+ "sync"
7
+
8
+ sdk "github.com/cosmos/cosmos-sdk/types"
5
9
  )
6
10
 
7
- type AgdServer struct{}
11
+ // AgdServer manages communication from the VM to the ABCI app. The structure
12
+ // is mutable and the mutex must be held to read or write any field.
13
+ type AgdServer struct {
14
+ currentCtx context.Context
15
+ mtx sync.Mutex
16
+ // zero is an out-of-bounds port number
17
+ lastPort int
18
+ // portToHandler[i] is nonzero iff portToName[i] is nonempty
19
+ portToHandler map[int]PortHandler
20
+ // portToName[nameToPort[s]] == s && nameToPort[portToName[i]] == i for all i, s
21
+ portToName map[int]string
22
+ nameToPort map[string]int
23
+ }
24
+
25
+ var wrappedEmptySDKContext = sdk.WrapSDKContext(
26
+ sdk.Context{}.WithContext(context.Background()),
27
+ )
8
28
 
29
+ // NewAgdServer returns a pointer to a new AgdServer with empty context and port
30
+ // mappings.
9
31
  func NewAgdServer() *AgdServer {
10
- return &AgdServer{}
32
+ return &AgdServer{
33
+ currentCtx: wrappedEmptySDKContext,
34
+ mtx: sync.Mutex{},
35
+ portToHandler: make(map[int]PortHandler),
36
+ portToName: make(map[int]string),
37
+ nameToPort: make(map[string]int),
38
+ }
39
+ }
40
+
41
+ // SetControllerContext sets the context to the given argument and returns a function
42
+ // which will reset the context to an empty context (not the old context).
43
+ func (s *AgdServer) SetControllerContext(ctx sdk.Context) func() {
44
+ // We are only called by the controller, so we assume that it is billing its
45
+ // own meter usage.
46
+ s.mtx.Lock()
47
+ defer s.mtx.Unlock()
48
+ s.currentCtx = sdk.WrapSDKContext(ctx.WithGasMeter(sdk.NewInfiniteGasMeter()))
49
+ return func() {
50
+ s.mtx.Lock()
51
+ defer s.mtx.Unlock()
52
+ s.currentCtx = wrappedEmptySDKContext
53
+ }
54
+ }
55
+
56
+ // getContextAndHandler returns the current context and the handler for the
57
+ // given port number.
58
+ func (s *AgdServer) getContextAndHandler(port int) (context.Context, PortHandler) {
59
+ s.mtx.Lock()
60
+ defer s.mtx.Unlock()
61
+ ctx := s.currentCtx
62
+ handler := s.portToHandler[port]
63
+ return ctx, handler
11
64
  }
12
65
 
13
66
  // ReceiveMessage is the method the VM calls in order to have agd receive a
14
67
  // Message.
15
- func (s AgdServer) ReceiveMessage(msg *Message, reply *string) error {
16
- handler := portToHandler[msg.Port]
68
+ func (s *AgdServer) ReceiveMessage(msg *Message, reply *string) error {
69
+ ctx, handler := s.getContextAndHandler(msg.Port)
17
70
  if handler == nil {
18
71
  return fmt.Errorf("unregistered port %d", msg.Port)
19
72
  }
20
- resp, err := handler.Receive(controllerContext, msg.Data)
73
+ resp, err := handler.Receive(ctx, msg.Data)
21
74
  *reply = resp
22
75
  return err
23
76
  }
77
+
78
+ // GetPort returns the port number for the given port name, or 0 if the name is
79
+ // not registered.
80
+ func (s *AgdServer) GetPort(name string) int {
81
+ s.mtx.Lock()
82
+ defer s.mtx.Unlock()
83
+ return s.nameToPort[name]
84
+ }
85
+
86
+ // MustRegisterPortHandler attempts to RegisterPortHandler, panicing on error.
87
+ func (s *AgdServer) MustRegisterPortHandler(name string, portHandler PortHandler) int {
88
+ port, err := s.RegisterPortHandler(name, portHandler)
89
+ if err != nil {
90
+ panic(err)
91
+ }
92
+ return port
93
+ }
94
+
95
+ // RegisterPortHandler registers the handler to a new port number, then maps the name to it,
96
+ // returning the port number. If the name was previously in use, an error is returned.
97
+ func (s *AgdServer) RegisterPortHandler(name string, portHandler PortHandler) (int, error) {
98
+ s.mtx.Lock()
99
+ defer s.mtx.Unlock()
100
+ if _, ok := s.nameToPort[name]; ok {
101
+ return 0, fmt.Errorf("name %s already in use", name)
102
+ }
103
+ s.lastPort++
104
+ s.portToHandler[s.lastPort] = NewProtectedPortHandler(portHandler)
105
+ s.portToName[s.lastPort] = name
106
+ s.nameToPort[name] = s.lastPort
107
+ return s.lastPort, nil
108
+ }
109
+
110
+ // UnregisterPortHandler unregisters the handler and name mappings for this port
111
+ // number, and the reverse mapping for its name, if any of these exist. If
112
+ // portNum is not registered, return an error.
113
+ func (s *AgdServer) UnregisterPortHandler(portNum int) error {
114
+ s.mtx.Lock()
115
+ defer s.mtx.Unlock()
116
+ if s.portToHandler[portNum] == nil {
117
+ return fmt.Errorf("port %d not registered", portNum)
118
+ }
119
+ delete(s.portToHandler, portNum)
120
+ name := s.portToName[portNum]
121
+ delete(s.portToName, portNum)
122
+ delete(s.nameToPort, name)
123
+ return nil
124
+ }