| 1 |
// Copyright 2024 The Archivista Contributors |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// |
| 7 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
// |
| 9 |
// Unless required by applicable law or agreed to in writing, software |
| 10 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
// See the License for the specific language governing permissions and |
| 13 |
// limitations under the License. |
| 14 |
package dapr |
| 15 |
|
| 16 |
import ( |
| 17 |
"bytes" |
| 18 |
"context" |
| 19 |
"encoding/json" |
| 20 |
"fmt" |
| 21 |
"net/http" |
| 22 |
"time" |
| 23 |
|
| 24 |
"github.com/in-toto/archivista/pkg/config" |
| 25 |
"github.com/sirupsen/logrus" |
| 26 |
) |
| 27 |
|
| 28 |
type DaprHttp struct { |
| 29 |
Client *http.Client |
| 30 |
Host string |
| 31 |
HttpPort string |
| 32 |
PubsubComponentName string |
| 33 |
PubsubTopic string |
| 34 |
Url string |
| 35 |
} |
| 36 |
|
| 37 |
type daprPayload struct { |
| 38 |
Gitoid string |
| 39 |
Payload []byte |
| 40 |
} |
| 41 |
|
| 42 |
type Publisher interface { |
| 43 |
Publish(ctx context.Context, gitoid string, payload []byte) error |
| 44 |
} |
| 45 |
|
| 46 |
func (d *DaprHttp) Publish(ctx context.Context, gitoid string, payload []byte) error { |
| 47 |
if d.Client == nil { |
| 48 |
d.Client = &http.Client{ |
| 49 |
Timeout: 15 * time.Second, |
| 50 |
} |
| 51 |
} |
| 52 |
|
| 53 |
if d.Url == "" { |
| 54 |
d.Url = d.Host + ":" + d.HttpPort + |
| 55 |
"/v1.0/publish/" + d.PubsubComponentName + "/" + d.PubsubTopic |
| 56 |
} |
| 57 |
|
| 58 |
dp := daprPayload{ |
| 59 |
Gitoid: gitoid, |
| 60 |
Payload: payload, |
| 61 |
} |
| 62 |
// Marshal the message to JSON |
| 63 |
msgBytes, err := json.Marshal(dp) |
| 64 |
if err != nil { |
| 65 |
logrus.Error(err.Error()) |
| 66 |
return err |
| 67 |
} |
| 68 |
|
| 69 |
res, err := d.Client.Post(d.Url, "application/json", bytes.NewReader(msgBytes)) |
| 70 |
if err != nil { |
| 71 |
logrus.Error(err.Error()) |
| 72 |
return err |
| 73 |
} |
| 74 |
if res.StatusCode != http.StatusNoContent { |
| 75 |
logrus.Printf("failed to publish message: %s", res.Body) |
| 76 |
return fmt.Errorf("failed to publish message: %s", res.Body) |
| 77 |
} |
| 78 |
defer res.Body.Close() |
| 79 |
|
| 80 |
return nil |
| 81 |
} |
| 82 |
|
| 83 |
func NewPublisher(config *config.Config) Publisher { |
| 84 |
daprPublisher := &DaprHttp{ |
| 85 |
Host: config.PublisherDaprHost, |
| 86 |
HttpPort: config.PublisherDaprPort, |
| 87 |
PubsubComponentName: config.PublisherDaprComponentName, |
| 88 |
PubsubTopic: config.PublisherDaprTopic, |
| 89 |
Url: config.PublisherDaprURL, |
| 90 |
} |
| 91 |
return daprPublisher |
| 92 |
} |