summaryrefslogtreecommitdiffstats
path: root/nixos/tests/nats.nix
blob: ea9dcf34e4d8851cd49905179875504d66eb458b (plain)
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
let

  port = 4222;
  username = "client";
  password = "password";
  topic = "foo.bar";

in
{ lib, ... }:
{
  name = "nats";
  meta = {
    maintainers = with lib.maintainers; [ c0deaddict ];
  };

  nodes =
    let
      client =
        { pkgs, ... }:
        {
          environment.systemPackages = with pkgs; [ natscli ];
        };
    in
    {
      server =
        { pkgs, ... }:
        {
          networking.firewall.allowedTCPPorts = [ port ];
          services.nats = {
            inherit port;
            enable = true;
            settings = {
              authorization = {
                users = [
                  {
                    user = username;
                    inherit password;
                  }
                ];
              };
            };
          };
        };

      client1 = client;
      client2 = client;
    };

  testScript =
    let
      file = "/tmp/msg";
    in
    ''
      def nats_cmd(*args):
          return (
              "nats "
              "--server=nats://server:${toString port} "
              "--user=${username} "
              "--password=${password} "
              "{}"
          ).format(" ".join(args))

      def parallel(*fns):
          from threading import Thread
          threads = [ Thread(target=fn) for fn in fns ]
          for t in threads: t.start()
          for t in threads: t.join()

      start_all()
      server.wait_for_unit("nats.service")

      with subtest("pub sub"):
          parallel(
              lambda: client1.succeed(nats_cmd("sub", "--count", "1", "${topic}")),
              lambda: client2.succeed("sleep 2 && {}".format(nats_cmd("pub", "${topic}", "hello"))),
          )
    '';
}