Mike Gerwitz

Activist for User Freedom

aboutsummaryrefslogtreecommitdiffstats
blob: 6d50bfc6c3fd72f593d6858b082341dbf77d84ac (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
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
/**
 * Amqp Connection
 *
 *  Copyright (C) 2010-2019 R-T Specialty, LLC.
 *
 *  This file is part of liza.
 *
 *  liza is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
import { AmqpConfig } from '../AmqpPublisher';
import { EventEmitter } from "events";
import * as amqplib from "amqplib";

/**
 * Connection to AMQP exchange
 *
 * XXX: Needs tests!
 */
export class AmqpConnection
{
    /** The amqp connection */
    private _conn?: amqplib.Connection;

    /** The amqp channel */
    private _channel?: amqplib.Channel;


    /**
     * Amqp Connection
     *
     * @param _conf    - amqp configuration
     * @param _emitter - event emitter instance
     */
    constructor(
        private readonly _amqp:    typeof amqplib,
        private readonly _conf:    AmqpConfig,
        private readonly _emitter: EventEmitter,
    ) {}


    /**
     * Initialize connection
     */
    connect(): Promise<void>
    {
        return this._amqp.connect( this._conf )
            .then( conn =>
            {
                this._conn = conn;

                /** If there is an error, attempt to reconnect
                 *  Only hook this once because it will be re-hooked on each
                 *  successive successful connection
                 */
                this._conn.once( 'error', e =>
                {
                    this._emitter.emit( 'amqp-conn-error', e );
                    this._reconnect();
                } );

                return this._conn.createChannel();
            } )
            .then( ( ch: amqplib.Channel ) =>
            {
                this._channel = ch;

                return this._channel.assertExchange(
                    this._conf.exchange,
                    'fanout',
                    { durable: true }
                );
            } )
            .then( _ => {} );
    }


    /**
     * Attempt to re-establish the connection
     *
     * @param retry_count - the number of retries attempted
     */
    private _reconnect( retry_count: number = 0 ): void
    {
        if ( retry_count >= this._conf.retries )
        {
            this._emitter.emit(
                'error',
                new Error( 'Could not re-establish AMQP connection.' )
            );

            return;
        }

        this._emitter.emit( 'amqp-reconnect' );

        this.connect()
            .then( _ => { this._emitter.emit( 'amqp-reconnected' ) } )
            .catch( _ =>
            {
                const wait_ms = this._conf.retry_wait;
                setTimeout( () => this._reconnect( ++retry_count ), wait_ms );
            } );
    }


    /**
     * Returns the exchange to publish to
     *
     * @return exchange name
     */
    getExchangeName(): string
    {
        return this._conf.exchange;
    }


    /**
     * Returns the amqp channel
     *
     * @return exchange name
     */
    getAmqpChannel(): amqplib.Channel | undefined
    {
        if ( !this._channel )
        {
            this._reconnect();
        }

        return this._channel;
    }


    /**
     * Close the amqp conenction
     */
    close(): void
    {
        if ( this._conn )
        {
            this._conn.close.bind(this._conn);
        }
    }
}