]> ruderich.org/simon Gitweb - safcm/safcm.git/blob - frontend/conn.go
Use SPDX license identifiers
[safcm/safcm.git] / frontend / conn.go
1 // Frontend: Connection functions for programs using the safcm library
2
3 // SPDX-License-Identifier: GPL-3.0-or-later
4 // Copyright (C) 2021-2024  Simon Ruderich
5
6 package frontend
7
8 import (
9         "fmt"
10
11         "ruderich.org/simon/safcm"
12         "ruderich.org/simon/safcm/rpc"
13 )
14
15 // SendRecv sends a message for host over conn and waits for the response. Any
16 // MsgLog messages received before the final (non MsgLog) response are passed
17 // to l.Log.
18 func (l *Loop) SendRecv(host Host, conn *rpc.Conn, msg safcm.Msg) (
19         safcm.Msg, error) {
20
21         err := conn.Send(msg)
22         if err != nil {
23                 return nil, err
24         }
25         for {
26                 x, err := conn.Recv()
27                 if err != nil {
28                         return nil, err
29                 }
30                 log, ok := x.(safcm.MsgLog)
31                 if ok {
32                         l.Log(host, log.Level, false, log.Text)
33                         continue
34                 }
35                 return x, nil
36         }
37 }
38
39 // HostInfoMsg sends a MsgInfoReq for host via conn and returns the resulting
40 // MsgInfoResp.
41 func (l *Loop) HostInfoMsg(host Host, conn *rpc.Conn, req safcm.MsgInfoReq) (
42         safcm.MsgInfoResp, error) {
43
44         var empty safcm.MsgInfoResp
45         x, err := l.SendRecv(host, conn, req)
46         if err != nil {
47                 return empty, err
48         }
49         resp, ok := x.(safcm.MsgInfoResp)
50         if !ok {
51                 return empty, fmt.Errorf("unexpected response %v", x)
52         }
53         return resp, nil
54 }
55
56 // HostSyncMsg sends a MsgSyncReq for host via conn and returns the resulting
57 // MsgSyncResp.
58 func (l *Loop) HostSyncMsg(host Host, conn *rpc.Conn, req safcm.MsgSyncReq) (
59         safcm.MsgSyncResp, error) {
60
61         var empty safcm.MsgSyncResp
62         x, err := l.SendRecv(host, conn, req)
63         if err != nil {
64                 return empty, err
65         }
66         resp, ok := x.(safcm.MsgSyncResp)
67         if !ok {
68                 return empty, fmt.Errorf("unexpected response %v", x)
69         }
70         return resp, nil
71 }