<commit_before>// Copyright 2016 tsuru authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package queue

import (
	"fmt"
	"sync"
	"time"

	"github.com/tsuru/tsuru/log"
	tsuruRedis "github.com/tsuru/tsuru/redis"
	"gopkg.in/redis.v3"
)

type redisPubSub struct {
	name    string
	prefix  string
	factory *redisPubSubFactory
	psc     *redis.PubSub
}

func (r *redisPubSub) Pub(msg []byte) error {
	conn, err := r.factory.getConn()
	if err != nil {
		return err
	}
	return conn.Publish(r.key(), string(msg)).Err()
}

func (r *redisPubSub) UnSub() error {
	err := r.psc.Unsubscribe()
	if err != nil {
		return err
	}
	err = r.psc.Close()
	if err != nil {
		return err
	}
	return nil
}

func (r *redisPubSub) Sub() (<-chan []byte, error) {
	conn, err := r.factory.getConn()
	if err != nil {
		return nil, err
	}
	r.psc, err = conn.Subscribe(r.key())
	if err != nil {
		return nil, err
	}
	msgChan := make(chan []byte)
	go func() {
		defer close(msgChan)
		for {
			msg, err := r.psc.ReceiveTimeout(r.factory.config.ReadTimeout)
			if err != nil {<commit_msg>queue: fix data race, it's not safe to unsub while waiting for messages<commit_after>// Copyright 2016 tsuru authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package queue

import (
	"fmt"
	"sync"
	"time"

	"github.com/tsuru/tsuru/log"
	tsuruRedis "github.com/tsuru/tsuru/redis"
	"gopkg.in/redis.v3"
)

type redisPubSub struct {
	name    string
	prefix  string
	factory *redisPubSubFactory
	psc     *redis.PubSub
}

func (r *redisPubSub) Pub(msg []byte) error {
	conn, err := r.factory.getConn()
	if err != nil {
		return err
	}
	return conn.Publish(r.key(), string(msg)).Err()
}

func (r *redisPubSub) UnSub() error {
	err := r.psc.Close()
	if err != nil {
		return err
	}
	return nil
}

func (r *redisPubSub) Sub() (<-chan []byte, error) {
	conn, err := r.factory.getConn()
	if err != nil {
		return nil, err
	}
	r.psc, err = conn.Subscribe(r.key())
	if err != nil {
		return nil, err
	}
	msgChan := make(chan []byte)
	go func() {
		defer close(msgChan)
		for {
			msg, err := r.psc.ReceiveTimeout(r.factory.config.ReadTimeout)
			if err != nil {
{'fraction_non_alphanumeric': 0.14273127753303966, 'fraction_numerical': 0.004405286343612335, 'mean_word_length': 3.2930056710775046, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3344438', 'n_tokens_mistral': 921, 'n_tokens_neox': 879, 'n_words': 255}