Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ jobs:
runs-on: ubuntu-latest
env:
ENVIRONMENT: pubsub.eu01.qa.onstackit.cloud
TOKEN_CUSTOM_URI: https://service-account.api.qa.stackit.cloud/token
TOKEN_CUSTOM_URI: https://accounts.qa.stackit.cloud/oauth/v2/token

steps:
- name: Checkout Code
Expand Down Expand Up @@ -117,7 +117,8 @@ jobs:
echo "pubsub-qa should been removed. Creating..."
stackit config profile import -c "@$RUNNER_TEMP/qa-env.json" --name pubsub-qa
stackit config profile set pubsub-qa
stackit auth activate-service-account # key is being read out from the env STACKIT_SERVICE_ACCOUNT_KEY
stackit config set --token-custom-endpoint "$TOKEN_CUSTOM_URI"
stackit auth activate-service-account --verbosity debug # key is being read out from the env STACKIT_SERVICE_ACCOUNT_KEY

- name: Create PubSub Topic and Subscription
run: ./scripts/create-pubsub-resources.sh
Expand Down
40 changes: 0 additions & 40 deletions pkg/pubsub/helper.go

This file was deleted.

22 changes: 7 additions & 15 deletions pkg/pubsub/message.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ package pubsub

import (
"context"
"fmt"
"time"
)

Expand Down Expand Up @@ -47,30 +46,23 @@ func (m PullMessages) AckIDs() []string {
return ids
}

// DecodeString reverses the transparent base64 encoding, returning the cleartext string.
// DecodeString returns the message payload as a string.
// The error is always nil and only kept for API compatibility.
func (m *PullMessage) DecodeString() (string, error) {
decoded, err := base64Decode(m.Data)
if err != nil {
return "", fmt.Errorf("failed to decode message data: %w", err)
}
return string(decoded), nil
return string(m.Data), nil
}

// DecodeStrings decodes an entire slice of messages.
// If any single message is corrupt, it returns the error immediately instead of swallowing it.
// DecodeStrings returns the payloads of all messages as strings.
// The error is always nil and only kept for API compatibility.
func (m PullMessages) DecodeStrings() ([]string, error) {
strings := make([]string, len(m))
for i, msg := range m {
str, err := msg.DecodeString()
if err != nil {
return nil, fmt.Errorf("failed to decode message at index %d: %w", i, err)
}
strings[i] = str
strings[i] = string(msg.Data)
}
return strings, nil
}

// Bytes exposes the underlying raw base64 data.
// Bytes returns the original message payload.
func (m *PullMessage) Bytes() []byte {
return m.Data
}
12 changes: 4 additions & 8 deletions pkg/pubsub/publisher.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,6 @@ func NewPublisher(topicID uuid.UUID, opts ...Option) *Publisher {
return publisher
}

