| OLD | NEW |
| (Empty) |
| 1 // Copyright 2015 The Chromium Authors. All rights reserved. | |
| 2 // Use of this source code is governed by a BSD-style license that can be | |
| 3 // found in the LICENSE file. | |
| 4 | |
| 5 package bindings | |
| 6 | |
| 7 import ( | |
| 8 "sync" | |
| 9 ) | |
| 10 | |
| 11 // MessageReceiver can receive |Message| objects. | |
| 12 type MessageReceiver interface { | |
| 13 // Accept receives a |Message|. Returns a error if the message was not | |
| 14 // handled. | |
| 15 Accept(message *Message) error | |
| 16 } | |
| 17 | |
| 18 // Stub is a base implementation of Stub. Stubs receives messages from message | |
| 19 // pipe, deserialize the payload and call the appropriate method in the | |
| 20 // implementation. If the method returns result, the stub serializes the | |
| 21 // response and sends it back. | |
| 22 type Stub struct { | |
| 23 // Makes sure that connector is closed only once. | |
| 24 closeOnce sync.Once | |
| 25 connector *Connector | |
| 26 receiver MessageReceiver | |
| 27 } | |
| 28 | |
| 29 // NewStub returns a new Stub instance using provided |Connector| to send and | |
| 30 // receive messages. Incoming messages are handled by the provided |receiver|. | |
| 31 func NewStub(connector *Connector, receiver MessageReceiver) *Stub { | |
| 32 return &Stub{ | |
| 33 connector: connector, | |
| 34 receiver: receiver, | |
| 35 } | |
| 36 } | |
| 37 | |
| 38 // ServeRequest synchronously serves one request from the message pipe: the | |
| 39 // |Stub| waits on its underlying message pipe for a message and handles it. | |
| 40 // Can be called from multiple goroutines. Each calling goroutine will receive | |
| 41 // a different message or an error. Closes itself in case of error. | |
| 42 func (s *Stub) ServeRequest() error { | |
| 43 message, err := s.connector.ReadMessage() | |
| 44 if err != nil { | |
| 45 s.Close() | |
| 46 return err | |
| 47 } | |
| 48 err = s.receiver.Accept(message) | |
| 49 if err != nil { | |
| 50 s.Close() | |
| 51 } | |
| 52 return err | |
| 53 } | |
| 54 | |
| 55 // Close immediately closes the |Stub| and its underlying message pipe. If the | |
| 56 // |Stub| is waiting on its message pipe handle the wait process is interrupted. | |
| 57 // All goroutines trying to serve will start returning errors as the underlying | |
| 58 // message pipe becomes invalid. | |
| 59 func (s *Stub) Close() { | |
| 60 s.closeOnce.Do(func() { | |
| 61 s.connector.Close() | |
| 62 }) | |
| 63 } | |
| OLD | NEW |