File: _example_customdns_test.go

package info (click to toggle)
golang-mongodb-mongo-driver 1.17.1%2Bds1-2
  • links: PTS, VCS
  • area: main
  • in suites: experimental, trixie
  • size: 25,988 kB
  • sloc: perl: 533; ansic: 491; python: 432; sh: 327; makefile: 174
file content (138 lines) | stat: -rw-r--r-- 3,095 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
// Copyright (C) MongoDB, Inc. 2022-present.
//
// 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

package examples

import (
	"context"
	"log"
	"net"
	"sync"
	"testing"
	"time"

	"github.com/miekg/dns"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func resolve(ctx context.Context, cache *dnsCache, in *dns.Conn, out *dns.Conn) {
	for ctx.Err() == nil {
		q, err := in.ReadMsg()
		if err != nil {
			// TODO: Handle error.
			log.Fatalf("Unhandled error in ReadMsg: %v", err)
		}
		if len(q.Question) != 1 {
			// Multiple questions in a single query is not actually used in real life.
			continue
		}

		a, err := func() (*dns.Msg, error) {
			cache.lock.Lock()
			defer cache.lock.Unlock()

			now := time.Now()
			if rr, ok := cache.records[q.Question[0]]; ok && rr.exp.After(now) {
				a := new(dns.Msg)
				a.SetReply(q)
				a.Compress = false
				a.Answer = append(a.Answer, rr.record)
				return a, nil
			}

			err := out.WriteMsg(q)
			if err != nil {
				return nil, err
			}

			m, err := out.ReadMsg()
			if err != nil {
				return nil, err
			}

			l := len(m.Answer)
			for i, q := range m.Question {
				if i >= l {
					break
				}
				a := m.Answer[i]
				cache.records[q] = &RR{
					a,
					now.Add(time.Second * time.Duration(a.Header().Ttl)),
				}
			}
			return m, nil
		}()
		if err != nil {
			// TODO: Handle error.
			log.Fatalf("Unhandled error in record retrieval: %v", err)
		}

		if err := in.WriteMsg(a); err != nil {
			// TODO: Handle error.
			log.Fatalf("Unhandled error in WriteMsg: %v", err)
		}
	}
}

type RR struct {
	record dns.RR
	exp    time.Time
}

type dnsCache struct {
	records map[dns.Question]*RR
	lock    sync.Mutex
}

type dialer struct {
	*net.Dialer
	cache *dnsCache
}

func NewDialer() dialer {
	cache := &dnsCache{
		records: make(map[dns.Question]*RR),
		lock:    sync.Mutex{},
	}
	return dialer{
		Dialer: &net.Dialer{
			Resolver: &net.Resolver{
				PreferGo: true,
				Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
					var d net.Dialer
					outConn, err := d.DialContext(ctx, network, address)
					conn, inConn := net.Pipe()
					if err == nil {
						go resolve(ctx, cache, &dns.Conn{Conn: inConn}, &dns.Conn{Conn: outConn})
					}
					return conn, err
				},
			},
		},
		cache: cache,
	}
}

func TestCustomDialer(t *testing.T) {
	client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://testurl:27017").SetDialer(NewDialer()))
	if err != nil {
		t.Fatalf("error creating client: %v", err)
	}
	ctx := context.Background()
	err = client.Connect(ctx)
	if err != nil {
		t.Fatalf("error connecting: %v", err)
	}
	defer client.Disconnect(context.Background())
	coll := client.Database("test").Collection("test")
	_, err = coll.InsertOne(context.Background(), bson.D{{"text", "text"}})
	if err != nil {
		t.Fatalf("error inserting: %v", err)
	}
}