// PublishStrings acts as a lightweight adapter converting string slice to byte slices,
// deferring all encoding safely to the core Publish method.
func (p *Publisher) PublishStrings(ctx context.Context, messages ...string) error {
byteMessages := make([][]byte, len(messages))
for i, msg := range messages {
Expand All @@ -76,13 +74,11 @@ func (p *Publisher) PublishStrings(ctx context.Context, messages ...string) erro
return p.Publish(ctx, byteMessages)
}

// Publish processes raw bytes, encodes them transparently using bytesToBase64,
// and transmits them out via the API client.
// Publish transmits raw bytes via the API client.
// The JSON encoding of the request base64-encodes each payload exactly once.
func (p *Publisher) Publish(ctx context.Context, messages [][]byte) error {
encodedMessages := bytesToBase64(messages...)

messagesToPublish := make([]api.PublishMessage, len(encodedMessages))
for i, msg := range encodedMessages {
messagesToPublish := make([]api.PublishMessage, len(messages))
for i, msg := range messages {
messagesToPublish[i] = api.PublishMessage{
Data: msg,
}
Expand Down
7 changes: 7 additions & 0 deletions pkg/pubsub/subscriber.go
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,11 @@ func (s *Subscriber) Pull(ctx context.Context, opts ...PullOption) (PullMessages
return nil, NewAPIError(resp.StatusCode(), resp.Body)
}

if resp.JSON200 == nil {
// The generated client only sets JSON200 for JSON content types, so a proxy page lands here.
return nil, NewAPIError(resp.StatusCode(), resp.Body[:min(len(resp.Body), maxErrorBodyBytes)])
}

messages := toSDKMessages(resp.JSON200.Messages, s)

s.logger.V(4).Info(
Expand All @@ -186,3 +191,5 @@ func (s *Subscriber) Pull(ctx context.Context, opts ...PullOption) (PullMessages
func (s *Subscriber) Wait() {
s.wg.Wait()
}

const maxErrorBodyBytes = 256
104 changes: 104 additions & 0 deletions pkg/pubsub/wire_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
// Copyright 2026 Schwarz Digits Cloud GmbH & Co. KG
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package pubsub_test

import (
"bytes"
"context"
"encoding/base64"
"errors"
"io"
"net/http"
"testing"

"github.com/google/uuid"

"github.com/onsi/gomega"

"github.com/stackitcloud/pubsub-sdk-go/pkg/pubsub"
)

type stubRoundTripper func(*http.Request) *http.Response

func (f stubRoundTripper) RoundTrip(r *http.Request) (*http.Response, error) {
return f(r), nil
}

func jsonResponse(status int, body string) *http.Response {
return &http.Response{
StatusCode: status,
Header: http.Header{"Content-Type": []string{"application/json"}},
Body: io.NopCloser(bytes.NewBufferString(body)),
}
}

// Plain Go test so it runs without the Ginkgo suite's environment (BeforeSuite).
func TestWire(t *testing.T) {
payload := []byte("Hello, Stackit!\x00\xff")
wire := base64.StdEncoding.EncodeToString(payload)

t.Run("base64-encodes published payloads exactly once", func(t *testing.T) {
g := gomega.NewWithT(t)
var requestBody []byte
rt := stubRoundTripper(func(r *http.Request) *http.Response {
requestBody, _ = io.ReadAll(r.Body)
return jsonResponse(http.StatusNoContent, "")
})
publisher := pubsub.NewPublisher(uuid.New(), pubsub.WithHTTPRoundTripper(rt))

g.Expect(publisher.Publish(context.Background(), [][]byte{payload})).To(gomega.Succeed())

g.Expect(requestBody).To(gomega.MatchJSON(`{"messages":[{"data":"` + wire + `"}]}`))
})

t.Run("returns the original bytes for pulled messages", func(t *testing.T) {
g := gomega.NewWithT(t)
rt := stubRoundTripper(func(*http.Request) *http.Response {
return jsonResponse(http.StatusOK, `{"messages":[{"ackId":"a","createTime":"2026-01-01T00:00:00Z","data":"`+wire+`","deliveryAttempts":1}]}`)
})
subscriber := pubsub.NewSubscriber(uuid.New(), uuid.New(), pubsub.WithHTTPRoundTripper(rt))

messages, err := subscriber.Pull(context.Background())

g.Expect(err).ToNot(gomega.HaveOccurred())
g.Expect(messages).To(gomega.HaveLen(1))
g.Expect(messages[0].Bytes()).To(gomega.Equal(payload))
str, err := messages[0].DecodeString()
g.Expect(err).ToNot(gomega.HaveOccurred())
g.Expect(str).To(gomega.Equal(string(payload)))
})

t.Run("returns an error for a non-JSON pull response", func(t *testing.T) {
g := gomega.NewWithT(t)
rt := stubRoundTripper(func(*http.Request) *http.Response {
return &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{"Content-Type": []string{"text/html"}},
Body: io.NopCloser(bytes.NewBufferString("<html>gateway page</html>")),
}
})
subscriber := pubsub.NewSubscriber(uuid.New(), uuid.New(), pubsub.WithHTTPRoundTripper(rt))

var messages pubsub.PullMessages
var err error
g.Expect(func() { messages, err = subscriber.Pull(context.Background()) }).ToNot(gomega.Panic())

g.Expect(messages).To(gomega.BeNil())
var apiErr *pubsub.APIError
g.Expect(errors.As(err, &apiErr)).To(gomega.BeTrue())
g.Expect(apiErr.StatusCode).To(gomega.Equal(http.StatusOK))
g.Expect(apiErr.Msg).To(gomega.ContainSubstring("gateway page"))
})
}
Loading