// PublisherMsgInterceptor add logging to the publisher
432077
func (o Middleware) PublisherMsgInterceptor(serviceName string, next pubsub.PublishHandler) pubsub.PublishHandler {
	return func(ctx context.Context, topic string, m *pubsub.Msg) error {
		if o.Logger == nil {
			o.Logger = DefaultLogger()
		}

		start := time.Now()
		err := next(ctx, topic, m)
		elapsed := time.Now().Sub(start)

		o.Logger.Debug("Published PubSub Msg",
			zap.String("component", "pubsub"),
			zap.String("topic", topic),
			zap.Duration("duration", elapsed),
			zap.Error(err),
		)

		return err
	}
}
827399
func (m *ClientMetrics) StreamClientInterceptor() func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) {
	return func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) {
		monitor := newClientReporter(m, clientStreamType(desc), method)
		clientStream, err := streamer(ctx, desc, cc, method, opts...)
		if err != nil {
			st, _ := status.FromError(err)
			monitor.Handled(st.Code())
			return nil, err
		}
		return &monitoredClientStream{clientStream, monitor}, nil
	}
}
154951
func (p *Publisher) SubReader() (reader SubReader, lastMsg interface{}) {
	p.m.Lock()
	defer p.m.Unlock()

	if p.lastMsg == nil {
		p.lastMsg = newMsg(nil)
	}
	return &subscriber{p.lastMsg.next}, p.lastMsg.val
}
934753
func metricsInterceptor(ctx context.Context, invocation *enigma.Invocation, proceed enigma.InterceptorContinuation) *enigma.InvocationResponse {
	ctxWithMetrics, metricsCollector := enigma.WithMetricsCollector(ctx)

	response := proceed(ctxWithMetrics, invocation)

	metrics := metricsCollector.Metrics()
	fmt.Println(response.RequestID, invocation.RemoteObject.Type, invocation.Method, metrics.ToString())
	return response
}
132709
func NewConsumer(topicName string, subscriptionName string) Consumer {
	pubsubClient, err := newPubSubClient()

	if err != nil {
		log.Fatalf("Could not create PubSub client: %v", err)
	}

	topic := ensureTopic(pubsubClient, topicName)
	sub := ensureSubscription(pubsubClient, topic, subscriptionName)

	return &googlePubSubConsumer{Subscription: sub}
}
90236
func NewPublisher(
	publisher *nats.Conn,
	subject string,
	enc EncodeRequestFunc,
	dec DecodeResponseFunc,
	options ...PublisherOption,
) *Publisher {
	p := &Publisher{
		publisher: publisher,
		subject:   subject,
		enc:       enc,
		dec:       dec,
		timeout:   10 * time.Second,
	}
	for _, option := range options {
		option(p)
	}
	return p
}
909343
func (ec *Envcfg) dnsCertProvider(params []string) CertificateProvider {
	if len(params) < 3 {
		panic("invalid dns certificate provider params")
	}

	var provisioner autocertdns.Provisioner
	switch params[0] {

	// godo:mydomain.com:user@mydomain.com:abaoeusntahoustnhaou
	case "godo", "godop", "do", "digitalocean":
		if len(params) != 4 {
			panic("invalid digitalocean dns certificate provider params")
		}

		var err error
		provisioner, err = godop.New(
			godop.Domain(params[1]),
			godop.GodoClientToken(context.Background(), params[3]),
			godop.Logf(ec.logf),
		)
		if err != nil {
			panic(err)
		}

	// clouddns:mydomain.com:user@mydomain.com:managed-zone-name:/path/to/credentials.json
	case "google", "gcdns", "gcdnsp", "gc", "googlecloud", "clouddns", "googleclouddns":
		if len(params) != 5 {
			panic("invalid google cloud dns certificate provider params")
		}

		var err error
		provisioner, err = gcdnsp.New(
			gcdnsp.Domain(params[1]),
			gcdnsp.ManagedZone(params[3]),
			gcdnsp.GoogleServiceAccountCredentialsFile(params[4]),
			gcdnsp.PropagationWait(ec.CertWait()),
			gcdnsp.ProvisionDelay(ec.CertDelay()),
			gcdnsp.Logf(ec.logf),
			gcdnsp.Errorf(ec.errf),
		)
		if err != nil {
			panic(err)
		}

	default:
		panic("invalid certificate provisioner type")
	}

	a := &autocertdns.Manager{
		Prompt:      autocert.AcceptTOS,
		Domain:      ec.Host(),
		Email:       params[2],
		CacheDir:    ec.CertPath(),
		Provisioner: provisioner,
		Logf:        ec.logf,
	}

	if err := a.Run(context.Background()); err != nil {
		panic(fmt.Sprintf("could not provision: %v", err))
	}

	return a
}
1160665
func NewService(config Config, publisher events.Publisher) (*Service, error) {
	if config.Namespace == "" {
		return nil, fmt.Errorf("shim namespace cannot be empty")
	}
	ctx := namespaces.WithNamespace(context.Background(), config.Namespace)
	ctx = log.WithLogger(ctx, logrus.WithFields(logrus.Fields{
		"namespace": config.Namespace,
		"path":      config.Path,
		"pid":       os.Getpid(),
	}))
	s := &Service{
		config:    config,
		context:   ctx,
		processes: make(map[string]rproc.Process),
		events:    make(chan interface{}, 128),
		ec:        Default.Subscribe(),
	}
	go s.processExits()
	if err := s.initPlatform(); err != nil {
		return nil, errors.Wrap(err, "failed to initialized platform behavior")
	}
	go s.forward(publisher)
	return s, nil
}
3861
func PayloadStreamClientInterceptor(logger *zap.Logger, decider grpc_logging.ClientPayloadLoggingDecider) grpc.StreamClientInterceptor {
	return func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) {
		if !decider(ctx, method) {
			return streamer(ctx, desc, cc, method, opts...)
		}
		logEntry := logger.With(newClientLoggerFields(ctx, method)...)
		clientStream, err := streamer(ctx, desc, cc, method, opts...)
		newStream := &loggingClientStream{ClientStream: clientStream, logger: logEntry}
		return newStream, err
	}
}
95335
func MessageHandler(Incoming <-chan tgbot.MessageWithUpdateID, bot *tgbot.TgBot) {
	for {
		input := <-Incoming

		if input.Msg.Text != nil {
			text := handleMessageText(*input.Msg.Text, input.Msg)
			if text != "" {
				nmsg, err := bot.SimpleSendMessage(input.Msg, text)
				if err != nil {
					fmt.Println(err)
					continue
				}
				fmt.Println(nmsg.String())
			}
		}
	}
}
1132399
func (o Middleware) SubscribeInterceptor(opts pubsub.HandlerOptions, next pubsub.MsgHandler) pubsub.MsgHandler {
	return func(ctx context.Context, m pubsub.Msg) error {
		start := time.Now()
		err := next(ctx, m)
		elapsed := time.Now().Sub(start)

		var traceID string
		span := opentracing.SpanFromContext(ctx)
		if span != nil {
			zs, ok := span.Context().(zipkintracing.SpanContext)
			if ok {
				traceID = zs.TraceID.ToHex()
			}
		}

		fields := logrus.Fields{
			"component": "pubsub",
			"topic":     opts.Topic,
			"handler":   opts.Name,
			"duration":  elapsed,
			"metadata":  m.Metadata,
		}

		if err != nil {
			de, ok := err.(errors.DropboxError)
			if ok {
				fields["err"] = de.GetMessage()
			} else {
				fields["err"] = err
			}
		}

		if m.ID != "" {
			fields["id"] = m.ID
		}

		if traceID != "" {
			fields["trace-id"] = traceID
		}

		logrus.WithFields(fields).Debug("Processed PubSub Msg")
		return err
	}
}
771651
func (ref *SyncProducer) SendMsgToPartition(topic string, partition int32, key sarama.Encoder, msg sarama.Encoder) (*ProducerMessage, error) {
	if msg == nil {
		err := errors.New("nil message can not be sent")
		ref.Error(err)
		return nil, err
	}
	message := &sarama.ProducerMessage{
		Topic:     topic,
		Partition: partition,
		Value:     msg,
		Key:       key,
	}

	partition, offset, err := ref.Producer.SendMessage(message)
	pmsg := &ProducerMessage{
		Topic:     message.Topic,
		Key:       message.Key,
		Value:     message.Value,
		Metadata:  message.Metadata,
		Offset:    offset,
		Partition: partition,
	}
	if err != nil {
		return pmsg, err
	}

	ref.Debugf("message sent: %s", pmsg)
	return pmsg, nil
}
732572
func (r *readlineUI) PrintErr(args ...interface{}) {
	text := fmt.Sprint(args...)
	if !strings.HasSuffix(text, "\n") {
		text += "\n"
	}
	if readline.IsTerminal(int(syscall.Stderr)) {
		text = colorize(text)
	}
	fmt.Fprint(r.rl.Stderr(), text)
}
1127281
func (s *sdkGrpcServer) rwlockIntercepter(
	ctx context.Context,
	req interface{},
	info *grpc.UnaryServerInfo,
	handler grpc.UnaryHandler,
) (interface{}, error) {
	s.lock.RLock()
	defer s.lock.RUnlock()

	return handler(ctx, req)
}
181649
func PublisherAfter(after ...PublisherResponseFunc) PublisherOption {
	return func(p *Publisher) { p.after = append(p.after, after...) }
}
275439
func PublisherBefore(before ...RequestFunc) PublisherOption {
	return func(p *Publisher) { p.before = append(p.before, before...) }
}
14953
func (a *Agent) Publisher(ctx context.Context, subscriptionID string) (exec.LogPublisher, func(), error) {
	// TODO(stevvooe): The level of coordination here is WAY too much for logs.
	// These should only be best effort and really just buffer until a session is
	// ready. Ideally, they would use a separate connection completely.

	var (
		err       error
		publisher api.LogBroker_PublishLogsClient
	)

	err = a.withSession(ctx, func(session *session) error {
		publisher, err = api.NewLogBrokerClient(session.conn.ClientConn).PublishLogs(ctx)
		return err
	})
	if err != nil {
		return nil, nil, err
	}

	// make little closure for ending the log stream
	sendCloseMsg := func() {
		// send a close message, to tell the manager our logs are done
		publisher.Send(&api.PublishLogsMessage{
			SubscriptionID: subscriptionID,
			Close:          true,
		})
		// close the stream forreal
		publisher.CloseSend()
	}

	return exec.LogPublisherFunc(func(ctx context.Context, message api.LogMessage) error {
			select {
			case <-ctx.Done():
				sendCloseMsg()
				return ctx.Err()
			default:
			}

			return publisher.Send(&api.PublishLogsMessage{
				SubscriptionID: subscriptionID,
				Messages:       []api.LogMessage{message},
			})
		}), func() {
			sendCloseMsg()
		}, nil
}