├── .github
└── workflows
│ └── golang-ci.yml
├── .gitignore
├── .golangci.yml
├── LICENSE
├── Makefile
├── README.md
├── README_zh.md
├── cmd
├── broker
│ └── broker.go
└── logic
│ └── logic.go
├── config_files
├── config.broker.yaml
└── config.logic.yaml
├── consts
├── consts.go
└── version.go
├── docker_compose
├── README
├── config.broker.yaml
├── config.logic.yaml
├── docker-compose.yaml
└── schema.sql
├── dockerfile
├── Dockerfile.broker
└── Dockerfile.logic
├── docs
├── command.md
├── command_zh.md
├── deployment
│ ├── chat-broker.service
│ └── chat-logic.service
├── mysql.md
├── mysql_zh.md
└── schema.sql
├── go.mod
├── go.sum
├── img
├── arch.png
├── arch2.png
├── chat_window.jpg
├── jetbrains.svg
├── logo.png
└── seq.jpeg
├── internal
├── biz
│ ├── reg.go
│ └── session.go
├── config
│ ├── base.go
│ ├── broker.go
│ └── logic.go
├── dao
│ ├── account.go
│ └── view_ack.go
├── engine
│ ├── broker
│ │ ├── grpc_worker.go
│ │ ├── ping_worker.go
│ │ └── websocket_worker.go
│ └── logic
│ │ ├── broker_checker.go
│ │ ├── grpc_worker.go
│ │ ├── pump_dialogue_loop.go
│ │ ├── pump_signal_loop.go
│ │ └── token.go
├── log
│ └── init.go
├── middleware
│ ├── ratelimit.go
│ └── record_req.go
├── resolver
│ └── srv
│ │ └── srv_resolver.go
├── resource
│ ├── base.go
│ ├── broker.go
│ └── logic.go
└── utils
│ ├── addr.go
│ ├── chat.go
│ ├── utils.go
│ └── wait_group_wrapper.go
├── model
├── broker.go
├── dto.go
├── logic.go
└── orm.go
├── proto
├── README
├── broker.pb.go
├── broker.proto
├── logic.pb.go
└── logic.proto
└── test
├── mock_client
└── client.sh
└── test_proto.go
/.github/workflows/golang-ci.yml:
--------------------------------------------------------------------------------
1 | name: golang-ci
2 |
3 | on:
4 | # Trigger the workflow on push or pull request,
5 | # but only for the main branch
6 | push:
7 | branches:
8 | - main
9 | - master
10 | pull_request:
11 | branches:
12 | - main
13 | - master
14 | # Allows you to run this workflow manually from the Actions tab
15 | workflow_dispatch:
16 |
17 | jobs:
18 | lint:
19 | runs-on: ubuntu-latest
20 | container:
21 | image: golangci/golangci-lint:v1.62.0
22 | steps:
23 | - name: checkout
24 | uses: actions/checkout@v4
25 | - name: Set GOFLAGS
26 | run: echo "GOFLAGS=-buildvcs=false" >> $GITHUB_ENV
27 | - name: golangci-lint
28 | run: golangci-lint run --modules-download-mode=mod
29 |
30 | build:
31 | runs-on: ubuntu-latest
32 | steps:
33 | - name: checkout
34 | uses: actions/checkout@v4
35 | - name: Set up Go
36 | uses: actions/setup-go@v4
37 | with:
38 | go-version: 1.23
39 | - name: build broker
40 | run: go build -o chat-broker ./cmd/broker
41 | - name: build logic
42 | run: go build -o chat-logic ./cmd/logic
43 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Created by .ignore support plugin (hsz.mobi)
2 | ### Go template
3 | # Binaries for programs and plugins
4 | *.exe
5 | *.exe~
6 | *.dll
7 | *.so
8 | *.dylib
9 |
10 | # Test binary, build with `go test -c`
11 | *.test
12 |
13 | # Output of the go coverage tool, specifically when used with LiteIDE
14 | *.out
15 | ### JetBrains template
16 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
17 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
18 |
19 | # User-specific stuff
20 | .idea/**/workspace.xml
21 | .idea/**/tasks.xml
22 | .idea/**/dictionaries
23 | .idea/**/shelf
24 |
25 | # Sensitive or high-churn files
26 | .idea/**/dataSources/
27 | .idea/**/dataSources.ids
28 | .idea/**/dataSources.local.xml
29 | .idea/**/sqlDataSources.xml
30 | .idea/**/dynamic.xml
31 | .idea/**/uiDesigner.xml
32 |
33 | # Gradle
34 | .idea/**/gradle.xml
35 | .idea/**/libraries
36 |
37 |
38 | #DS_STORE
39 | .DS_Store
40 |
41 | # CMake
42 | cmake-build-debug/
43 | cmake-build-release/
44 |
45 | # Mongo Explorer plugin
46 | .idea/**/mongoSettings.xml
47 |
48 | # File-based project format
49 | *.iws
50 |
51 | # IntelliJ
52 | out/
53 |
54 | export/
55 | dist/
56 |
57 | # mpeltonen/sbt-idea plugin
58 | .idea_modules/
59 |
60 | # JIRA plugin
61 | atlassian-ide-plugin.xml
62 |
63 | # Cursive Clojure plugin
64 | .idea/replstate.xml
65 |
66 | # Crashlytics plugin (for Android Studio and IntelliJ)
67 | com_crashlytics_export_strings.xml
68 | crashlytics.properties
69 | crashlytics-build.properties
70 | fabric.properties
71 |
72 | # Editor-based Rest Client
73 | .idea/httpRequests
74 |
75 | .idea
76 | ### VisualStudioCode template
77 | .vscode/
78 | !.vscode/settings.json
79 | !.vscode/tasks.json
80 | !.vscode/launch.json
81 | !.vscode/extensions.json
82 |
83 | *.retry
84 |
85 | cover*.html
86 | */*.log
87 | *.swp
88 |
89 | chat
90 | dist
91 | vendor
92 |
--------------------------------------------------------------------------------
/.golangci.yml:
--------------------------------------------------------------------------------
1 | linters:
2 | # https://golangci-lint.run/usage/linters
3 | disable-all: true # 关闭其他linter
4 | enable:
5 | - errcheck # Errcheck 是一个用于检查 Go 代码中未处理错误的程序。在某些情况下,这些未处理的错误可能会导致严重的漏洞。
6 | - gosimple # 专注于简化代码的 Go 源代码 Linter。
7 | - govet # Vet 检查 Go 源代码并报告可疑的结构。它大致等同于 go vet,并使用其检查项。
8 | - ineffassign # 检测对已存在变量的赋值是否未被使用
9 | - staticcheck # 一组静态检查规则
10 | - unused # 检查 Go 代码中未使用的常量、变量、函数和类型
11 | - copyloopvar # 检测循环变量是否被拷贝
12 | - gocyclo # 计算并检查函数的圈复杂度
13 | - gocognit # 计算并检查函数的认知复杂度
14 |
15 | linters-settings:
16 | govet: # 对于linter govet,我们手动开启了它的某些扫描规则
17 | enable-all: true
18 | disable:
19 | - fieldalignment
20 | gocyclo:
21 | # Default: 30 (but we recommend 10-20)
22 | min-complexity: 20
23 | gocognit:
24 | # Minimal code complexity to report.
25 | # Default: 30 (but we recommend 10-20)
26 | min-complexity: 30
27 |
28 | issues:
29 | exclude-dirs:
30 | - scripts
31 | - test
32 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | VERSION :=v0.1.5
2 |
3 | RELEASE_DIR = dist
4 | IMPORT_PATH = github.com/vearne/chat
5 |
6 | BUILD_COMMIT := $(shell git rev-parse --short HEAD)
7 | BUILD_TIME := $(shell date +%Y%m%d%H%M%S)
8 | GITTAG = `git log -1 --pretty=format:"%H"`
9 | LDFLAGS = -ldflags "-s -w -X ${IMPORT_PATH}/consts.GitTag=${GITTAG} -X ${IMPORT_PATH}/consts.BuildTime=${BUILD_TIME} -X ${IMPORT_PATH}/consts.Version=${VERSION}"
10 |
11 | #TAG = ${VERSION}-${BUILD_TIME}-${BUILD_COMMIT}
12 | TAG = ${VERSION}
13 | IMAGE_BROKER = woshiaotian/chat-broker:${TAG}
14 | IMAGE_LOGIC = woshiaotian/chat-logic:${TAG}
15 |
16 |
17 | .PHONY: clean
18 | clean: ## Remove release binaries
19 | rm -rf ${RELEASE_DIR}
20 |
21 | build-dirs: clean
22 | mkdir -p ${RELEASE_DIR}
23 |
24 | .PHONY: build
25 | build: build-dirs
26 | env GOOS=linux GOARCH=amd64 go build ${LDFLAGS} -o ${RELEASE_DIR}/chat-broker ./cmd/broker
27 | env GOOS=linux GOARCH=amd64 go build ${LDFLAGS} -o ${RELEASE_DIR}/chat-logic ./cmd/logic
28 | chmod +x ${RELEASE_DIR}/*
29 |
30 | .PHONY: image
31 | image:
32 | # broker
33 | docker build -f ./dockerfile/Dockerfile.broker \
34 | --build-arg BUILD_VERSION=$(VERSION) \
35 | --build-arg BUILD_TIME=$(BUILD_TIME) \
36 | --build-arg BUILD_COMMIT=$(BUILD_COMMIT) \
37 | --rm --no-cache -t ${IMAGE_BROKER} .
38 |
39 | docker push ${IMAGE_BROKER}
40 | # logic
41 | docker build -f ./dockerfile/Dockerfile.logic \
42 | --build-arg BUILD_VERSION=$(VERSION) \
43 | --build-arg BUILD_TIME=$(BUILD_TIME) \
44 | --build-arg BUILD_COMMIT=$(BUILD_COMMIT) \
45 | --rm --no-cache -t ${IMAGE_LOGIC} .
46 | docker push ${IMAGE_LOGIC}
47 |
48 |
49 | .PHONY: image-multiple
50 | image-multiple:
51 | # broker
52 | docker buildx build -f ./dockerfile/Dockerfile.broker \
53 | --build-arg BUILD_VERSION=$(VERSION) \
54 | --build-arg BUILD_TIME=$(BUILD_TIME) \
55 | --build-arg BUILD_COMMIT=$(BUILD_COMMIT) \
56 | --platform linux/amd64,linux/arm64 --push -t ${IMAGE_BROKER} .
57 | # logic
58 | docker buildx build -f ./dockerfile/Dockerfile.logic \
59 | --build-arg BUILD_VERSION=$(VERSION) \
60 | --build-arg BUILD_TIME=$(BUILD_TIME) \
61 | --build-arg BUILD_COMMIT=$(BUILD_COMMIT) \
62 | --platform linux/amd64,linux/arm64 --push -t ${IMAGE_LOGIC} .
63 |
64 |
65 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | # chat
5 | [](https://github.com/vearne/chat/actions/workflows/golang-ci.yml)
6 |
7 | This chat system is designed to automatically match strangers for chat, so no registration is required
8 |
9 | [中文 README](./README_zh.md)
10 |
11 | ## Feature
12 | * Supports service discovery through Etcd, so the entire system is easy to scale horizontally
13 |
14 |
15 | ## Online service
16 | [chat.vearne.cc](http://chat.vearne.cc/)
17 |
18 | Notice: If no other match is available,
19 | you can open multiple windows and chat with yourself.
20 | ## Quick Start with Docker compose
21 | Switch to directory [docker_compose](https://github.com/vearne/chat/tree/master/docker_compose)
22 | ```
23 | cd docker_compose
24 | ```
25 |
26 | ### start
27 |
28 | ```
29 | docker-compose up -d
30 | ```
31 |
32 | ### stop
33 | ```
34 | docker-compose down
35 | ```
36 | Then you can open a browser and visit
37 | http://localhost/
38 |
39 | ### Interface
40 | Notice: If no other match is available,
41 | you can open multiple windows and chat with yourself.
42 | 
43 |
44 | ### Architecture
45 | 
46 |
47 | ### Database Table Design
48 | [database](./docs/mysql.md)
49 |
50 | ### Websocket Command
51 | [command](./docs/command.md)
52 |
53 | ### Supporting projects
54 | [chat-ui](https://github.com/vearne/chat-ui)
55 |
56 | ### Thanks
57 | >"If I have been able to see further, it was only because I stood on the shoulders of giants." by Isaac Newton
58 |
59 | ### Thanks to JetBrains
60 | [](https://www.jetbrains.com/community/opensource/#support)
61 |
62 |
--------------------------------------------------------------------------------
/README_zh.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | # chat
6 | [](https://github.com/vearne/chat/actions/workflows/golang-ci.yml)
7 |
8 | chat是一个对陌生人随机匹配的聊天系统。
9 |
10 | [English README](./README.md)
11 |
12 | ## 特色
13 | * 支持通过Etcd进行服务发现,因此整个系统很容易进行水平扩展
14 |
15 | ## 在线服务
16 | [chat.vearne.cc](http://chat.vearne.cc/)
17 |
18 | 注意:如果无法配到到其他人, 您可以打开多个窗口并与自己聊天。
19 | ## 使用Docker compose快速开始
20 | 切换到目录 [docker_compose](https://github.com/vearne/chat/tree/master/docker_compose)
21 | ```
22 | cd docker_compose
23 | ```
24 |
25 | ### 启动
26 |
27 | ```
28 | docker-compose up -d
29 | ```
30 |
31 | ### 停止
32 | ```
33 | docker-compose down
34 | ```
35 | 然后,你可以打开浏览器,并访问
36 | http://localhost/
37 |
38 | ### 交互界面
39 | 注意:如果无法配到到其他人, 您可以打开多个窗口并与自己聊天。
40 | 
41 |
42 | ### 架构
43 | 
44 |
45 | ### 数据库表设计
46 | [database](./docs/mysql_zh.md)
47 |
48 | ### Websocket 命令
49 | [command](./docs/command_zh.md)
50 |
51 | ### 配套项目
52 | [chat-ui](https://github.com/vearne/chat-ui)
53 |
54 | ### 感谢
55 | >"If I have been able to see further, it was only because I stood on the shoulders of giants." by Isaac Newton
56 |
57 |
--------------------------------------------------------------------------------
/cmd/broker/broker.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "flag"
5 | "fmt"
6 | "github.com/vearne/chat/consts"
7 | config2 "github.com/vearne/chat/internal/config"
8 | broker2 "github.com/vearne/chat/internal/engine/broker"
9 | zlog "github.com/vearne/chat/internal/log"
10 | "github.com/vearne/chat/internal/resource"
11 | wm "github.com/vearne/worker_manager"
12 | clientv3 "go.etcd.io/etcd/client/v3"
13 | etcdresolver "go.etcd.io/etcd/client/v3/naming/resolver"
14 | "go.uber.org/zap"
15 | "google.golang.org/grpc/resolver"
16 | "log"
17 | "os"
18 | "strings"
19 | "time"
20 | )
21 |
22 | var (
23 | // config file path
24 | cfgFile string
25 | versionFlag bool
26 | )
27 |
28 | func init() {
29 | flag.StringVar(&cfgFile, "config", "", "config file")
30 | flag.BoolVar(&versionFlag, "version", false, "Show version")
31 |
32 | // register gRPC resolver
33 | regEtcdResolver()
34 | }
35 |
36 | func main() {
37 | flag.Parse()
38 |
39 | if versionFlag {
40 | fmt.Println("service: chat-broker")
41 | fmt.Println("Version", consts.Version)
42 | fmt.Println("BuildTime", consts.BuildTime)
43 | fmt.Println("GitTag", consts.GitTag)
44 | return
45 | }
46 |
47 | config2.ReadConfig("broker", cfgFile)
48 | config2.InitBrokerConfig()
49 |
50 | zlog.InitLogger(&config2.GetBrokerOpts().Logger)
51 | resource.InitBrokerResource()
52 |
53 | app := wm.NewApp()
54 | app.AddWorker(broker2.NewWebsocketWorker())
55 | app.AddWorker(broker2.NewGrpcWorker())
56 | app.AddWorker(broker2.NewPingWorker())
57 | app.Run()
58 | }
59 |
60 | func regEtcdResolver() {
61 | // ETCD_ENDPOINTS="192.168.2.101:2379;192.168.2.102:2379;192.168.2.103:2379"
62 | // ETCD_USERNAME=root
63 | // ETCD_PASSWORD=8323-01AmA004A509
64 | endpoints, ok := os.LookupEnv("ETCD_ENDPOINTS")
65 | username := os.Getenv("ETCD_USERNAME")
66 | password := os.Getenv("ETCD_PASSWORD")
67 | if !ok {
68 | return
69 | }
70 |
71 | log.Println("regEtcdResolver, endpoints:", endpoints)
72 | cf := clientv3.Config{
73 | Endpoints: strings.Split(endpoints, ";"),
74 | DialTimeout: 5 * time.Second,
75 | Logger: zlog.DefaultLogger,
76 | }
77 | if len(username) > 0 {
78 | cf.Username = username
79 | cf.Password = password
80 | }
81 | cli, err := clientv3.New(cf)
82 | if err != nil {
83 | log.Fatal("regEtcdResolver", zap.Error(err))
84 | }
85 |
86 | etcdResolver, err := etcdresolver.NewBuilder(cli)
87 | if err != nil {
88 | log.Fatal("regEtcdResolver", zap.Error(err))
89 | }
90 | resolver.Register(etcdResolver)
91 | }
92 |
--------------------------------------------------------------------------------
/cmd/logic/logic.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "flag"
5 | "fmt"
6 |
7 | "github.com/vearne/chat/consts"
8 | "github.com/vearne/chat/internal/biz"
9 | config2 "github.com/vearne/chat/internal/config"
10 | logic2 "github.com/vearne/chat/internal/engine/logic"
11 | zlog "github.com/vearne/chat/internal/log"
12 | "github.com/vearne/chat/internal/resource"
13 | "github.com/vearne/chat/internal/utils"
14 | wm "github.com/vearne/worker_manager"
15 | "go.uber.org/zap"
16 | )
17 |
18 | var (
19 | // config file path
20 | cfgFile string
21 | versionFlag bool
22 | )
23 |
24 | func init() {
25 | flag.StringVar(&cfgFile, "config", "", "config file")
26 | flag.BoolVar(&versionFlag, "version", false, "Show version")
27 | }
28 |
29 | func main() {
30 | flag.Parse()
31 |
32 | if versionFlag {
33 | fmt.Println("service: chat-broker")
34 | fmt.Println("Version", consts.Version)
35 | fmt.Println("BuildTime", consts.BuildTime)
36 | fmt.Println("GitTag", consts.GitTag)
37 | return
38 | }
39 |
40 | config2.ReadConfig("logic", cfgFile)
41 | config2.InitLogicConfig()
42 |
43 | zlog.InitLogger(&config2.GetLogicOpts().Logger)
44 | resource.InitLogicResource()
45 |
46 | fmt.Println("logic starting ... ")
47 |
48 | regService()
49 |
50 | app := wm.NewApp()
51 | app.AddWorker(logic2.NewLogicGrpcWorker())
52 | app.AddWorker(logic2.NewPumpSignalLoopWorker())
53 | app.AddWorker(logic2.NewPumpDialogueLoopWorker(1, 5))
54 | app.AddWorker(logic2.NewBrokerChecker())
55 | app.Run()
56 | }
57 |
58 | func regService() {
59 | ec := config2.GetLogicOpts().Ectd
60 |
61 | if ec.Register {
62 | ip, _ := utils.GetIP()
63 | addr := ip + config2.GetLogicOpts().LogicDealer.ListenAddress
64 | ser, err := biz.NewServiceRegister(
65 | ec.Endpoints,
66 | ec.Username,
67 | ec.Password,
68 | "services/logic",
69 | addr)
70 | if err != nil {
71 | zlog.Fatal("regService", zap.Error(err))
72 | }
73 | //监听续租相应chan
74 | go ser.ListenLeaseRespChan()
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/config_files/config.broker.yaml:
--------------------------------------------------------------------------------
1 | logic_dealer:
2 | # TCP 直连
3 | # address: "127.0.0.1:18223"
4 |
5 | ## 支持多种resolver
6 | # 1) SRV
7 | # dig @8.8.8.8 _grpclb._tcp.logic.vearne.cc srv
8 | # 在dns中 _grpclb._tcp.logic.vearne.cc -> 0 50 28223 logic1.vearne.cc
9 | # _grpclb._tcp.logic.vearne.cc -> 0 50 28224 logic2.vearne.cc
10 | # address: "srv://8.8.8.8/logic.vearne.cc"
11 |
12 | # 2) DNS
13 | # address: "dns://8.8.8.8/example.grpc.com:18223"
14 |
15 | # 3) ETCD
16 | # https://etcd.io/docs/v3.5/dev-guide/grpc_naming/
17 | # logic is the name of the service
18 | #
19 | # NOTICE: To use etcd resolver, environment variables need to be given
20 | # ETCD_ENDPOINTS="192.168.2.101:2379;192.168.2.102:2379;192.168.2.103:2379"
21 | # ETCD_USERNAME=root
22 | # ETCD_PASSWORD=8323-01AmA004A509
23 | # address: "etcd:///services/logic"
24 |
25 | # address: "127.0.0.1:18223"
26 | address: "etcd:///services/logic"
27 |
28 |
29 | logger:
30 | # 1. "info"
31 | # 2. "debug"
32 | # 3. "error"
33 | level: "debug"
34 | filepath: "/var/log/test/chat_broker.log"
35 |
36 | # broker的配置
37 | broker:
38 | ws_address: ":18224"
39 | grpc_address: ":18225"
40 |
41 | # 用Ping检查Client是否退出或者掉线
42 | # 超过maxWait就认为Client已经掉线
43 | ping:
44 | interval: "3s"
45 | maxWait: "20s"
46 |
47 | # debug log for grpc request
48 | service-debug: true
49 |
50 |
51 |
52 |
--------------------------------------------------------------------------------
/config_files/config.logic.yaml:
--------------------------------------------------------------------------------
1 | logic_dealer:
2 | listen_address: ":18223"
3 |
4 | logger:
5 | # 1. "info"
6 | # 2. "debug"
7 | # 3. "error"
8 | level: "info"
9 | filepath: "/var/log/test/chat_logic.log"
10 |
11 | mysql:
12 | dsn: "root:9E68-2607F7855D7D@tcp(127.0.0.1:23406)/chat?charset=utf8&loc=Asia%2FShanghai&parseTime=true"
13 | max_idle_conn: 50
14 | max_open_conn: 100
15 | conn_max_life_secs: 600
16 | # 是否启动debug模式
17 | # 若开启则会打印具体的执行SQL
18 | debug: true
19 |
20 | etcd:
21 | register: true
22 | endpoints:
23 | - 127.0.0.1:2379
24 | username: root
25 | password: 8323-01AmA004A509
26 |
27 | # debug log for grpc request
28 | service-debug: true
--------------------------------------------------------------------------------
/consts/consts.go:
--------------------------------------------------------------------------------
1 | package consts
2 |
3 | const (
4 | AccountStatusCreated = iota
5 | AccountStatusInUse
6 | AccountStatusDestroyed
7 | )
8 | const (
9 | SessionStatusCreated = iota
10 | SessionStatusInUse
11 | SessionStatusDestroyed
12 | )
13 |
14 | const (
15 | OutBoxStatusNormal = iota
16 | OutBoxStatusDeleted
17 | )
18 |
19 | const (
20 | InBoxStatusCreated = iota
21 | InBoxStatusDelivered
22 | )
23 |
24 | const (
25 | SystemSender = 0
26 | )
27 |
28 | const (
29 | CmdCreateAccount = "CRT_ACCOUNT"
30 | CmdMatch = "MATCH"
31 | CmdDialogue = "DIALOGUE"
32 | CmdPushDialogue = "PUSH_DIALOGUE"
33 | CmdPushSignal = "PUSH_SIGNAL"
34 | CmdPing = "PING"
35 | CmdViewedAck = "VIEWED_ACK"
36 | CmdPushViewedAck = "PUSH_VIEWED_ACK"
37 | CmdReConnect = "RECONNECT"
38 | )
39 |
--------------------------------------------------------------------------------
/consts/version.go:
--------------------------------------------------------------------------------
1 | package consts
2 |
3 | import "time"
4 |
5 | var (
6 | // Version logs build version injected with -ldflags -X opitons.
7 | Version string
8 |
9 | // BuildTime logs build time injected with -ldflags -X opitons.
10 | BuildTime string
11 |
12 | // GitTag logs git version and injected with -ldflags -X opitons.
13 | GitTag string
14 |
15 | // uptime
16 | UpTime string
17 | )
18 |
19 | func init() {
20 | UpTime = time.Now().Format(time.RFC3339)
21 | }
22 |
--------------------------------------------------------------------------------
/docker_compose/README:
--------------------------------------------------------------------------------
1 | ## start
2 | ```
3 | docker-compose up -d
4 | ```
5 |
6 | ## stop
7 | ```
8 | docker-compose down
9 | ```
--------------------------------------------------------------------------------
/docker_compose/config.broker.yaml:
--------------------------------------------------------------------------------
1 | logic_dealer:
2 | address: logic:18223
3 |
4 | logger:
5 | # 1. "info"
6 | # 2. "debug"
7 | # 3. "error"
8 | level: "debug"
9 | filepath: "/var/log/chat_broker.log"
10 |
11 | # broker的配置
12 | broker:
13 | ws_address: ":18224"
14 | grpc_address: ":18225"
15 |
16 | # 用Ping检查Client是否退出或者掉线
17 | # 超过maxWait就认为Client已经掉线
18 | ping:
19 | interval: "3s"
20 | maxWait: "20s"
21 |
--------------------------------------------------------------------------------
/docker_compose/config.logic.yaml:
--------------------------------------------------------------------------------
1 | logic_dealer:
2 | listen_address: ":18223"
3 |
4 | logger:
5 | # 1. "info"
6 | # 2. "debug"
7 | # 3. "error"
8 | level: "debug"
9 | filepath: "/var/log/chat_logic.log"
10 |
11 | mysql:
12 | dsn: "root:happy-chat@tcp(mysql:3306)/chat?charset=utf8&loc=Asia%2FShanghai&parseTime=true"
13 | max_idle_conn: 50
14 | max_open_conn: 100
15 | conn_max_life_secs: 600
16 | # 是否启动debug模式
17 | # 若开启则会打印具体的执行SQL
18 | debug: true
19 |
20 |
--------------------------------------------------------------------------------
/docker_compose/docker-compose.yaml:
--------------------------------------------------------------------------------
1 | services:
2 | mysql:
3 | image: mysql:8
4 | volumes:
5 | - ./schema.sql:/docker-entrypoint-initdb.d/init.sql
6 | environment:
7 | MYSQL_ROOT_PASSWORD: happy-chat
8 | healthcheck:
9 | test: [ "CMD", "mysqladmin", "ping", "-h", "localhost" ]
10 | interval: 3s # 健康检查的间隔
11 | timeout: 3s
12 | retries: 3
13 | start_period: 5s
14 |
15 | logic:
16 | image: woshiaotian/chat-logic:v0.1.5
17 | depends_on:
18 | mysql:
19 | condition: service_healthy
20 | volumes:
21 | - ./config.logic.yaml:/data/config.logic.yaml
22 |
23 | broker:
24 | image: woshiaotian/chat-broker:v0.1.5
25 | depends_on:
26 | - logic
27 | volumes:
28 | - ./config.broker.yaml:/data/config.broker.yaml
29 | # ports:
30 | # - 18224:18224
31 |
32 | chat-ui:
33 | image: woshiaotian/chat-ui:v0.0.3
34 | depends_on:
35 | - broker
36 | ports:
37 | - 80:80
38 | environment:
39 | API_HOST: broker:18224
40 |
--------------------------------------------------------------------------------
/docker_compose/schema.sql:
--------------------------------------------------------------------------------
1 | create database chat;
2 |
3 | use chat;
4 |
5 | CREATE TABLE `account` (
6 | `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
7 | `nickname` varchar(30) DEFAULT NULL,
8 | `status` int(11) DEFAULT NULL,
9 | `broker` varchar(255) DEFAULT NULL,
10 | `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
11 | `modified_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
12 | `token` varchar(50) DEFAULT '',
13 | PRIMARY KEY (`id`)
14 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
15 |
16 | CREATE TABLE `inbox` (
17 | `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
18 | `sender_id` bigint(20) unsigned DEFAULT NULL,
19 | `msg_id` bigint(20) unsigned DEFAULT NULL,
20 | `receiver_id` bigint(20) unsigned DEFAULT NULL,
21 | PRIMARY KEY (`id`),
22 | KEY `idx_receiver` (`receiver_id`)
23 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
24 |
25 | CREATE TABLE `outbox` (
26 | `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
27 | `sender_id` bigint(20) unsigned DEFAULT NULL,
28 | `session_id` bigint(20) unsigned DEFAULT NULL,
29 | `status` int(11) DEFAULT NULL,
30 | `msg_type` int(11) DEFAULT NULL,
31 | `content` varchar(255) DEFAULT NULL,
32 | `created_at` timestamp NULL DEFAULT NULL,
33 | `modified_at` timestamp NULL DEFAULT NULL,
34 | PRIMARY KEY (`id`),
35 | KEY `idx_sender` (`sender_id`)
36 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
37 |
38 | CREATE TABLE `session` (
39 | `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
40 | `status` int(11) DEFAULT NULL,
41 | `created_at` timestamp NULL DEFAULT NULL,
42 | `modified_at` timestamp NULL DEFAULT NULL,
43 | PRIMARY KEY (`id`)
44 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
45 |
46 |
47 | CREATE TABLE `session_account` (
48 | `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
49 | `session_id` bigint(20) unsigned DEFAULT NULL,
50 | `account_id` bigint(20) unsigned DEFAULT NULL,
51 | PRIMARY KEY (`id`),
52 | KEY `idx_session` (`session_id`)
53 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
54 |
55 | CREATE TABLE `view_ack` (
56 | `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
57 | `session_id` bigint(20) unsigned DEFAULT NULL,
58 | `account_id` bigint(20) unsigned DEFAULT NULL,
59 | `msg_id` bigint(20) unsigned DEFAULT NULL,
60 | `created_at` timestamp NULL DEFAULT NULL,
61 | PRIMARY KEY (`id`),
62 | UNIQUE KEY `idx_view_ack` (`session_id`,`account_id`)
63 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--------------------------------------------------------------------------------
/dockerfile/Dockerfile.broker:
--------------------------------------------------------------------------------
1 | # build
2 | FROM golang:1.21 as builder
3 | ADD . $GOPATH/src/github.com/vearne/chat
4 | WORKDIR $GOPATH/src/github.com/vearne/chat/cmd/broker
5 |
6 | ARG BUILD_VERSION=""
7 | ARG BUILD_TIME=""
8 | ARG BUILD_COMMIT=""
9 | ARG IMPORT_PATH="github.com/vearne/chat"
10 |
11 | ENV CGO_ENABLED=0
12 | RUN go build -o /bin/chat-broker\
13 | -ldflags "-s -w -X ${IMPORT_PATH}/consts.GitTag=${BUILD_COMMIT} -X ${IMPORT_PATH}/consts.BuildTime=${BUILD_TIME} -X ${IMPORT_PATH}/consts.Version=${BUILD_VERSION}"
14 |
15 |
16 | FROM woshiaotian/simple-base-image:v0.1.6
17 |
18 | WORKDIR /data
19 | COPY --from=builder /bin/chat-broker /data/chat-broker
20 |
21 | CMD ["/data/chat-broker", "--config", "/data/config.broker.yaml"]
22 |
--------------------------------------------------------------------------------
/dockerfile/Dockerfile.logic:
--------------------------------------------------------------------------------
1 | # build
2 | FROM golang:1.21 as builder
3 | ADD . $GOPATH/src/github.com/vearne/chat
4 | WORKDIR $GOPATH/src/github.com/vearne/chat/cmd/logic
5 |
6 | ARG BUILD_VERSION=""
7 | ARG BUILD_TIME=""
8 | ARG BUILD_COMMIT=""
9 | ARG IMPORT_PATH="github.com/vearne/chat"
10 |
11 | ENV CGO_ENABLED=0
12 | RUN go build -o /bin/chat-logic\
13 | -ldflags "-s -w -X ${IMPORT_PATH}/consts.GitTag=${BUILD_COMMIT} -X ${IMPORT_PATH}/consts.BuildTime=${BUILD_TIME} -X ${IMPORT_PATH}/consts.Version=${BUILD_VERSION}"
14 |
15 |
16 | FROM woshiaotian/simple-base-image:v0.1.6
17 |
18 | WORKDIR /data
19 | COPY --from=builder /bin/chat-logic /data/chat-logic
20 |
21 | CMD ["/data/chat-logic", "--config", "/data/config.logic.yaml"]
22 |
--------------------------------------------------------------------------------
/docs/command.md:
--------------------------------------------------------------------------------
1 | ## The protocol for interaction between the device and broker.
2 | websocket + JSON
3 |
4 |
5 | ```
6 | client broker
7 |
8 | # Request to create a temporary account
9 | CRT_ACCOUNT_REQ -->
10 | <-- CRT_ACCOUNT_RESP
11 | # Request to match a chat partner
12 | MATCH_REQ -->
13 | <-- MATCH_RESP
14 | # Send a conversation message
15 | DIALOGUE_REQ -->
16 | <-- DIALOGUE_RESP
17 |
18 | # Receive a conversation message
19 | <-- PUSH_DIALOGUE_REQ
20 | PUSH_DIALOGUE_RESP -->
21 |
22 | # Receive a system message (chat partner offline, etc.)
23 | <-- PUSH_SIGNAL_REQ
24 | PUSH_SIGNAL_RESP -->
25 |
26 | # Ping
27 | PING_REQ -->
28 | <-- PING_RESP
29 |
30 | # Inform the other party that the message has been read
31 | VIEWED_ACK_REQ -->
32 | <-- VIEWED_ACK_RESP
33 |
34 | # Receive notification that the message from the sender has been read by the recipient
35 | <-- PUSH_VIEWED_ACK_REQ
36 | PUSH_VIEWED_ACK_RESP -->
37 |
38 | # Attempt to reconnect after a sudden disconnection
39 | RECONNECT_REQ -->
40 | <-- RECONNECT_RESP
41 |
42 | ```
43 |
44 | ## Sequence diagram
45 | 
46 |
--------------------------------------------------------------------------------
/docs/command_zh.md:
--------------------------------------------------------------------------------
1 | # 设备与接入层交互协议
2 | websocket + 自定义协议(JSON)
3 |
4 |
5 | ```
6 | client broker
7 |
8 | # 请求创建一个临时账号
9 | CRT_ACCOUNT_REQ -->
10 | <-- CRT_ACCOUNT_RESP
11 | # 请求匹配一个聊天对象
12 | MATCH_REQ -->
13 | <-- MATCH_RESP
14 | # 发出一条对话消息
15 | DIALOGUE_REQ -->
16 | <-- DIALOGUE_RESP
17 |
18 | # 收到一条对话消息
19 | <-- PUSH_DIALOGUE_REQ
20 | PUSH_DIALOGUE_RESP -->
21 |
22 | # 收到一条系统消息(聊天对象下线等等)
23 | <-- PUSH_SIGNAL_REQ
24 | PUSH_SIGNAL_RESP -->
25 |
26 | # Ping
27 | PING_REQ -->
28 | <-- PING_RESP
29 |
30 | # 告知对方消息已经被已方阅读
31 | VIEWED_ACK_REQ -->
32 | <-- VIEWED_ACK_RESP
33 |
34 | # 收到已方消息已经被对方阅读
35 | <-- PUSH_VIEWED_ACK_REQ
36 | PUSH_VIEWED_ACK_RESP -->
37 |
38 | # 连接意外断开后,尝试重新连接
39 | RECONNECT_REQ -->
40 | <-- RECONNECT_RESP
41 |
42 | ```
43 |
44 | ## 时序图
45 | 
--------------------------------------------------------------------------------
/docs/deployment/chat-broker.service:
--------------------------------------------------------------------------------
1 | [Unit]
2 | Description=chat-broker
3 | Requires=network-online.target
4 | After=network-online.target
5 |
6 | [Service]
7 | User=root
8 | Group=root
9 | PermissionsStartOnly=true
10 | LimitNPROC=81920
11 | LimitNOFILE=81920
12 | WorkingDirectory=/opt/chat
13 | ExecStart=/opt/chat/chat broker --config ./config.broker.yaml
14 | KillMode=process
15 | KillSignal=SIGTERM
16 | Restart=on-failure
17 | RestartSec=500ms
18 | TimeoutStartSec=3s
19 | TimeoutStopSec=3s
20 | StandardError=syslog
21 | StandardOutput=syslog
22 | SyslogIdentifier=chat-broker
23 |
24 |
25 | [Install]
26 | WantedBy=multi-user.target
27 |
--------------------------------------------------------------------------------
/docs/deployment/chat-logic.service:
--------------------------------------------------------------------------------
1 | [Unit]
2 | Description=chat-logic
3 | Requires=network-online.target
4 | After=network-online.target
5 |
6 | [Service]
7 | User=root
8 | Group=root
9 | PermissionsStartOnly=true
10 | LimitNPROC=81920
11 | LimitNOFILE=81920
12 | WorkingDirectory=/opt/chat
13 | ExecStart=/opt/chat/chat logic --config ./config.logic.yaml
14 | KillMode=process
15 | KillSignal=SIGTERM
16 | Restart=on-failure
17 | RestartSec=500ms
18 | TimeoutStartSec=3s
19 | TimeoutStopSec=3s
20 | StandardError=syslog
21 | StandardOutput=syslog
22 | SyslogIdentifier=chat-logic
23 |
24 |
25 | [Install]
26 | WantedBy=multi-user.target
27 |
--------------------------------------------------------------------------------
/docs/mysql.md:
--------------------------------------------------------------------------------
1 | #### account
2 |
3 | |field|type|illustrate|detail|
4 | |:---|:---|:---|:---|
5 | |id|int|primary key||
6 | |nickname|string|nick name|nickname can be repeated|
7 | |status|int|status|0:created 1: in use 2: destroyed|
8 | |broker|string|broker that user is logged into|When delivering a message, it is required|
9 | |token|string|account unique identifier|Required when reconnecting|
10 | |created_at|date|create time||
11 | |modified_at|date|modify time||
12 |
13 | #### session
14 |
15 | |field|type|illustrate|detail|
16 | |:---|:---|:---|:---|
17 | |id|int|primary key||
18 | |status|int|status|0:created 1: in use 2: destroyed|
19 | |created_at|date|create time||
20 | |modified_at|date|modify time||
21 |
22 | #### session_account
23 |
24 | |field|type|illustrate|detail|
25 | |:---|:---|:---|:---|
26 | |id|int|primary key||
27 | |session_id|int|sender ID||
28 | |account_id|int|account ID||
29 |
30 |
31 | #### outbox
32 |
33 | |field|type|illustrate|detail|
34 | |:---|:---|:---|:---|
35 | |id|int|primary key||
36 | |sender_id|int|sender ID||
37 | |session_id|int|session ID||
38 | |status|int|status|0:deleted 1: normal|
39 | |msg_type|int|message type| 0: dialogue 1: signal|
40 | |content|string|content||
41 | |created_at|date|create time||
42 |
43 | #### inbox
44 |
45 | |field|type|illustrate|detail|
46 | |:---|:---|:---|:---|
47 | |id|int|primary key||
48 | |sender_id|int|sender ID||
49 | |msg_id|int|message ID||
50 | |receiver_id|int|receiver ID||
51 |
52 |
53 | #### view ack
54 | |field|type|illustrate|detail|
55 | |:---|:---|:---|:---|
56 | |id|int|primary key||
57 | |session_id|int|session ID||
58 | |account_id|int|account ID||
59 | |msg_id|int|message ID||
60 | |created_at|date|create time||
61 |
--------------------------------------------------------------------------------
/docs/mysql_zh.md:
--------------------------------------------------------------------------------
1 |
2 | #### 用户 account
3 | |字段|类型|说明|备注|
4 | |:---|:---|:---|:---|
5 | |id|int|主键||
6 | |nickname|string|昵称|可以重复|
7 | |status|int|状态|0:创建 1:使用中 2:销毁|
8 | |broker|string|用户登录的broker信息|消息投递时,需要|
9 | |token|string|用户唯一性标识|重连时需要|
10 | |created_at|date|创建时间||
11 | |modified_at|date|更新时间||
12 |
13 |
14 | #### 会话 session
15 | |字段|类型|说明|备注|
16 | |:---|:---|:---|:---|
17 | |id|int|会话ID||
18 | |status|int|状态|0:创建 1:使用中 2:销毁|
19 | |created_at|date|创建时间||
20 | |modified_at|date|更新时间||
21 |
22 | #### session_account
23 | |字段|类型|说明|备注|
24 | |:---|:---|:---|:---|
25 | |id|int|主键||
26 | |session_id|int|会话ID||
27 | |account_id|int|账号ID||
28 |
29 |
30 | #### 发件箱 outbox
31 | |字段|类型|说明|备注|
32 | |:---|:---|:---|:---|
33 | |id|int|主键||
34 | |sender_id|int|发出者ID||
35 | |session_id|int|会话ID||
36 | |status|int|状态|0:删除 1: 正常|
37 | |msg_type|int|类型| 0: dialogue 1: signal|
38 | |content|string|内容||
39 | |created_at|date|创建时间||
40 |
41 | #### 收件箱 inbox
42 | |字段|类型|说明|备注|
43 | |:---|:---|:---|:---|
44 | |id|int|主键||
45 | |sender_id|int|发出者ID||
46 | |msg_id|int|消息ID||
47 | |receiver_id|int|接收者ID||
48 |
49 |
50 | #### view ack
51 | |字段|类型|说明|备注|
52 | |:---|:---|:---|:---|
53 | |id|int|主键||
54 | |session_id|int|会话ID||
55 | |account_id|int|账号ID||
56 | |msg_id|int|消息ID||
57 | |created_at|date|创建时间||
58 |
--------------------------------------------------------------------------------
/docs/schema.sql:
--------------------------------------------------------------------------------
1 |
2 | -- 2019-11-18
3 | CREATE TABLE `account` (
4 | `id` bigint unsigned NOT NULL AUTO_INCREMENT,
5 | `nickname` varchar(30) DEFAULT NULL,
6 | `status` int(11) DEFAULT NULL,
7 | `broker` varchar(255) DEFAULT NULL,
8 | `created_at` timestamp NULL DEFAULT NULL,
9 | `modified_at` timestamp NULL DEFAULT NULL,
10 | PRIMARY KEY (`id`)
11 | ) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;
12 |
13 | CREATE TABLE `session` (
14 | `id` bigint unsigned NOT NULL AUTO_INCREMENT,
15 | `status` int(11) DEFAULT NULL,
16 | `created_at` timestamp NULL DEFAULT NULL,
17 | `modified_at` timestamp NULL DEFAULT NULL,
18 | PRIMARY KEY (`id`)
19 | ) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;
20 |
21 |
22 | CREATE TABLE `session_account` (
23 | `id` bigint unsigned NOT NULL AUTO_INCREMENT,
24 | `session_id` bigint unsigned DEFAULT NULL,
25 | `account_id` bigint unsigned DEFAULT NULL,
26 | PRIMARY KEY (`id`)
27 | ) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;
28 |
29 | ALTER TABLE session_account ADD index idx_session (`session_id`);
30 |
31 | CREATE TABLE `outbox` (
32 | `id` bigint unsigned NOT NULL AUTO_INCREMENT,
33 | `sender_id` bigint unsigned DEFAULT NULL,
34 | `session_id` bigint unsigned DEFAULT NULL,
35 | `status` int(11) DEFAULT NULL,
36 | `msg_type` int(11) DEFAULT NULL,
37 | `content` varchar(255) DEFAULT NULL,
38 | `created_at` timestamp NULL DEFAULT NULL,
39 | `modified_at` timestamp NULL DEFAULT NULL,
40 | PRIMARY KEY (`id`)
41 | ) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;
42 |
43 | ALTER TABLE outbox ADD index idx_sender (`sender_id`);
44 |
45 | CREATE TABLE `inbox` (
46 | `id` bigint unsigned NOT NULL AUTO_INCREMENT,
47 | `sender_id` bigint unsigned DEFAULT NULL,
48 | `msg_id` bigint unsigned DEFAULT NULL,
49 | `receiver_id` bigint unsigned DEFAULT NULL,
50 | PRIMARY KEY (`id`)
51 | ) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;
52 |
53 | ALTER TABLE inbox ADD index idx_receiver (`receiver_id`);
54 |
55 | -- 2019-12-13
56 | CREATE TABLE `view_ack` (
57 | `id` bigint unsigned NOT NULL AUTO_INCREMENT,
58 | `session_id` bigint unsigned DEFAULT NULL,
59 | `account_id` bigint unsigned DEFAULT NULL,
60 | `msg_id` bigint unsigned DEFAULT NULL,
61 | `created_at` timestamp NULL DEFAULT NULL,
62 | PRIMARY KEY (`id`)
63 | ) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;
64 |
65 | ALTER TABLE view_ack ADD unique idx_view_ack (`session_id`, `account_id`);
66 |
67 | -- 2021-08-09
68 | ALTER TABLE account ADD column `token` varchar(50) DEFAULT '';
69 |
70 | -- 2021-08-11
71 | ALTER TABLE account modify `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP;
72 | ALTER TABLE account modify `modified_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/vearne/chat
2 |
3 | go 1.23.6
4 |
5 | require (
6 | github.com/fatih/color v1.18.0
7 | github.com/gin-gonic/gin v1.10.0
8 | github.com/golang/protobuf v1.5.4
9 | github.com/google/uuid v1.6.0
10 | github.com/grpc-ecosystem/go-grpc-middleware v1.4.0
11 | github.com/json-iterator/go v1.1.12
12 | github.com/spf13/viper v1.20.0
13 | github.com/vearne/worker_manager v0.1.0
14 | go.etcd.io/etcd/client/v3 v3.5.19
15 | go.uber.org/zap v1.27.0
16 | golang.org/x/time v0.11.0
17 | google.golang.org/grpc v1.71.0
18 | gopkg.in/natefinch/lumberjack.v2 v2.2.1
19 | gopkg.in/olahol/melody.v1 v1.0.0-20170518105555-d52139073376
20 | gorm.io/driver/mysql v1.5.7
21 | gorm.io/gorm v1.25.12
22 | )
23 |
24 | require (
25 | github.com/bytedance/sonic v1.11.6 // indirect
26 | github.com/bytedance/sonic/loader v0.1.1 // indirect
27 | github.com/cloudwego/base64x v0.1.4 // indirect
28 | github.com/cloudwego/iasm v0.2.0 // indirect
29 | github.com/coreos/go-semver v0.3.0 // indirect
30 | github.com/coreos/go-systemd/v22 v22.3.2 // indirect
31 | github.com/fsnotify/fsnotify v1.8.0 // indirect
32 | github.com/gabriel-vasile/mimetype v1.4.3 // indirect
33 | github.com/gin-contrib/sse v0.1.0 // indirect
34 | github.com/go-playground/locales v0.14.1 // indirect
35 | github.com/go-playground/universal-translator v0.18.1 // indirect
36 | github.com/go-playground/validator/v10 v10.20.0 // indirect
37 | github.com/go-sql-driver/mysql v1.7.0 // indirect
38 | github.com/go-viper/mapstructure/v2 v2.2.1 // indirect
39 | github.com/goccy/go-json v0.10.2 // indirect
40 | github.com/gogo/protobuf v1.3.2 // indirect
41 | github.com/gorilla/websocket v1.5.3 // indirect
42 | github.com/jinzhu/inflection v1.0.0 // indirect
43 | github.com/jinzhu/now v1.1.5 // indirect
44 | github.com/klauspost/cpuid/v2 v2.2.7 // indirect
45 | github.com/leodido/go-urn v1.4.0 // indirect
46 | github.com/mattn/go-colorable v0.1.13 // indirect
47 | github.com/mattn/go-isatty v0.0.20 // indirect
48 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
49 | github.com/modern-go/reflect2 v1.0.2 // indirect
50 | github.com/pelletier/go-toml/v2 v2.2.3 // indirect
51 | github.com/sagikazarmark/locafero v0.7.0 // indirect
52 | github.com/sourcegraph/conc v0.3.0 // indirect
53 | github.com/spf13/afero v1.12.0 // indirect
54 | github.com/spf13/cast v1.7.1 // indirect
55 | github.com/spf13/pflag v1.0.6 // indirect
56 | github.com/subosito/gotenv v1.6.0 // indirect
57 | github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
58 | github.com/ugorji/go/codec v1.2.12 // indirect
59 | github.com/vearne/simplelog v0.0.2 // indirect
60 | go.etcd.io/etcd/api/v3 v3.5.19 // indirect
61 | go.etcd.io/etcd/client/pkg/v3 v3.5.19 // indirect
62 | go.uber.org/multierr v1.10.0 // indirect
63 | golang.org/x/arch v0.8.0 // indirect
64 | golang.org/x/crypto v0.36.0 // indirect
65 | golang.org/x/net v0.38.0 // indirect
66 | golang.org/x/sys v0.31.0 // indirect
67 | golang.org/x/text v0.23.0 // indirect
68 | google.golang.org/genproto/googleapis/api v0.0.0-20250106144421-5f5ef82da422 // indirect
69 | google.golang.org/genproto/googleapis/rpc v0.0.0-20250115164207-1a7da9e5054f // indirect
70 | google.golang.org/protobuf v1.36.4 // indirect
71 | gopkg.in/yaml.v3 v3.0.1 // indirect
72 | )
73 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
2 | github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
3 | github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA=
4 | github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc0=
5 | github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4=
6 | github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM=
7 | github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=
8 | github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
9 | github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
10 | github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y=
11 | github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w=
12 | github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg=
13 | github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY=
14 | github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc=
15 | github.com/coreos/go-semver v0.3.0 h1:wkHLiw0WNATZnSG7epLsujiMCgPAc9xhjJ4tgnAxmfM=
16 | github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk=
17 | github.com/coreos/go-systemd/v22 v22.3.2 h1:D9/bQk5vlXQFZ6Kwuu6zaiXJ9oTPe68++AzAJc1DzSI=
18 | github.com/coreos/go-systemd/v22 v22.3.2/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
19 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
20 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
21 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
22 | github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
23 | github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
24 | github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=
25 | github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
26 | github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM=
27 | github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU=
28 | github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
29 | github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
30 | github.com/fsnotify/fsnotify v1.8.0 h1:dAwr6QBTBZIkG8roQaJjGof0pp0EeF+tNV7YBP3F/8M=
31 | github.com/fsnotify/fsnotify v1.8.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
32 | github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0=
33 | github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk=
34 | github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
35 | github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
36 | github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU=
37 | github.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y=
38 | github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vbaY=
39 | github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A=
40 | github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY=
41 | github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
42 | github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
43 | github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
44 | github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
45 | github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
46 | github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
47 | github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
48 | github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
49 | github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
50 | github.com/go-playground/validator/v10 v10.20.0 h1:K9ISHbSaI0lyB2eWMPJo+kOS/FBExVwjEviJTixqxL8=
51 | github.com/go-playground/validator/v10 v10.20.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
52 | github.com/go-sql-driver/mysql v1.7.0 h1:ueSltNNllEqE3qcWBTD0iQd3IpL/6U+mJxLkazJ7YPc=
53 | github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI=
54 | github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
55 | github.com/go-viper/mapstructure/v2 v2.2.1 h1:ZAaOCxANMuZx5RCeg0mBdEZk7DZasvvZIxtHqx8aGss=
56 | github.com/go-viper/mapstructure/v2 v2.2.1/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
57 | github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
58 | github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
59 | github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
60 | github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
61 | github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
62 | github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
63 | github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
64 | github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
65 | github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
66 | github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw=
67 | github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
68 | github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
69 | github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
70 | github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
71 | github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
72 | github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
73 | github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
74 | github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
75 | github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
76 | github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
77 | github.com/grpc-ecosystem/go-grpc-middleware v1.4.0 h1:UH//fgunKIs4JdUbpDl1VZCDaL56wXCB/5+wF6uHfaI=
78 | github.com/grpc-ecosystem/go-grpc-middleware v1.4.0/go.mod h1:g5qyo/la0ALbONm6Vbp88Yd8NsDy6rZz+RcrMPxvld8=
79 | github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
80 | github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
81 | github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
82 | github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
83 | github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
84 | github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
85 | github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
86 | github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
87 | github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
88 | github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM=
89 | github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
90 | github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=
91 | github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
92 | github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
93 | github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
94 | github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
95 | github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
96 | github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
97 | github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
98 | github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
99 | github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
100 | github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
101 | github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
102 | github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
103 | github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
104 | github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
105 | github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
106 | github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
107 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
108 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
109 | github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
110 | github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
111 | github.com/opentracing/opentracing-go v1.1.0/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o=
112 | github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M=
113 | github.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc=
114 | github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
115 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
116 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
117 | github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
118 | github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
119 | github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
120 | github.com/sagikazarmark/locafero v0.7.0 h1:5MqpDsTGNDhY8sGp0Aowyf0qKsPrhewaLSsFaodPcyo=
121 | github.com/sagikazarmark/locafero v0.7.0/go.mod h1:2za3Cg5rMaTMoG/2Ulr9AwtFaIppKXTRYnozin4aB5k=
122 | github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
123 | github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo=
124 | github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0=
125 | github.com/spf13/afero v1.12.0 h1:UcOPyRBYczmFn6yvphxkn9ZEOY65cpwGKb5mL36mrqs=
126 | github.com/spf13/afero v1.12.0/go.mod h1:ZTlWwG4/ahT8W7T0WQ5uYmjI9duaLQGy3Q2OAl4sk/4=
127 | github.com/spf13/cast v1.7.1 h1:cuNEagBQEHWN1FnbGEjCXL2szYEXqfJPbP2HNUaca9Y=
128 | github.com/spf13/cast v1.7.1/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo=
129 | github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o=
130 | github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
131 | github.com/spf13/viper v1.20.0 h1:zrxIyR3RQIOsarIrgL8+sAvALXul9jeEPa06Y0Ph6vY=
132 | github.com/spf13/viper v1.20.0/go.mod h1:P9Mdzt1zoHIG8m2eZQinpiBjo6kCmZSKBClNNqjJvu4=
133 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
134 | github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
135 | github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
136 | github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
137 | github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
138 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
139 | github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
140 | github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
141 | github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
142 | github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
143 | github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
144 | github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
145 | github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
146 | github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
147 | github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
148 | github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
149 | github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
150 | github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=
151 | github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
152 | github.com/vearne/simplelog v0.0.2 h1:SOd9ksyniEABwiqkLDpoGvxDcE0TSjW+3ExO4BpxONk=
153 | github.com/vearne/simplelog v0.0.2/go.mod h1:W7Ip7PHWs8c0X+7b8hSj9zH7WxKB3oQ1pkr3tAtxqSo=
154 | github.com/vearne/worker_manager v0.1.0 h1:EtOql50CROIC+szWtsrsNa1KkNypeJBZCWL9rC3D9j4=
155 | github.com/vearne/worker_manager v0.1.0/go.mod h1:PJUvadZxnBjNo5FcZ1d1iDvyjpFTHAcuYMxErGhpyrI=
156 | github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
157 | github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
158 | go.etcd.io/etcd/api/v3 v3.5.19 h1:w3L6sQZGsWPuBxRQ4m6pPP3bVUtV8rjW033EGwlr0jw=
159 | go.etcd.io/etcd/api/v3 v3.5.19/go.mod h1:QqKGViq4KTgOG43dr/uH0vmGWIaoJY3ggFi6ZH0TH/U=
160 | go.etcd.io/etcd/client/pkg/v3 v3.5.19 h1:9VsyGhg0WQGjDWWlDI4VuaS9PZJGNbPkaHEIuLwtixk=
161 | go.etcd.io/etcd/client/pkg/v3 v3.5.19/go.mod h1:qaOi1k4ZA9lVLejXNvyPABrVEe7VymMF2433yyRQ7O0=
162 | go.etcd.io/etcd/client/v3 v3.5.19 h1:+4byIz6ti3QC28W0zB0cEZWwhpVHXdrKovyycJh1KNo=
163 | go.etcd.io/etcd/client/v3 v3.5.19/go.mod h1:FNzyinmMIl0oVsty1zA3hFeUrxXI/JpEnz4sG+POzjU=
164 | go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA=
165 | go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A=
166 | go.opentelemetry.io/otel v1.34.0 h1:zRLXxLCgL1WyKsPVrgbSdMN4c0FMkDAskSTQP+0hdUY=
167 | go.opentelemetry.io/otel v1.34.0/go.mod h1:OWFPOQ+h4G8xpyjgqo4SxJYdDQ/qmRH+wivy7zzx9oI=
168 | go.opentelemetry.io/otel/metric v1.34.0 h1:+eTR3U0MyfWjRDhmFMxe2SsW64QrZ84AOhvqS7Y+PoQ=
169 | go.opentelemetry.io/otel/metric v1.34.0/go.mod h1:CEDrp0fy2D0MvkXE+dPV7cMi8tWZwX3dmaIhwPOaqHE=
170 | go.opentelemetry.io/otel/sdk v1.34.0 h1:95zS4k/2GOy069d321O8jWgYsW3MzVV+KuSPKp7Wr1A=
171 | go.opentelemetry.io/otel/sdk v1.34.0/go.mod h1:0e/pNiaMAqaykJGKbi+tSjWfNNHMTxoC9qANsCzbyxU=
172 | go.opentelemetry.io/otel/sdk/metric v1.34.0 h1:5CeK9ujjbFVL5c1PhLuStg1wxA7vQv7ce1EK0Gyvahk=
173 | go.opentelemetry.io/otel/sdk/metric v1.34.0/go.mod h1:jQ/r8Ze28zRKoNRdkjCZxfs6YvBTG1+YIqyFVFYec5w=
174 | go.opentelemetry.io/otel/trace v1.34.0 h1:+ouXS2V8Rd4hp4580a8q23bg0azF2nI8cqLYnC8mh/k=
175 | go.opentelemetry.io/otel/trace v1.34.0/go.mod h1:Svm7lSjQD7kG7KJ/MUHPVXSDGz2OX4h0M2jHBhmSfRE=
176 | go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
177 | go.uber.org/goleak v1.1.10/go.mod h1:8a7PlsEVH3e/a/GLqe5IIrQx6GzcnRmZEufDUTk4A7A=
178 | go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
179 | go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
180 | go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU=
181 | go.uber.org/multierr v1.10.0 h1:S0h4aNzvfcFsC3dRF1jLoaov7oRaKqRGC/pUEJ2yvPQ=
182 | go.uber.org/multierr v1.10.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
183 | go.uber.org/zap v1.18.1/go.mod h1:xg/QME4nWcxGxrpdeYfq7UvYrLh66cuVKdrbD1XF/NI=
184 | go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8=
185 | go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
186 | golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
187 | golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc=
188 | golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=
189 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
190 | golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
191 | golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
192 | golang.org/x/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34=
193 | golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc=
194 | golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
195 | golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
196 | golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
197 | golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
198 | golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
199 | golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
200 | golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
201 | golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
202 | golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
203 | golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
204 | golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
205 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
206 | golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
207 | golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
208 | golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
209 | golang.org/x/net v0.38.0 h1:vRMAPTMaeGqVhG5QyLJHqNDwecKTomGeqbnfZyKlBI8=
210 | golang.org/x/net v0.38.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8=
211 | golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
212 | golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
213 | golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
214 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
215 | golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
216 | golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
217 | golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
218 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
219 | golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
220 | golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
221 | golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
222 | golang.org/x/sys v0.0.0-20211025201205-69cdffdb9359/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
223 | golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
224 | golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
225 | golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
226 | golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik=
227 | golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
228 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
229 | golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
230 | golang.org/x/text v0.23.0 h1:D71I7dUrlY+VX0gQShAThNGHFxZ13dGLBHQLVl1mJlY=
231 | golang.org/x/text v0.23.0/go.mod h1:/BLNzu4aZCJ1+kcD0DNRotWKage4q2rGVAg4o22unh4=
232 | golang.org/x/time v0.11.0 h1:/bpjEDfN9tkoN/ryeYHnv5hcMlc8ncjMcM4XBk5NWV0=
233 | golang.org/x/time v0.11.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg=
234 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
235 | golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
236 | golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
237 | golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
238 | golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
239 | golang.org/x/tools v0.0.0-20191108193012-7d206e10da11/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
240 | golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
241 | golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
242 | golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
243 | golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
244 | golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
245 | golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
246 | golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
247 | google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
248 | google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
249 | google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
250 | google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
251 | google.golang.org/genproto v0.0.0-20200423170343-7949de9c1215/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c=
252 | google.golang.org/genproto/googleapis/api v0.0.0-20250106144421-5f5ef82da422 h1:GVIKPyP/kLIyVOgOnTwFOrvQaQUzOzGMCxgFUOEmm24=
253 | google.golang.org/genproto/googleapis/api v0.0.0-20250106144421-5f5ef82da422/go.mod h1:b6h1vNKhxaSoEI+5jc3PJUCustfli/mRab7295pY7rw=
254 | google.golang.org/genproto/googleapis/rpc v0.0.0-20250115164207-1a7da9e5054f h1:OxYkA3wjPsZyBylwymxSHa7ViiW1Sml4ToBrncvFehI=
255 | google.golang.org/genproto/googleapis/rpc v0.0.0-20250115164207-1a7da9e5054f/go.mod h1:+2Yz8+CLJbIfL9z73EW45avw8Lmge3xVElCP9zEKi50=
256 | google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
257 | google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg=
258 | google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY=
259 | google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk=
260 | google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk=
261 | google.golang.org/grpc v1.71.0 h1:kF77BGdPTQ4/JZWMlb9VpJ5pa25aqvVqogsxNHHdeBg=
262 | google.golang.org/grpc v1.71.0/go.mod h1:H0GRtasmQOh9LkFoCPDu3ZrwUtD1YGE+b2vYBYd/8Ec=
263 | google.golang.org/protobuf v1.36.4 h1:6A3ZDJHn/eNqc1i+IdefRzy/9PokBTPvcqMySR7NNIM=
264 | google.golang.org/protobuf v1.36.4/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE=
265 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
266 | gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
267 | gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
268 | gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
269 | gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc=
270 | gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc=
271 | gopkg.in/olahol/melody.v1 v1.0.0-20170518105555-d52139073376 h1:sY2a+y0j4iDrajJcorb+a0hJIQ6uakU5gybjfLWHlXo=
272 | gopkg.in/olahol/melody.v1 v1.0.0-20170518105555-d52139073376/go.mod h1:BHKOc1m5wm8WwQkMqYBoo4vNxhmF7xg8+xhG8L+Cy3M=
273 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
274 | gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
275 | gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
276 | gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
277 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
278 | gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
279 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
280 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
281 | gorm.io/driver/mysql v1.5.7 h1:MndhOPYOfEp2rHKgkZIhJ16eVUIRf2HmzgoPmh7FCWo=
282 | gorm.io/driver/mysql v1.5.7/go.mod h1:sEtPWMiqiN1N1cMXoXmBbd8C6/l+TESwriotuRRpkDM=
283 | gorm.io/gorm v1.25.7/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=
284 | gorm.io/gorm v1.25.12 h1:I0u8i2hWQItBq1WfE0o2+WuL9+8L21K9e2HHSTE/0f8=
285 | gorm.io/gorm v1.25.12/go.mod h1:xh7N7RHfYlNc5EmcI/El95gXusucDrQnHXe0+CgWcLQ=
286 | honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
287 | honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
288 | nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=
289 | rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=
290 |
--------------------------------------------------------------------------------
/img/arch.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vearne/chat/7204c6d4860c3c1be70d6bd8e43e4b6b4e3019c9/img/arch.png
--------------------------------------------------------------------------------
/img/arch2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vearne/chat/7204c6d4860c3c1be70d6bd8e43e4b6b4e3019c9/img/arch2.png
--------------------------------------------------------------------------------
/img/chat_window.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vearne/chat/7204c6d4860c3c1be70d6bd8e43e4b6b4e3019c9/img/chat_window.jpg
--------------------------------------------------------------------------------
/img/jetbrains.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
67 |
--------------------------------------------------------------------------------
/img/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vearne/chat/7204c6d4860c3c1be70d6bd8e43e4b6b4e3019c9/img/logo.png
--------------------------------------------------------------------------------
/img/seq.jpeg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vearne/chat/7204c6d4860c3c1be70d6bd8e43e4b6b4e3019c9/img/seq.jpeg
--------------------------------------------------------------------------------
/internal/biz/reg.go:
--------------------------------------------------------------------------------
1 | package biz
2 |
3 | import (
4 | "context"
5 | "encoding/json"
6 | "github.com/google/uuid"
7 | zlog "github.com/vearne/chat/internal/log"
8 | clientv3 "go.etcd.io/etcd/client/v3"
9 | "go.etcd.io/etcd/client/v3/naming/endpoints"
10 | "go.uber.org/zap"
11 | "path"
12 | "time"
13 | )
14 |
15 | // ServiceRegister 创建租约注册服务
16 | type ServiceRegister struct {
17 | cli *clientv3.Client //etcd client
18 | leaseID clientv3.LeaseID //租约ID
19 | //租约keepalieve相应chan
20 | keepAliveChan <-chan *clientv3.LeaseKeepAliveResponse
21 | key string //key
22 | val string //value
23 | }
24 |
25 | // NewServiceRegister 新建注册服务
26 | func NewServiceRegister(
27 | etcdServers []string,
28 | username, password string,
29 | prefix, addr string,
30 | ) (*ServiceRegister, error) {
31 | cli, err := clientv3.New(clientv3.Config{
32 | Username: username,
33 | Password: password,
34 | Endpoints: etcdServers,
35 | DialTimeout: 5 * time.Second,
36 | })
37 | if err != nil {
38 | zlog.Fatal("NewServiceRegister", zap.Error(err))
39 | }
40 |
41 | buff, _ := json.Marshal(endpoints.Endpoint{Addr: addr})
42 | key := path.Join(prefix, uuid.NewString())
43 | zlog.Info("register service", zap.String("key", key), zap.String("val", string(buff)))
44 | ser := &ServiceRegister{
45 | cli: cli,
46 | key: key,
47 | val: string(buff),
48 | }
49 |
50 | //申请租约设置时间keepalive
51 | // 5 seconds
52 | var lease int64 = 5
53 | if err := ser.putKeyWithLease(lease); err != nil {
54 | return nil, err
55 | }
56 |
57 | return ser, nil
58 | }
59 |
60 | // 设置租约
61 | func (s *ServiceRegister) putKeyWithLease(lease int64) error {
62 | //设置租约时间
63 | resp, err := s.cli.Grant(context.Background(), lease)
64 | if err != nil {
65 | return err
66 | }
67 | //注册服务并绑定租约
68 | _, err = s.cli.Put(context.Background(), s.key, s.val, clientv3.WithLease(resp.ID))
69 | if err != nil {
70 | return err
71 | }
72 | //设置续租 定期发送需求请求
73 | leaseRespChan, err := s.cli.KeepAlive(context.Background(), resp.ID)
74 | if err != nil {
75 | return err
76 | }
77 | s.leaseID = resp.ID
78 | zlog.Debug("putKeyWithLease", zap.Int64("leaseID", int64(s.leaseID)))
79 | s.keepAliveChan = leaseRespChan
80 | return nil
81 | }
82 |
83 | // ListenLeaseRespChan 监听 续租情况
84 | func (s *ServiceRegister) ListenLeaseRespChan() {
85 | for leaseKeepResp := range s.keepAliveChan {
86 | zlog.Debug("lease renew successful", zap.Any("leaseKeepResp", leaseKeepResp))
87 | }
88 | }
89 |
90 | // Close 注销服务
91 | func (s *ServiceRegister) Close() error {
92 | if _, err := s.cli.Revoke(context.Background(), s.leaseID); err != nil {
93 | return err
94 | }
95 | zlog.Info("cancel lease")
96 | return s.cli.Close()
97 | }
98 |
--------------------------------------------------------------------------------
/internal/biz/session.go:
--------------------------------------------------------------------------------
1 | package biz
2 |
3 | import (
4 | "github.com/vearne/chat/consts"
5 | "github.com/vearne/chat/internal/resource"
6 | "github.com/vearne/chat/model"
7 | "time"
8 | )
9 |
10 | func CreateSession(partner1, partner2 uint64) (*model.Session, error) {
11 | var session model.Session
12 | var err error
13 | session.Status = consts.SessionStatusInUse
14 | session.CreatedAt = time.Now()
15 | session.ModifiedAt = session.CreatedAt
16 | err = resource.MySQLClient.Create(&session).Error
17 | if err != nil {
18 | return nil, err
19 | }
20 | // 2. 创建会话中的对象 session-account
21 | s1 := model.SessionAccount{SessionId: session.ID, AccountId: partner1}
22 | err = resource.MySQLClient.Create(&s1).Error
23 | if err != nil {
24 | return nil, err
25 | }
26 | s2 := model.SessionAccount{SessionId: session.ID, AccountId: partner2}
27 | err = resource.MySQLClient.Create(&s2).Error
28 | if err != nil {
29 | return nil, err
30 | }
31 | return &session, nil
32 | }
33 |
--------------------------------------------------------------------------------
/internal/config/base.go:
--------------------------------------------------------------------------------
1 | package config
2 |
3 | import (
4 | "fmt"
5 | "github.com/spf13/viper"
6 | "log"
7 | "sync"
8 | "sync/atomic"
9 | )
10 |
11 | var initOnce sync.Once
12 | var gcf atomic.Value
13 |
14 | type LogConfig struct {
15 | Level string `mapstructure:"level"`
16 | FilePath string `mapstructure:"filepath"`
17 | }
18 |
19 | type MySQLConf struct {
20 | DSN string `mapstructure:"dsn"`
21 | MaxIdleConn int `mapstructure:"max_idle_conn"`
22 | MaxOpenConn int `mapstructure:"max_open_conn"`
23 | ConnMaxLifeSecs int `mapstructure:"conn_max_life_secs"`
24 | // 是否启动debug模式
25 | // 若开启则会打印具体的执行SQL
26 | Debug bool `mapstructure:"debug"`
27 | }
28 |
29 | func ReadConfig(role string, cfgFile string) {
30 | if cfgFile != "" {
31 | // Use config file from the flag.
32 | viper.SetConfigFile(cfgFile)
33 |
34 | } else {
35 | viper.AddConfigPath("config_files")
36 | fname := fmt.Sprintf("config.%s", role)
37 | viper.SetConfigName(fname)
38 | }
39 |
40 | viper.AutomaticEnv() // read in environment variables that match
41 |
42 | // If a config file is found, read it in.
43 | if err := viper.ReadInConfig(); err == nil {
44 | log.Println("Using config file:", viper.ConfigFileUsed())
45 | } else {
46 | log.Println("can't find config file", err)
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/internal/config/broker.go:
--------------------------------------------------------------------------------
1 | package config
2 |
3 | import (
4 | "github.com/spf13/viper"
5 | "github.com/vearne/chat/internal/utils"
6 | "log"
7 | "time"
8 | )
9 |
10 | type BrokerConfig struct {
11 | Logger LogConfig `mapstructure:"logger"`
12 |
13 | LogicDealer struct {
14 | Address string `mapstructure:"address"`
15 | } `mapstructure:"logic_dealer"`
16 |
17 | Broker struct {
18 | WebSocketAddress string `mapstructure:"ws_address"`
19 | GrpcAddress string `mapstructure:"grpc_address"`
20 | } `mapstructure:"broker"`
21 |
22 | Ping struct {
23 | Interval time.Duration `mapstructure:"interval"`
24 | MaxWait time.Duration `mapstructure:"maxWait"`
25 | } `mapstructure:"ping"`
26 |
27 | BrokerGrpcAddr string
28 |
29 | ServiceDebug bool `mapstructure:"service-debug"`
30 | }
31 |
32 | func InitBrokerConfig() {
33 | log.Println("---InitBrokerConfig---")
34 | initOnce.Do(func() {
35 | var cf = BrokerConfig{}
36 | err := viper.Unmarshal(&cf)
37 | if err != nil {
38 | log.Fatalf("InitBrokerConfig:%v \n", err)
39 | }
40 | // Grpc地址
41 | ip, _ := utils.GetIP()
42 | cf.BrokerGrpcAddr = ip + cf.Broker.GrpcAddress
43 | gcf.Store(&cf)
44 | })
45 | }
46 |
47 | func GetBrokerOpts() *BrokerConfig {
48 | return gcf.Load().(*BrokerConfig)
49 | }
50 |
--------------------------------------------------------------------------------
/internal/config/logic.go:
--------------------------------------------------------------------------------
1 | package config
2 |
3 | import (
4 | "github.com/spf13/viper"
5 | "log"
6 | )
7 |
8 | type LogicConfig struct {
9 | Logger LogConfig `mapstructure:"logger"`
10 |
11 | LogicDealer struct {
12 | ListenAddress string `mapstructure:"listen_address"`
13 | } `mapstructure:"logic_dealer"`
14 |
15 | MySQLConf MySQLConf `mapstructure:"mysql"`
16 |
17 | Ectd struct {
18 | Register bool `mapstructure:"register"`
19 | Endpoints []string `mapstructure:"endpoints"`
20 | Username string `mapstructure:"username"`
21 | Password string `mapstructure:"password"`
22 | } `mapstructure:"etcd"`
23 |
24 | ServiceDebug bool `mapstructure:"service-debug"`
25 | }
26 |
27 | func InitLogicConfig() {
28 | log.Println("---InitLogicConfig---")
29 | initOnce.Do(func() {
30 | var cf = LogicConfig{}
31 | err := viper.Unmarshal(&cf)
32 | if err != nil {
33 | log.Fatalf("InitLogicConfig:%v \n", err)
34 | }
35 | gcf.Store(&cf)
36 | })
37 | }
38 |
39 | func GetLogicOpts() *LogicConfig {
40 | return gcf.Load().(*LogicConfig)
41 | }
42 |
--------------------------------------------------------------------------------
/internal/dao/account.go:
--------------------------------------------------------------------------------
1 | package dao
2 |
3 | import (
4 | "github.com/vearne/chat/consts"
5 | "github.com/vearne/chat/internal/resource"
6 | "github.com/vearne/chat/model"
7 | pb "github.com/vearne/chat/proto"
8 | "time"
9 | )
10 |
11 | func GetAccount(accountId uint64) (*model.Account, error) {
12 | var account model.Account
13 | err := resource.MySQLClient.Where("id = ?", accountId).First(&account).Error
14 | if err != nil {
15 | return nil, err
16 | }
17 | return &account, nil
18 | }
19 |
20 | func GetSession(sessionId uint64) (*model.Session, error) {
21 | var session model.Session
22 | err := resource.MySQLClient.Where("id = ?", sessionId).First(&session).Error
23 | if err != nil {
24 | return nil, err
25 | }
26 | return &session, nil
27 | }
28 |
29 | func GetSessionPartner(sessionId uint64, accountId uint64) (*model.SessionAccount, error) {
30 | var partner model.SessionAccount
31 | err := resource.MySQLClient.Where("session_id = ? and account_id != ?",
32 | sessionId, accountId).First(&partner).Error
33 | if err != nil {
34 | return nil, err
35 | }
36 | return &partner, nil
37 | }
38 |
39 | func CreateOutMsg(msgType pb.MsgTypeEnum, senderId, sessionId uint64, content string) (*model.OutBox, error) {
40 | outMsg := model.OutBox{SenderId: senderId, SessionId: sessionId}
41 | outMsg.Status = consts.OutBoxStatusNormal
42 | outMsg.MsgType = int(msgType)
43 | outMsg.Content = content
44 | outMsg.CreatedAt = time.Now()
45 | outMsg.ModifiedAt = outMsg.CreatedAt
46 |
47 | err := resource.MySQLClient.Create(&outMsg).Error
48 | if err != nil {
49 | return nil, err
50 | }
51 | return &outMsg, nil
52 | }
53 |
54 | func CreateInMsg(senderId, msgId, receiverId uint64) (*model.InBox, error) {
55 | inMsg := model.InBox{}
56 | inMsg.SenderId = senderId
57 | inMsg.MsgId = msgId
58 | inMsg.ReceiverId = receiverId
59 |
60 | err := resource.MySQLClient.Create(&inMsg).Error
61 | if err != nil {
62 | return nil, err
63 | }
64 | return &inMsg, nil
65 | }
66 |
--------------------------------------------------------------------------------
/internal/dao/view_ack.go:
--------------------------------------------------------------------------------
1 | package dao
2 |
3 | import (
4 | "github.com/vearne/chat/internal/resource"
5 | "time"
6 | )
7 |
8 | func CreatOrUpdateViewedAck(sessionId uint64, accountId uint64, msgId uint64) error {
9 | sql := "INSERT INTO `view_ack` (`session_id`, `account_id`, `msg_id`, `created_at`) "
10 | sql += "VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE msg_id = ?, created_at = ?; "
11 | err := resource.MySQLClient.Exec(sql, sessionId, accountId, msgId, time.Now(), msgId, time.Now()).Error
12 | if err != nil {
13 | return err
14 | }
15 | return nil
16 | }
17 |
--------------------------------------------------------------------------------
/internal/engine/broker/grpc_worker.go:
--------------------------------------------------------------------------------
1 | package broker
2 |
3 | import (
4 | "context"
5 | "github.com/vearne/chat/internal/config"
6 | zlog "github.com/vearne/chat/internal/log"
7 | "github.com/vearne/chat/internal/resource"
8 | "github.com/vearne/chat/model"
9 | pb "github.com/vearne/chat/proto"
10 | "go.uber.org/zap"
11 | "google.golang.org/grpc"
12 | "google.golang.org/grpc/reflection"
13 | "net"
14 | )
15 |
16 | type GrpcWorker struct {
17 | server *grpc.Server
18 | }
19 |
20 | func NewGrpcWorker() *GrpcWorker {
21 | worker := GrpcWorker{}
22 |
23 | worker.server = grpc.NewServer()
24 | pb.RegisterBrokerServer(worker.server, &worker)
25 | // Register reflection service on gRPC server.
26 | reflection.Register(worker.server)
27 |
28 | return &worker
29 | }
30 |
31 | func (w *GrpcWorker) Start() {
32 | lis, err := net.Listen("tcp", config.GetBrokerOpts().Broker.GrpcAddress)
33 | if err != nil {
34 | zlog.Fatal("failed to listen", zap.Error(err))
35 | }
36 | if err := w.server.Serve(lis); err != nil {
37 | zlog.Fatal("failed to serve", zap.Error(err))
38 | }
39 | }
40 |
41 | func (w *GrpcWorker) Stop() {
42 | w.server.Stop()
43 | }
44 |
45 | func (w *GrpcWorker) HealthCheck(ctx context.Context, req *pb.HealthCheckReq) (*pb.HealthCheckResp, error) {
46 | ans := &pb.HealthCheckResp{Code: pb.CodeEnum_Success}
47 | return ans, nil
48 | }
49 |
50 | func (w *GrpcWorker) ReceiveMsgDialogue(ctx context.Context, in *pb.PushDialogue) (*pb.PushResp, error) {
51 | zlog.Debug("ReceiveMsgDialogue", zap.Uint64("senderId", in.SenderId),
52 | zap.Uint64("sessionId", in.SessionId), zap.String("content", in.Content))
53 |
54 | client, ok := resource.Hub.GetClient(in.ReceiverId)
55 | if ok {
56 | req := model.NewCmdPushDialogueReq()
57 | req.SenderId = in.SenderId
58 | req.MsgId = in.MsgId
59 | req.SessionId = in.SessionId
60 | req.Content = in.Content
61 | clientWrite(client, req)
62 | } else {
63 | zlog.Info("Receiver offline", zap.Uint64("receiverId", in.ReceiverId))
64 | req := pb.LogoutRequest{
65 | AccountId: in.ReceiverId,
66 | Broker: config.GetBrokerOpts().BrokerGrpcAddr,
67 | }
68 | _, err := resource.LogicClient.Logout(context.Background(), &req)
69 | if err != nil {
70 | zlog.Error("LogicClient.Logout", zap.Error(err))
71 | }
72 | }
73 |
74 | // result
75 | resp := pb.PushResp{Code: pb.CodeEnum_Success}
76 | return &resp, nil
77 | }
78 |
79 | func (w *GrpcWorker) ReceiveMsgSignal(ctx context.Context, in *pb.PushSignal) (*pb.PushResp, error) {
80 | zlog.Info("ReceiveMsgSignal", zap.Uint64("senderId", in.SenderId),
81 | zap.Uint64("sessionId", in.SessionId), zap.String("signalType",
82 | pb.SignalTypeEnum_name[int32(in.SignalType)]))
83 | // result
84 | resp := &pb.PushResp{Code: pb.CodeEnum_Success}
85 |
86 | switch in.SignalType {
87 | case pb.SignalTypeEnum_NewSession:
88 | zlog.Debug("NewSession")
89 |
90 | req := model.NewCmdPushSignalReq()
91 | req.SenderId = in.SenderId
92 | req.SignalType = pb.SignalTypeEnum_name[int32(in.SignalType)]
93 | req.SessionId = in.SessionId
94 | req.ReceiverId = in.ReceiverId
95 | req.Data = in.GetPartner()
96 |
97 | client, ok := resource.Hub.GetClient(in.ReceiverId)
98 | if ok {
99 | clientWrite(client, req)
100 | }
101 |
102 | case pb.SignalTypeEnum_PartnerExit:
103 | zlog.Debug("PartnerExit")
104 | /*
105 | {
106 | "cmd": "PUSH_SIGNAL_REQ",
107 | "signalType: "PartnerExit"
108 | "senderId": 1111,
109 | "sessionId": 10000,
110 | "receiverId": 12000,
111 | "data":{
112 | "accountId": 1000,
113 | }
114 | }
115 | */
116 |
117 | req := model.NewCmdPushSignalReq()
118 | req.SenderId = in.SenderId
119 | req.SignalType = pb.SignalTypeEnum_name[int32(in.SignalType)]
120 | req.SessionId = in.SessionId
121 | req.ReceiverId = in.ReceiverId
122 | req.Data = map[string]uint64{"accountId": in.GetAccountId()}
123 |
124 | client, ok := resource.Hub.GetClient(in.ReceiverId)
125 | if ok {
126 | clientWrite(client, req)
127 | }
128 |
129 | case pb.SignalTypeEnum_DeleteMsg:
130 | zlog.Debug("DeleteMsg")
131 |
132 | case pb.SignalTypeEnum_ViewedAck:
133 | zlog.Debug("ViewedAck")
134 |
135 | req := model.NewCmdPushViewedAckReq()
136 | req.SessionId = in.SessionId
137 | req.AccountId = in.SenderId
138 | req.MsgId = in.GetMsgId()
139 |
140 | client, ok := resource.Hub.GetClient(in.ReceiverId)
141 | if ok {
142 | clientWrite(client, req)
143 | }
144 | default:
145 | zlog.Error("unknow SignalType", zap.Int32("SignalType", int32(in.SignalType)))
146 | }
147 |
148 | // result
149 | return resp, nil
150 | }
151 |
152 | func clientWrite(client *model.Client, obj any) {
153 | err := client.Write(obj)
154 | if err != nil {
155 | zlog.Error("clientWrite", zap.Error(err))
156 | }
157 | }
158 |
--------------------------------------------------------------------------------
/internal/engine/broker/ping_worker.go:
--------------------------------------------------------------------------------
1 | package broker
2 |
3 | import (
4 | "github.com/vearne/chat/internal/config"
5 | zlog "github.com/vearne/chat/internal/log"
6 | "github.com/vearne/chat/internal/resource"
7 | "github.com/vearne/chat/model"
8 | "go.uber.org/zap"
9 | "sync/atomic"
10 | "time"
11 | )
12 |
13 | type PingWorker struct {
14 | RunningFlag atomic.Bool
15 | ExitedFlag chan struct{} // 已经退出的标识
16 | ExitChan chan struct{}
17 | }
18 |
19 | func NewPingWorker() *PingWorker {
20 | //RunningFlag: true, ExitedFlag: false
21 | worker := PingWorker{ExitChan: make(chan struct{})}
22 | worker.RunningFlag.Store(true)
23 | worker.ExitedFlag = make(chan struct{})
24 | return &worker
25 | }
26 |
27 | func (w *PingWorker) Start() {
28 | pingConfig := config.GetBrokerOpts().Ping
29 | zlog.Info("[start]PingWorker", zap.Duration("Interval", pingConfig.Interval),
30 | zap.Duration("MaxWait", pingConfig.MaxWait))
31 |
32 | ticker := time.NewTicker(pingConfig.Interval)
33 | defer ticker.Stop()
34 |
35 | for w.RunningFlag.Load() {
36 | select {
37 | case <-ticker.C:
38 | clients := resource.Hub.GetAllClient()
39 | for _, client := range clients {
40 | if time.Since(client.LastPong) > pingConfig.MaxWait {
41 | // client可能已经掉线
42 | ExecuteLogout(client.AccountId)
43 |
44 | } else {
45 | // 执行一次Ping
46 | cmd := model.NewCmdPingReq()
47 | cmd.AccountId = client.AccountId
48 | clientWrite(client, &cmd)
49 | }
50 | }
51 | case <-w.ExitChan:
52 | zlog.Info("PingWorker execute exit logic")
53 | }
54 | }
55 | close(w.ExitedFlag)
56 | }
57 |
58 | func (w *PingWorker) Stop() {
59 | zlog.Info("PingWorker exit...")
60 | w.RunningFlag.Store(false)
61 | close(w.ExitChan)
62 |
63 | <-w.ExitedFlag
64 | zlog.Info("[end]PingWorker")
65 | }
66 |
--------------------------------------------------------------------------------
/internal/engine/broker/websocket_worker.go:
--------------------------------------------------------------------------------
1 | package broker
2 |
3 | import (
4 | "context"
5 | "encoding/json"
6 | "github.com/gin-gonic/gin"
7 | "github.com/vearne/chat/consts"
8 | "github.com/vearne/chat/internal/config"
9 | zlog "github.com/vearne/chat/internal/log"
10 | "github.com/vearne/chat/internal/resource"
11 | "github.com/vearne/chat/internal/utils"
12 | "github.com/vearne/chat/model"
13 | pb "github.com/vearne/chat/proto"
14 | "go.uber.org/zap"
15 | "gopkg.in/olahol/melody.v1"
16 | "net/http"
17 | "time"
18 | )
19 |
20 | type WebsocketWorker struct {
21 | Server *http.Server
22 | }
23 |
24 | func NewWebsocketWorker() *WebsocketWorker {
25 | zlog.Info("[init]WebServer")
26 | worker := &WebsocketWorker{}
27 | worker.Server = &http.Server{
28 | Addr: config.GetBrokerOpts().Broker.WebSocketAddress,
29 | Handler: createGinEngine(),
30 | ReadTimeout: 10 * time.Second,
31 | WriteTimeout: 10 * time.Second,
32 | MaxHeaderBytes: 1 << 20,
33 | }
34 |
35 | return worker
36 | }
37 |
38 | func (worker *WebsocketWorker) Start() {
39 | zlog.Info("[start]WebsocketWorker")
40 | // 将之前连接在此broker上的用户,都置为离线
41 | zlog.Info("WebsocketWorker-ClearUserStatus")
42 |
43 | zlog.Error(worker.Server.ListenAndServe().Error())
44 | }
45 |
46 | func createGinEngine() *gin.Engine {
47 | r := gin.Default()
48 | m := melody.New()
49 | m.Config.MaxMessageSize = 1024 * 10
50 | m.Config.MessageBufferSize = 4 * 1024
51 |
52 | r.GET("/ws", func(c *gin.Context) {
53 | err := m.HandleRequest(c.Writer, c.Request)
54 | if err != nil {
55 | zlog.Error("websocket", zap.Error(err))
56 | }
57 | })
58 |
59 | m.HandleConnect(func(s *melody.Session) {
60 | zlog.Debug("HandleConnect")
61 | })
62 | m.HandleDisconnect(HandleDisconnect)
63 | m.HandleMessage(handlerMessage)
64 | return r
65 | }
66 |
67 | func (worker *WebsocketWorker) Stop() {
68 | //defer Conn.Close()
69 | // 将之前连接在此broker上的用户,都置为离线
70 | zlog.Info("WebsocketWorker-ClearUserStatus")
71 | cxt, cancel := context.WithTimeout(context.Background(), 5*time.Second)
72 | defer cancel()
73 |
74 | err := worker.Server.Shutdown(cxt)
75 | if err != nil {
76 | zlog.Error("shutdown error", zap.Error(err))
77 | }
78 | zlog.Info("[end]WebsocketWorker exit")
79 | }
80 |
81 | func HandleDisconnect(s *melody.Session) {
82 | accountId, _ := s.Get("accountId")
83 | zlog.Info("HandleDisconnect", zap.Uint64("accountId", accountId.(uint64)))
84 |
85 | ExecuteLogout(accountId.(uint64))
86 | err := s.Close()
87 | if err != nil {
88 | zlog.Error("Session close", zap.Error(err))
89 | }
90 | }
91 |
92 | func HandlePing(wrapper *model.SessionWrapper, data []byte) {
93 | zlog.Debug("CmdPing")
94 | var cmd model.CmdPingReq
95 | err := json.Unmarshal(data, &cmd)
96 | if err != nil {
97 | zlog.Error("HandlePing", zap.Error(err))
98 | return
99 | }
100 | resource.Hub.SetLastPong(cmd.AccountId, time.Now())
101 |
102 | // 返回给客户端
103 | result := model.NewCmdPingResp()
104 | result.AccountId = cmd.AccountId
105 | wrapperWrite(wrapper, result)
106 | }
107 |
108 | func HandlePong(wrapper *model.SessionWrapper, data []byte) {
109 | zlog.Debug("CmdPong")
110 | var cmd model.CmdPingResp
111 | err := json.Unmarshal(data, &cmd)
112 | if err != nil {
113 | zlog.Error("HandlePong", zap.Error(err))
114 | return
115 | }
116 | resource.Hub.SetLastPong(cmd.AccountId, time.Now())
117 | }
118 |
119 | func handlerMessage(s *melody.Session, data []byte) {
120 | var cmd model.CommonCmd
121 | err := json.Unmarshal(data, &cmd)
122 | if err != nil {
123 | zlog.Error("handlerMessage", zap.Error(err))
124 | return
125 | }
126 |
127 | wrapper := model.NewSessionWrapper(s)
128 | switch cmd.Cmd {
129 | case utils.AssembleCmdReq(consts.CmdCreateAccount):
130 | zlog.Info("handlerMessage", zap.String("msg", string(data)))
131 | HandleCrtAccount(wrapper, data)
132 | case utils.AssembleCmdReq(consts.CmdMatch):
133 | zlog.Info("handlerMessage", zap.String("msg", string(data)))
134 | HandleMatch(wrapper, data)
135 | case utils.AssembleCmdReq(consts.CmdDialogue):
136 | zlog.Info("handlerMessage", zap.String("msg", string(data)))
137 | HandleDialogue(wrapper, data)
138 | case utils.AssembleCmdReq(consts.CmdPing):
139 | HandlePing(wrapper, data)
140 | case utils.AssembleCmdResp(consts.CmdPing):
141 | HandlePong(wrapper, data)
142 | case utils.AssembleCmdReq(consts.CmdViewedAck):
143 | HandleViewedAck(wrapper, data)
144 | case utils.AssembleCmdReq(consts.CmdReConnect):
145 | HandleReConnect(wrapper, data)
146 | default:
147 | zlog.Debug("unknow cmd", zap.String("cmd", cmd.Cmd))
148 | }
149 |
150 | }
151 |
152 | func HandleReConnect(wrapper *model.SessionWrapper, data []byte) {
153 | zlog.Debug("CmdReConnect")
154 | var cmd model.CmdReConnectReq
155 | err := json.Unmarshal(data, &cmd)
156 | if err != nil {
157 | zlog.Error("HandleReConnect", zap.Error(err))
158 | return
159 | }
160 |
161 | ctx := context.Background()
162 |
163 | req := pb.ReConnectRequest{
164 | AccountId: cmd.AccountId,
165 | Token: cmd.Token,
166 | Broker: config.GetBrokerOpts().BrokerGrpcAddr,
167 | }
168 | resp, err := resource.LogicClient.Reconnect(ctx, &req)
169 | if err != nil {
170 | zlog.Error("LogicClient.Reconnect", zap.Error(err))
171 | }
172 | // 重新登录成功
173 | if resp.Code == pb.CodeEnum_Success {
174 | zlog.Debug("LogicClient.Reconnect", zap.Any("resp", resp),
175 | zap.Uint64("accountId", resp.AccountId))
176 | // 2 记录accountId和session的对应关系
177 | resource.Hub.SetClient(resp.Nickname, resp.AccountId, wrapper.Session)
178 | wrapper.Session.Set("accountId", resp.AccountId)
179 | }
180 |
181 | result := model.NewCmdReConnectResp()
182 | result.Code = int32(resp.Code)
183 | wrapperWrite(wrapper, result)
184 | }
185 |
186 | func HandleViewedAck(wrapper *model.SessionWrapper, data []byte) {
187 | zlog.Debug("CmdViewedAck")
188 | var cmd model.CmdViewedAckReq
189 | err := json.Unmarshal(data, &cmd)
190 | if err != nil {
191 | zlog.Error("HandleViewedAck", zap.Error(err))
192 | return
193 | }
194 |
195 | ctx := context.Background()
196 | req := pb.ViewedAckRequest{
197 | SessionId: cmd.SessionId,
198 | AccountId: cmd.AccountId,
199 | MsgId: cmd.MsgId,
200 | }
201 | resp, err := resource.LogicClient.ViewedAck(ctx, &req)
202 | if err != nil {
203 | zlog.Error("LogicClient.ViewedAck", zap.Error(err))
204 | }
205 |
206 | result := model.NewCmdViewedAckResp()
207 | result.Code = int32(resp.Code)
208 | wrapperWrite(wrapper, result)
209 | }
210 |
211 | func HandleDialogue(wrapper *model.SessionWrapper, data []byte) {
212 | zlog.Debug("CmdDialogue")
213 | var cmd model.CmdDialogueReq
214 | err := json.Unmarshal(data, &cmd)
215 | if err != nil {
216 | zlog.Error("HandleDialogue", zap.Error(err))
217 | return
218 | }
219 |
220 | ctx := context.Background()
221 | req := pb.SendMsgRequest{
222 | SenderId: cmd.SenderId, SessionId: cmd.SessionId,
223 | Msgtype: pb.MsgTypeEnum_Dialogue, Content: cmd.Content}
224 |
225 | resp, err := resource.LogicClient.SendMsg(ctx, &req)
226 | if err != nil {
227 | zlog.Error("LogicClient.HandleDialogue", zap.Error(err))
228 | }
229 | result := model.NewCmdDialogueResp()
230 | result.Code = int32(resp.Code)
231 | result.MsgId = resp.MsgId
232 | result.RequestId = cmd.RequestId
233 | wrapperWrite(wrapper, result)
234 | }
235 |
236 | func HandleMatch(wrapper *model.SessionWrapper, data []byte) {
237 | zlog.Debug("CmdMatch")
238 | var cmd model.CmdMatchReq
239 | err := json.Unmarshal(data, &cmd)
240 | if err != nil {
241 | zlog.Error("HandleMatch", zap.Error(err))
242 | return
243 | }
244 |
245 | // 1. 请求
246 | ctx := context.Background()
247 | req := pb.MatchRequest{AccountId: cmd.AccountId}
248 | resp, err := resource.LogicClient.Match(ctx, &req)
249 | if err != nil {
250 | zlog.Error("LogicClient.Match", zap.Error(err))
251 | }
252 | result := model.NewCmdMatchResp()
253 | result.Code = int32(resp.Code)
254 | if resp.Code == pb.CodeEnum_Success {
255 | result.PartnerId = resp.PartnerId
256 | result.PartnerName = resp.PartnerName
257 | result.SessionId = resp.SessionId
258 | }
259 | wrapperWrite(wrapper, result)
260 | }
261 |
262 | func HandleCrtAccount(wrapper *model.SessionWrapper, data []byte) {
263 | zlog.Debug("CmdCreateAccount")
264 | var cmd model.CmdCreateAccountReq
265 | err := json.Unmarshal(data, &cmd)
266 | if err != nil {
267 | zlog.Error("HandleCrtAccount", zap.Error(err))
268 | return
269 | }
270 |
271 | // 1. 请求
272 | ctx := context.Background()
273 | req := pb.CreateAccountRequest{Nickname: cmd.NickName, Broker: config.GetBrokerOpts().BrokerGrpcAddr}
274 | resp, err := resource.LogicClient.CreateAccount(ctx, &req)
275 | if err != nil {
276 | zlog.Error("LogicClient.CreateAccount", zap.Error(err))
277 | return
278 | }
279 |
280 | zlog.Debug("LogicClient.CreateAccount", zap.Any("resp", resp),
281 | zap.Uint64("accountId", resp.AccountId))
282 | // 2 记录accountId和session的对应关系
283 | resource.Hub.SetClient(req.Nickname, resp.AccountId, wrapper.Session)
284 | wrapper.Session.Set("accountId", resp.AccountId)
285 |
286 | // 3. 返回给客户端
287 | result := model.NewCmdCreateAccountResp()
288 | result.AccountId = resp.AccountId
289 | result.NickName = req.Nickname
290 | result.Token = resp.Token
291 | wrapperWrite(wrapper, result)
292 | }
293 |
294 | func ExecuteLogout(accountId uint64) {
295 | // 1. 修改本地状态
296 | // melody 会清理它的hub
297 | // 我们只需要清理我们自己的
298 | resource.Hub.RemoveClient(accountId)
299 |
300 | // 2. 通知其他人
301 | req := pb.LogoutRequest{
302 | AccountId: accountId,
303 | Broker: config.GetBrokerOpts().BrokerGrpcAddr,
304 | }
305 | resp, err := resource.LogicClient.Logout(context.Background(), &req)
306 | if err != nil {
307 | zlog.Error("LogicClient.Logout", zap.Error(err))
308 | return
309 | }
310 | zlog.Info("LogicClient.Logout", zap.Uint64("accountId", accountId),
311 | zap.Int32("code", int32(resp.Code)))
312 | }
313 |
314 | func wrapperWrite(wrapper *model.SessionWrapper, obj any) {
315 | err := wrapper.Write(obj)
316 | if err != nil {
317 | zlog.Error("wrapperWrite", zap.Error(err))
318 | }
319 | }
320 |
--------------------------------------------------------------------------------
/internal/engine/logic/broker_checker.go:
--------------------------------------------------------------------------------
1 | package logic
2 |
3 | import (
4 | "context"
5 | "github.com/vearne/chat/internal/config"
6 | zlog "github.com/vearne/chat/internal/log"
7 | "github.com/vearne/chat/internal/resource"
8 | "github.com/vearne/chat/internal/utils"
9 | pb "github.com/vearne/chat/proto"
10 | "go.uber.org/zap"
11 | "sync/atomic"
12 | "time"
13 | )
14 |
15 | var DefaultExpiredTime = time.Time{}
16 |
17 | const maxOffLine = 10 * time.Second
18 |
19 | /*
20 | 确保broker都在线
21 | 如果broker已经掉线,就将与broker连接的用户全部下线
22 | */
23 | type BrokerChecker struct {
24 | RunningFlag atomic.Bool // 是否运行 true:运行 false:停止
25 | ExitedFlag chan struct{} // 已经退出的标识
26 | ExitChan chan struct{}
27 | // addr -> 上一次健康检查通过的时间
28 | brokerStatus map[string]time.Time
29 | }
30 |
31 | func NewBrokerChecker() *BrokerChecker {
32 | worker := &BrokerChecker{}
33 | worker.RunningFlag.Store(true)
34 | worker.ExitedFlag = make(chan struct{})
35 | worker.ExitChan = make(chan struct{})
36 | worker.brokerStatus = make(map[string]time.Time)
37 | return worker
38 | }
39 |
40 | func (worker *BrokerChecker) Start() {
41 | ticker := time.NewTicker(time.Second * 3)
42 | defer ticker.Stop()
43 |
44 | zlog.Info("[start]BrokerChecker")
45 | for worker.RunningFlag.Load() {
46 | select {
47 | case <-ticker.C:
48 | zlog.Debug("BrokerChecker-ticker trigger")
49 | worker.checkBroker()
50 | case <-worker.ExitChan:
51 | zlog.Info("BrokerChecker-got exit signal from ExitChan")
52 | }
53 |
54 | }
55 | zlog.Info("BrokerChecker exit")
56 | // mark
57 | close(worker.ExitedFlag)
58 | }
59 |
60 | func (worker *BrokerChecker) Stop() {
61 | worker.RunningFlag.Store(false)
62 | close(worker.ExitChan)
63 |
64 | <-worker.ExitedFlag
65 | zlog.Info("[end]BrokerChecker")
66 | }
67 |
68 | func (worker *BrokerChecker) checkBroker() {
69 | begin := time.Now()
70 | zlog.Debug("[start]checkBroker")
71 |
72 | ip, _ := utils.GetIP()
73 | logicID := ip + config.GetLogicOpts().LogicDealer.ListenAddress
74 | in := pb.HealthCheckReq{Asker: logicID}
75 |
76 | addrs := GetBrokerList()
77 | var client pb.BrokerClient
78 | var err error
79 | var ok bool
80 |
81 | for _, addr := range addrs {
82 | client, ok = resource.BrokerHub.GetBroker(addr)
83 | if !ok {
84 | client, err = CreateBrokerClient(addr)
85 | if err != nil {
86 | zlog.Error("CreateBrokerClient", zap.Error(err))
87 | if _, ok := worker.brokerStatus[addr]; !ok {
88 | worker.brokerStatus[addr] = DefaultExpiredTime
89 | }
90 | continue
91 | }
92 | }
93 |
94 | _, err = client.HealthCheck(context.Background(), &in)
95 | if err != nil {
96 | zlog.Info("check broker", zap.String("broker", addr), zap.Error(err))
97 | } else {
98 | worker.brokerStatus[addr] = time.Now()
99 | }
100 | }
101 |
102 | // 清理已经掉线的broker,以及与这些broker关联的账号
103 | for addr, t := range worker.brokerStatus {
104 | if time.Since(t) > maxOffLine {
105 | zlog.Error("broker may have been offline", zap.String("broker", addr))
106 | ClearUserStatus(addr)
107 | resource.BrokerHub.RemoveBroker(addr)
108 | delete(worker.brokerStatus, addr)
109 | }
110 | }
111 |
112 | zlog.Debug("[end]checkBroker", zap.Duration("cost", time.Since(begin)))
113 | }
114 |
115 | type BrokerInfo struct {
116 | Broker string `gorm:"column:broker" json:"broker"`
117 | }
118 |
119 | func GetBrokerList() []string {
120 | brokerList := make([]BrokerInfo, 0)
121 | err := resource.MySQLClient.Table("account").Distinct("broker").
122 | Where("status = 1").Find(&brokerList).Error
123 | if err != nil {
124 | zlog.Error("GetBrokerList", zap.Error(err))
125 | return nil
126 | }
127 | addrs := make([]string, 0)
128 | for i := range brokerList {
129 | addrs = append(addrs, brokerList[i].Broker)
130 | }
131 | return addrs
132 | }
133 |
--------------------------------------------------------------------------------
/internal/engine/logic/grpc_worker.go:
--------------------------------------------------------------------------------
1 | package logic
2 |
3 | import (
4 | "context"
5 | "errors"
6 | "github.com/grpc-ecosystem/go-grpc-middleware/ratelimit"
7 | "github.com/vearne/chat/consts"
8 | "github.com/vearne/chat/internal/biz"
9 | "github.com/vearne/chat/internal/config"
10 | dao2 "github.com/vearne/chat/internal/dao"
11 | zlog "github.com/vearne/chat/internal/log"
12 | "github.com/vearne/chat/internal/middleware"
13 | "github.com/vearne/chat/internal/resource"
14 | "github.com/vearne/chat/model"
15 | pb "github.com/vearne/chat/proto"
16 | "go.uber.org/zap"
17 | "google.golang.org/grpc"
18 | "google.golang.org/grpc/reflection"
19 | "gorm.io/gorm"
20 | "net"
21 | "time"
22 | )
23 |
24 | const TokenLen = 30
25 |
26 | type LogicGrpcWorker struct {
27 | server *grpc.Server
28 | }
29 |
30 | func NewLogicGrpcWorker() *LogicGrpcWorker {
31 | worker := LogicGrpcWorker{}
32 |
33 | limiter := middleware.NewTokenBucketLimiter(10, 2)
34 |
35 | worker.server = grpc.NewServer(
36 | grpc.ChainUnaryInterceptor(
37 | ratelimit.UnaryServerInterceptor(limiter),
38 | ),
39 | grpc.ChainStreamInterceptor(
40 | ratelimit.StreamServerInterceptor(limiter),
41 | ),
42 | )
43 |
44 | pb.RegisterLogicDealerServer(worker.server, &LogicServer{})
45 | // Register reflection service on gRPC server.
46 | reflection.Register(worker.server)
47 |
48 | return &worker
49 | }
50 |
51 | func (w *LogicGrpcWorker) Start() {
52 | listenAddr := config.GetLogicOpts().LogicDealer.ListenAddress
53 | zlog.Info("[start]LogicGrpcWorker", zap.String("LogicDealer", listenAddr))
54 | lis, err := net.Listen("tcp", listenAddr)
55 | if err != nil {
56 | zlog.Fatal("failed to listen", zap.Error(err))
57 | }
58 | if err := w.server.Serve(lis); err != nil {
59 | zlog.Fatal("failed to serve", zap.Error(err))
60 | }
61 | }
62 |
63 | func (w *LogicGrpcWorker) Stop() {
64 | w.server.Stop()
65 | zlog.Info("[end]LogicGrpcWorker")
66 | }
67 |
68 | type LogicServer struct{}
69 |
70 | func (s *LogicServer) Reconnect(ctx context.Context, in *pb.ReConnectRequest) (*pb.ReConnectResponse, error) {
71 | var account model.Account
72 | err := resource.MySQLClient.Model(&model.Account{}).Where("id = ? and token = ?",
73 | in.AccountId, in.Token).Take(&account).Error
74 |
75 | out := &pb.ReConnectResponse{}
76 | if errors.Is(err, gorm.ErrRecordNotFound) {
77 | out.Code = pb.CodeEnum_NoDataFound
78 | } else {
79 | err = resource.MySQLClient.Model(&model.Account{}).Where("id = ?",
80 | in.AccountId).Updates(map[string]interface{}{
81 | "status": consts.AccountStatusInUse,
82 | "broker": in.Broker,
83 | }).Error
84 | if err != nil {
85 | zlog.Error("update account", zap.Error(err))
86 | out.Code = pb.CodeEnum_InternalErr
87 | out.Msg = err.Error()
88 | } else {
89 | out.Code = pb.CodeEnum_Success
90 | out.AccountId = in.AccountId
91 | out.Nickname = account.NickName
92 | }
93 | }
94 | return out, nil
95 | }
96 |
97 | func (s *LogicServer) ViewedAck(ctx context.Context, req *pb.ViewedAckRequest) (*pb.ViewedAckResponse, error) {
98 | var resp pb.ViewedAckResponse
99 |
100 | err := dao2.CreatOrUpdateViewedAck(req.SessionId, req.AccountId, req.MsgId)
101 | if err != nil {
102 | zlog.Error("dao2.CreatOrUpdateViewedAck", zap.Error(err))
103 | resp.Code = pb.CodeEnum_InternalErr
104 | resp.Msg = err.Error()
105 | return &resp, nil
106 | }
107 |
108 | partner, err := dao2.GetSessionPartner(req.SessionId, req.AccountId)
109 | if err != nil {
110 | resp.Code = pb.CodeEnum_InternalErr
111 | resp.Msg = err.Error()
112 | return &resp, nil
113 | }
114 |
115 | notifyViewedAck(req.AccountId, partner.AccountId, req.SessionId, req.MsgId)
116 |
117 | resp.Code = pb.CodeEnum_Success
118 | return &resp, nil
119 | }
120 |
121 | func (s *LogicServer) CreateAccount(ctx context.Context,
122 | req *pb.CreateAccountRequest) (*pb.CreateAccountResponse, error) {
123 | // Broker
124 | // 192.168.10.100:18223
125 |
126 | token := RandStringBytes(TokenLen)
127 | var account model.Account
128 | account.NickName = req.Nickname
129 | account.Broker = req.Broker
130 | account.Status = consts.AccountStatusInUse
131 | account.Token = token
132 | account.CreatedAt = time.Now()
133 | account.ModifiedAt = account.CreatedAt
134 |
135 | var resp pb.CreateAccountResponse
136 |
137 | err := resource.MySQLClient.Create(&account).Error
138 | if err != nil {
139 | zlog.Error("CreateAccount", zap.Error(err))
140 | resp.Code = pb.CodeEnum_InternalErr
141 | resp.Msg = err.Error()
142 | return &resp, nil
143 | }
144 |
145 | resp.Code = pb.CodeEnum_Success
146 | resp.AccountId = account.ID
147 | resp.Token = token
148 | return &resp, nil
149 | }
150 |
151 | func (s *LogicServer) Match(ctx context.Context, req *pb.MatchRequest) (*pb.MatchResponse, error) {
152 | var partner model.Account
153 |
154 | var resp pb.MatchResponse
155 |
156 | sql := "select * from account where status = 1 and id != ? order by rand() limit 1"
157 | err := resource.MySQLClient.Raw(sql, req.AccountId).Scan(&partner).Error
158 | if err != nil {
159 | zlog.Error("Match-query", zap.Error(err))
160 | resp.Code = pb.CodeEnum_InternalErr
161 | resp.Msg = err.Error()
162 | return &resp, nil
163 | }
164 |
165 | if partner.ID <= 0 {
166 | // No suitable target found
167 | resp.Code = pb.CodeEnum_NoDataFound
168 | return &resp, nil
169 | }
170 | // 1. 创建会话
171 | session, err := biz.CreateSession(partner.ID, req.AccountId)
172 | if err != nil {
173 | zlog.Error("Match-CreateSession", zap.Error(err))
174 | resp.Code = pb.CodeEnum_InternalErr
175 | resp.Msg = err.Error()
176 | return &resp, nil
177 | }
178 |
179 | // 2. 给被匹配的account发送一个信令,通知他有新的会话建立
180 | notifyPartnerNewSession(req.AccountId, partner.ID, session.ID)
181 |
182 | resp.PartnerId = partner.ID
183 | resp.PartnerName = partner.NickName
184 | resp.SessionId = session.ID
185 | resp.Code = pb.CodeEnum_Success
186 |
187 | return &resp, nil
188 | }
189 |
190 | func (s *LogicServer) SendMsg(ctx context.Context, req *pb.SendMsgRequest) (*pb.SendMsgResponse, error) {
191 | // 这个的消息可能是 正常的消息 或者 某种信号
192 | // 比如 1) 用户主动退出会话 2)用户掉线退出会话 3)删除某条消息
193 | var resp pb.SendMsgResponse
194 | var err error
195 | var session *model.Session
196 | var partner *model.SessionAccount
197 |
198 | // 1. 存储在发件箱
199 | outMsg, err := dao2.CreateOutMsg(req.Msgtype, req.SenderId, req.SessionId, req.Content)
200 | if err != nil {
201 | zlog.Error("dao2.CreateOutMsg", zap.Error(err))
202 | goto INTERNAL_ERROR
203 | }
204 |
205 | // 判断一下会话的状态,收件人是否退出等情况
206 | session, err = dao2.GetSession(req.SessionId)
207 | if err != nil {
208 | zlog.Error("dao2.GetSession", zap.Error(err))
209 | goto INTERNAL_ERROR
210 | }
211 | // 2. 存储在收件箱
212 | if session.Status == consts.SessionStatusInUse {
213 | partner, err = dao2.GetSessionPartner(outMsg.SessionId, req.SenderId)
214 | if err != nil {
215 | zlog.Error("dao2.GetSessionPartner", zap.Error(err))
216 | goto INTERNAL_ERROR
217 | }
218 |
219 | _, err = dao2.CreateInMsg(req.SenderId, outMsg.ID, partner.AccountId)
220 | if err != nil {
221 | zlog.Error("dao2.CreateInMsg", zap.Error(err))
222 | goto INTERNAL_ERROR
223 | }
224 | SendPartnerMsg(outMsg.ID, req.SenderId, partner.AccountId, req.SessionId, req.Content)
225 |
226 | } else {
227 | // 由系统产生一条消息,来替代用户发出的消息
228 | // 消息的接收人已经退出了
229 | partner, err = dao2.GetSessionPartner(req.SessionId, req.SenderId)
230 | if err != nil {
231 | zlog.Error("dao2.GetSessionPartner", zap.Error(err))
232 | goto INTERNAL_ERROR
233 | }
234 | notifyPartnerExit(req.SenderId, partner.SessionId, partner.AccountId)
235 | }
236 |
237 | // push
238 | resp.Code = pb.CodeEnum_Success
239 | resp.MsgId = outMsg.ID
240 | return &resp, nil
241 |
242 | INTERNAL_ERROR:
243 | resp.Code = pb.CodeEnum_InternalErr
244 | resp.Msg = err.Error()
245 | return &resp, nil
246 | }
247 |
248 | func (s *LogicServer) Logout(ctx context.Context, req *pb.LogoutRequest) (*pb.LogoutResponse, error) {
249 | handlerLogout(req.AccountId, req.Broker)
250 | var resp pb.LogoutResponse
251 | resp.Code = pb.CodeEnum_Success
252 | return &resp, nil
253 | }
254 |
255 | func notifyPartnerExit(receiverId, sessionId uint64, exiterId uint64) {
256 | resource.WaitToBrokerSignalChan <- &pb.PushSignal{
257 | SignalType: pb.SignalTypeEnum_PartnerExit,
258 | SenderId: consts.SystemSender,
259 | SessionId: sessionId,
260 | ReceiverId: receiverId,
261 | Data: &pb.PushSignal_AccountId{AccountId: exiterId},
262 | }
263 | zlog.Debug("notifyPartnerExit, 1.send signal to broker")
264 | // 存入数据库
265 | // outbox
266 | outMsg, err := dao2.CreateOutMsg(pb.MsgTypeEnum_Signal, consts.SystemSender, sessionId,
267 | pb.SignalTypeEnum_name[int32(pb.SignalTypeEnum_PartnerExit)])
268 | if err != nil {
269 | zlog.Error("dao2.CreateOutMsg", zap.Error(err))
270 | return
271 | }
272 |
273 | // inbox
274 | _, err = dao2.CreateInMsg(consts.SystemSender, outMsg.ID, receiverId)
275 | if err != nil {
276 | zlog.Error("dao2.CreateInMsg", zap.Error(err))
277 | return
278 | }
279 | zlog.Debug("notifyPartnerExit, 2.save to database")
280 | }
281 |
282 | func notifyPartnerNewSession(senderId, receiverId, sessionId uint64) {
283 | //resource.WaitToBrokerSignalChan <- &
284 | msg := pb.PushSignal{
285 | SignalType: pb.SignalTypeEnum_NewSession,
286 | SenderId: senderId,
287 | SessionId: sessionId,
288 | ReceiverId: receiverId,
289 | }
290 |
291 | sender, err := dao2.GetAccount(senderId)
292 | if err != nil {
293 | zlog.Error("dao2.GetAccount", zap.Error(err))
294 | return
295 | }
296 |
297 | msg.Data = &pb.PushSignal_Partner{Partner: &pb.AccountInfo{
298 | AccountId: sender.ID,
299 | NickName: sender.NickName,
300 | }}
301 | resource.WaitToBrokerSignalChan <- &msg
302 | zlog.Debug("notifyPartnerNewSession, 1.send signal to broker")
303 |
304 | // 存入数据库
305 | // outbox
306 | outMsg, err := dao2.CreateOutMsg(pb.MsgTypeEnum_Signal, senderId, sessionId,
307 | pb.SignalTypeEnum_name[int32(pb.SignalTypeEnum_NewSession)])
308 | if err != nil {
309 | zlog.Error("dao2.CreateOutMsg", zap.Error(err))
310 | return
311 | }
312 |
313 | // inbox
314 | _, err = dao2.CreateInMsg(senderId, outMsg.ID, receiverId)
315 | if err != nil {
316 | zlog.Error("dao2.CreateInMsg", zap.Error(err))
317 | return
318 | }
319 |
320 | zlog.Debug("notifyPartnerNewSession, 2.save to database")
321 | }
322 |
323 | func notifyViewedAck(senderId, receiverId, sessionId uint64, msgId uint64) {
324 | msg := pb.PushSignal{
325 | SignalType: pb.SignalTypeEnum_ViewedAck,
326 | SenderId: senderId,
327 | SessionId: sessionId,
328 | ReceiverId: receiverId,
329 | Data: &pb.PushSignal_MsgId{MsgId: msgId},
330 | }
331 | resource.WaitToBrokerSignalChan <- &msg
332 | zlog.Debug("notifyViewedAck", zap.Uint64("SenderId", senderId),
333 | zap.Uint64("SessionId", sessionId),
334 | zap.Uint64("ReceiverId", receiverId), zap.Uint64("msgId", msgId))
335 | }
336 |
337 | func SendPartnerMsg(msgId, senderId, receiverId, sessionId uint64, content string) {
338 | resource.WaitToBrokerDialogueChan <- &pb.PushDialogue{
339 | MsgId: msgId,
340 | SenderId: senderId,
341 | SessionId: sessionId,
342 | ReceiverId: receiverId,
343 | Content: content,
344 | }
345 | }
346 |
347 | func ClearUserStatus(broker string) {
348 | // 清理某个broker上的所有账号
349 | // 让他们都下线(登出)
350 | accounts := make([]model.Account, 0)
351 | err := resource.MySQLClient.Model(&model.Account{}).
352 | Where("status = ? AND broker = ?", consts.AccountStatusInUse, broker).Find(&accounts).Error
353 | if err != nil {
354 | zlog.Error("ClearUserStatus", zap.Error(err))
355 | return
356 | }
357 |
358 | for _, item := range accounts {
359 | zlog.Info("logout", zap.Uint64("AccountId", item.ID))
360 | handlerLogout(item.ID, broker)
361 | }
362 | }
363 |
364 | func handlerLogout(accountId uint64, broker string) bool {
365 | // 1, 把账号置为退出
366 | result := resource.MySQLClient.Model(&model.Account{}).Where("id = ? AND broker = ? AND status = ?",
367 | accountId, broker, consts.AccountStatusInUse).Updates(map[string]interface{}{
368 | "status": consts.AccountStatusDestroyed,
369 | "modified_at": time.Now()})
370 |
371 | if result.RowsAffected <= 0 {
372 | return false
373 | }
374 |
375 | var itemList []model.SessionAccount
376 | err := resource.MySQLClient.Where("account_id = ?", accountId).Find(&itemList).Error
377 | if err != nil {
378 | zlog.Error("handlerLogout", zap.Error(err))
379 | return false
380 | }
381 |
382 | var partner *model.SessionAccount
383 | for _, item := range itemList {
384 | // update session
385 | // 2. 将账号关联的所有会话都退出
386 | result := resource.MySQLClient.Model(&model.Session{}).Where("id = ? and status = ?",
387 | item.SessionId, consts.SessionStatusInUse).Updates(map[string]interface{}{
388 | "status": consts.SessionStatusDestroyed,
389 | "modified_at": time.Now(),
390 | })
391 | if result.Error != nil {
392 | zlog.Error("handlerLogout-update session", zap.Error(err))
393 | return false
394 | }
395 |
396 | // Maybe this session has been closed long ago
397 | if result.RowsAffected <= 0 {
398 | continue
399 | }
400 |
401 | // notify parnter
402 | // 通知这些会话的参与者,会话即将销毁
403 | partner, err = dao2.GetSessionPartner(item.SessionId, accountId)
404 | if err != nil {
405 | zlog.Error("handlerLogout-GetSessionPartner", zap.Error(err))
406 | return false
407 | }
408 | notifyPartnerExit(partner.AccountId, item.SessionId, accountId)
409 | }
410 | return true
411 | }
412 |
--------------------------------------------------------------------------------
/internal/engine/logic/pump_dialogue_loop.go:
--------------------------------------------------------------------------------
1 | package logic
2 |
3 | import (
4 | "context"
5 | "fmt"
6 | "github.com/vearne/chat/internal/dao"
7 | zlog "github.com/vearne/chat/internal/log"
8 | resource2 "github.com/vearne/chat/internal/resource"
9 | "github.com/vearne/chat/internal/utils"
10 | pb "github.com/vearne/chat/proto"
11 | "go.uber.org/zap"
12 | "time"
13 | )
14 |
15 | type PumpDialogueLoopWorker struct {
16 | //RunningFlag bool // is running? true:running false:stoped
17 | ExitedFlag chan struct{}
18 | ExitChan chan struct{}
19 | minCount int
20 | maxCount int
21 | poolSize int
22 | waitGroup utils.WaitGroupWrapper
23 | }
24 |
25 | func NewPumpDialogueLoopWorker(minCount, maxCount int) *PumpDialogueLoopWorker {
26 | worker := PumpDialogueLoopWorker{ExitChan: make(chan struct{})}
27 | worker.ExitedFlag = make(chan struct{})
28 | if minCount <= 1 {
29 | minCount = 1
30 | }
31 | if maxCount <= 1 {
32 | maxCount = 1
33 | }
34 | worker.minCount = minCount
35 | worker.maxCount = maxCount
36 | return &worker
37 | }
38 |
39 | func (w *PumpDialogueLoopWorker) Start() {
40 | zlog.Info("[start]PumpDialogueLoopWorker")
41 | w.PumpDialogueLoop()
42 | close(w.ExitedFlag)
43 | }
44 |
45 | func (w *PumpDialogueLoopWorker) Stop() {
46 | zlog.Info("PumpDialogueLoopWorker exit...")
47 | close(w.ExitChan)
48 |
49 | <-w.ExitedFlag
50 | zlog.Info("[end]PumpDialogueLoopWorker")
51 | }
52 |
53 | func (w *PumpDialogueLoopWorker) PumpDialogueLoop() {
54 | // 用于统计使用
55 | successedCounter := 0
56 | failedCounter := 0
57 |
58 | // 回收处理结果
59 | responseCh := make(chan bool, 100)
60 |
61 | // TODO
62 | go func() {
63 | for result := range responseCh {
64 | if result {
65 | successedCounter++
66 | } else {
67 | failedCounter++
68 | }
69 | }
70 | }()
71 |
72 | // 用于结束worker
73 | closeCh := make(chan int, 1)
74 |
75 | brokerCount := resource2.BrokerHub.Size()
76 | // 期望是处理的协程数 与 broker的数量相等
77 | w.resizePool(brokerCount, resource2.WaitToBrokerDialogueChan, responseCh, closeCh)
78 |
79 | refreshTicker := time.NewTicker(time.Second * 1)
80 |
81 | for {
82 | select {
83 | case <-refreshTicker.C:
84 | brokerCount = resource2.BrokerHub.Size()
85 | w.resizePool(brokerCount, resource2.WaitToBrokerDialogueChan, responseCh, closeCh)
86 | continue
87 | case <-w.ExitChan:
88 | goto exit
89 | }
90 | }
91 |
92 | exit:
93 | close(closeCh)
94 | refreshTicker.Stop()
95 | w.waitGroup.Wait()
96 | close(w.ExitedFlag)
97 | }
98 |
99 | // 参考nsq动态协程池的实现
100 | func (w *PumpDialogueLoopWorker) resizePool(idealPoolSize int, inCh chan *pb.PushDialogue,
101 | outCh chan bool, closeCh chan int) {
102 | if idealPoolSize < w.minCount {
103 | idealPoolSize = w.minCount
104 | }
105 | if idealPoolSize > w.maxCount {
106 | idealPoolSize = w.maxCount
107 | }
108 | for {
109 | if idealPoolSize == w.poolSize {
110 | break
111 | } else if idealPoolSize < w.poolSize {
112 | // contract
113 | closeCh <- 1
114 | w.poolSize--
115 | } else {
116 | // expand
117 | w.waitGroup.Wrap(func() {
118 | pumpDialogueWorker(inCh, outCh, closeCh)
119 | })
120 | w.poolSize++
121 | }
122 | }
123 | }
124 |
125 | func pumpDialogueWorker(inCh chan *pb.PushDialogue, outCh chan bool, closeCh chan int) {
126 | for {
127 | select {
128 | case c := <-inCh:
129 | result := pumpDialogueToBroker(c)
130 | outCh <- result
131 | case <-closeCh:
132 | return
133 | }
134 | }
135 | }
136 |
137 | func pumpDialogueToBroker(msg *pb.PushDialogue) bool {
138 | var client pb.BrokerClient
139 | var err error
140 | var ok bool
141 | // 先获取目标所在的broker
142 | account, err := dao.GetAccount(msg.ReceiverId)
143 | if err != nil {
144 | zlog.Error("dao.GetAccount", zap.Error(err))
145 | return false
146 | }
147 | if client, ok = resource2.BrokerHub.GetBroker(account.Broker); !ok {
148 | client, err = CreateBrokerClient(account.Broker)
149 | if err != nil {
150 | zlog.Error("CreateBrokerClient fail", zap.Error(err))
151 | return false
152 | }
153 | resource2.BrokerHub.SetBroker(account.Broker, client)
154 | }
155 | resp, err := client.ReceiveMsgDialogue(context.Background(), msg)
156 | if err != nil {
157 | zlog.Error("PumpDialogueToBroker", zap.Error(err))
158 | return false
159 | }
160 | zlog.Info("PumpDialogueToBroker", zap.Int32("code", int32(resp.Code)),
161 | zap.Uint64("ReceiverId", msg.ReceiverId),
162 | zap.String("content", msg.Content))
163 | return true
164 | }
165 | func CreateBrokerClient(broker string) (pb.BrokerClient, error) {
166 | conn, err := resource2.CreateGrpcClientConn(broker, 3, time.Second*3, resource2.ServiceDebug)
167 |
168 | if err != nil {
169 | zlog.Error("can't connect to logic", zap.String("broker", broker))
170 | return nil, fmt.Errorf("con't connect to logic:%v", broker)
171 | }
172 | //defer conn.Close()
173 | client := pb.NewBrokerClient(conn)
174 | return client, nil
175 | }
176 |
--------------------------------------------------------------------------------
/internal/engine/logic/pump_signal_loop.go:
--------------------------------------------------------------------------------
1 | package logic
2 |
3 | import (
4 | "context"
5 | "github.com/json-iterator/go"
6 | "github.com/vearne/chat/internal/dao"
7 | zlog "github.com/vearne/chat/internal/log"
8 | "github.com/vearne/chat/internal/resource"
9 | pb "github.com/vearne/chat/proto"
10 | "go.uber.org/zap"
11 | "sync/atomic"
12 | )
13 |
14 | type PumpSignalLoopWorker struct {
15 | RunningFlag atomic.Bool // is running? true:running false:stoped
16 | ExitedFlag chan struct{} // 已经退出的标识
17 | ExitChan chan struct{}
18 | }
19 |
20 | func NewPumpSignalLoopWorker() *PumpSignalLoopWorker {
21 | worker := PumpSignalLoopWorker{ExitChan: make(chan struct{})}
22 | worker.RunningFlag.Store(true)
23 | worker.ExitedFlag = make(chan struct{})
24 | return &worker
25 | }
26 |
27 | func (w *PumpSignalLoopWorker) Start() {
28 | zlog.Info("[start]PumpSignalLoopWorker")
29 | w.PumpSignalLoop()
30 | }
31 |
32 | func (w *PumpSignalLoopWorker) Stop() {
33 | zlog.Info("PumpSignalLoopWorker exit...")
34 | w.RunningFlag.Store(false)
35 | close(w.ExitChan)
36 |
37 | <-w.ExitedFlag
38 | zlog.Info("[end]PumpSignalLoopWorker")
39 | }
40 |
41 | func (w *PumpSignalLoopWorker) PumpSignalLoop() {
42 | for w.RunningFlag.Load() {
43 | select {
44 | case msg := <-resource.WaitToBrokerSignalChan:
45 | pumpSignalToBroker(msg)
46 | case <-w.ExitChan:
47 | break
48 | }
49 | }
50 | close(w.ExitedFlag)
51 | }
52 |
53 | func pumpSignalToBroker(msg *pb.PushSignal) bool {
54 | var client pb.BrokerClient
55 | var err error
56 | var ok bool
57 | // 先获取目标所在的broker
58 | account, err := dao.GetAccount(msg.ReceiverId)
59 | if err != nil {
60 | zlog.Error("dao.GetAccount", zap.Error(err))
61 | return false
62 | }
63 | if client, ok = resource.BrokerHub.GetBroker(account.Broker); !ok {
64 | client, err = CreateBrokerClient(account.Broker)
65 | if err != nil {
66 | zlog.Error("CreateBrokerClient fail", zap.Error(err))
67 | return false
68 | }
69 | resource.BrokerHub.SetBroker(account.Broker, client)
70 | }
71 | str, _ := jsoniter.MarshalToString(msg)
72 | zlog.Debug("----2---", zap.String("msg", str))
73 |
74 | resp, err := client.ReceiveMsgSignal(context.Background(), msg)
75 | if err != nil {
76 | zlog.Error("PumpSignalToBroker", zap.Error(err))
77 | return false
78 | }
79 | zlog.Info("PumpSignalToBroker", zap.Int32("code", int32(resp.Code)),
80 | zap.Uint64("ReceiverId", msg.ReceiverId),
81 | zap.String("signalType", pb.SignalTypeEnum_name[int32(msg.SignalType)]))
82 |
83 | return true
84 | }
85 |
--------------------------------------------------------------------------------
/internal/engine/logic/token.go:
--------------------------------------------------------------------------------
1 | package logic
2 |
3 | import "math/rand"
4 |
5 | const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
6 |
7 | func RandStringBytes(n int) string {
8 | b := make([]byte, n)
9 | for i := range b {
10 | b[i] = letterBytes[rand.Intn(len(letterBytes))]
11 | }
12 | return string(b)
13 | }
14 |
--------------------------------------------------------------------------------
/internal/log/init.go:
--------------------------------------------------------------------------------
1 | package log
2 |
3 | import (
4 | "github.com/vearne/chat/internal/config"
5 | "go.uber.org/zap"
6 | "go.uber.org/zap/zapcore"
7 | "gopkg.in/natefinch/lumberjack.v2"
8 | )
9 |
10 | var DefaultLogger *zap.Logger
11 |
12 | func InitLogger(logConfig *config.LogConfig) {
13 | alevel := zap.NewAtomicLevel()
14 | hook := lumberjack.Logger{
15 | Filename: logConfig.FilePath,
16 | MaxSize: 100, // megabytes
17 | MaxBackups: 3,
18 | MaxAge: 7, //days
19 | Compress: true, // disabled by default
20 | }
21 | w := zapcore.AddSync(&hook)
22 |
23 | switch logConfig.Level {
24 | case "debug":
25 | alevel.SetLevel(zap.DebugLevel)
26 | case "info":
27 | alevel.SetLevel(zap.InfoLevel)
28 | case "error":
29 | alevel.SetLevel(zap.ErrorLevel)
30 | default:
31 | alevel.SetLevel(zap.InfoLevel)
32 | }
33 |
34 | encoderConfig := zap.NewProductionEncoderConfig()
35 | encoderConfig.EncodeTime = zapcore.TimeEncoderOfLayout("2006-01-02 15:04:05")
36 | encoderConfig.ConsoleSeparator = " | "
37 |
38 | core := zapcore.NewCore(
39 | zapcore.NewConsoleEncoder(encoderConfig),
40 | w,
41 | alevel,
42 | )
43 |
44 | DefaultLogger = zap.New(core)
45 | DefaultLogger = DefaultLogger.WithOptions(zap.AddCaller(), zap.AddCallerSkip(1))
46 | DefaultLogger.Info("DefaultLogger init success")
47 | }
48 |
49 | func Debug(msg string, fields ...zapcore.Field) {
50 | DefaultLogger.Debug(msg, fields...)
51 | }
52 |
53 | func Info(msg string, fields ...zapcore.Field) {
54 | DefaultLogger.Info(msg, fields...)
55 | }
56 |
57 | func Warn(msg string, fields ...zapcore.Field) {
58 | DefaultLogger.Warn(msg, fields...)
59 | }
60 |
61 | func Error(msg string, fields ...zapcore.Field) {
62 | DefaultLogger.Error(msg, fields...)
63 | }
64 |
65 | func Fatal(msg string, fields ...zapcore.Field) {
66 | DefaultLogger.Fatal(msg, fields...)
67 | }
68 |
69 | func Sync() error {
70 | return DefaultLogger.Sync()
71 | }
72 |
--------------------------------------------------------------------------------
/internal/middleware/ratelimit.go:
--------------------------------------------------------------------------------
1 | package middleware
2 |
3 | import (
4 | "golang.org/x/time/rate"
5 | )
6 |
7 | type TokenBucketLimiter struct {
8 | *rate.Limiter
9 | }
10 |
11 | func NewTokenBucketLimiter(r rate.Limit, b int) *TokenBucketLimiter {
12 | t := TokenBucketLimiter{}
13 | t.Limiter = rate.NewLimiter(r, b)
14 | return &t
15 | }
16 | func (t *TokenBucketLimiter) Limit() bool {
17 | return !t.Allow()
18 | }
19 |
--------------------------------------------------------------------------------
/internal/middleware/record_req.go:
--------------------------------------------------------------------------------
1 | package middleware
2 |
3 | import (
4 | "context"
5 | "encoding/json"
6 | "google.golang.org/grpc"
7 | "log"
8 |
9 | //"google.golang.org/grpc/codes"
10 | //"google.golang.org/grpc/status"
11 | "io"
12 | )
13 |
14 | // 记录grpc请求
15 | func UnaryServerInterceptor(writer io.Writer) grpc.UnaryServerInterceptor {
16 | return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
17 | //if limiter.Limit() {
18 | // return nil, status.Errorf(codes.ResourceExhausted, "%s is rejected by grpc_ratelimit middleware, please retry later.", info.FullMethod)
19 | //}
20 |
21 | bt, _ := json.Marshal(req)
22 | log.Println("FullMethod", info.FullMethod, string(bt))
23 | //log.Println("FullMethod", info.Server)
24 | return handler(ctx, req)
25 | }
26 | }
27 |
28 | func StreamServerInterceptor(writer io.Writer) grpc.StreamServerInterceptor {
29 | return func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
30 | //if limiter.Limit() {
31 | // return status.Errorf(codes.ResourceExhausted, "%s is rejected by grpc_ratelimit middleware, please retry later.", info.FullMethod)
32 | //}
33 | //bt, _ := json.Marshal(stream.)
34 | //log.Println("FullMethod", info.FullMethod, string(bt))
35 | return handler(srv, stream)
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/internal/resolver/srv/srv_resolver.go:
--------------------------------------------------------------------------------
1 | package srv
2 |
3 | import (
4 | "context"
5 | "errors"
6 | "fmt"
7 | "google.golang.org/grpc/grpclog"
8 | "google.golang.org/grpc/resolver"
9 | "net"
10 | "strconv"
11 | "sync"
12 | "time"
13 | )
14 |
15 | var logger = grpclog.Component("dns")
16 |
17 | var (
18 | errMissingAddr = errors.New("dns resolver: missing address")
19 |
20 | // Addresses ending with a colon that is supposed to be the separator
21 | // between host and port is not allowed. E.g. "::" is a valid address as
22 | // it is an IPv6 address (host only) and "[::]:" is invalid as it ends with
23 | // a colon as the host and port separator
24 | errEndsWithColon = errors.New("dns resolver: missing port after port-separator colon")
25 |
26 | defaultResolver netResolver = net.DefaultResolver
27 | minDNSResRate = 10 * time.Second
28 | )
29 |
30 | type netResolver interface {
31 | LookupHost(ctx context.Context, host string) (addrs []string, err error)
32 | LookupSRV(ctx context.Context, service, proto, name string) (cname string, addrs []*net.SRV, err error)
33 | LookupTXT(ctx context.Context, name string) (txts []string, err error)
34 | }
35 |
36 | func init() {
37 | resolver.Register(NewSRVBuilder())
38 | }
39 |
40 | func NewSRVBuilder() resolver.Builder {
41 | return &srvBuilder{}
42 | }
43 |
44 | type srvBuilder struct{}
45 |
46 | // Build creates and starts a DNS resolver that watches the name resolution of the target.
47 | func (b *srvBuilder) Build(target resolver.Target, cc resolver.ClientConn, opts resolver.BuildOptions) (resolver.Resolver, error) {
48 | host, port, err := parseTarget(target.Endpoint(), "8080")
49 | if err != nil {
50 | return nil, err
51 | }
52 |
53 | // IP address.
54 | if ipAddr, ok := formatIP(host); ok {
55 | addr := []resolver.Address{{Addr: ipAddr + ":" + port}}
56 | err = cc.UpdateState(resolver.State{Addresses: addr})
57 | return deadResolver{}, err
58 | }
59 |
60 | // DNS address (non-IP).
61 | ctx, cancel := context.WithCancel(context.Background())
62 | d := &srvResolver{
63 | host: host,
64 | port: port,
65 | ctx: ctx,
66 | cancel: cancel,
67 | cc: cc,
68 | rn: make(chan struct{}, 1),
69 | disableServiceConfig: opts.DisableServiceConfig,
70 | }
71 |
72 | d.resolver = defaultResolver
73 | d.wg.Add(1)
74 | go d.watcher()
75 | return d, nil
76 | }
77 |
78 | // Scheme returns the naming scheme of this resolver builder, which is "dns".
79 | func (b *srvBuilder) Scheme() string {
80 | return "srv"
81 | }
82 |
83 | // dnsResolver watches for the name resolution update for a non-IP target.
84 | type srvResolver struct {
85 | host string
86 | port string
87 | resolver netResolver
88 | ctx context.Context
89 | cancel context.CancelFunc
90 | cc resolver.ClientConn
91 | // rn channel is used by ResolveNow() to force an immediate resolution of the target.
92 | rn chan struct{}
93 | // wg is used to enforce Close() to return after the watcher() goroutine has finished.
94 | // Otherwise, data race will be possible. [Race Example] in dns_resolver_test we
95 | // replace the real lookup functions with mocked ones to facilitate testing.
96 | // If Close() doesn't wait for watcher() goroutine finishes, race detector sometimes
97 | // will warns lookup (READ the lookup function pointers) inside watcher() goroutine
98 | // has data race with replaceNetFunc (WRITE the lookup function pointers).
99 | wg sync.WaitGroup
100 | disableServiceConfig bool
101 | }
102 |
103 | func (d *srvResolver) Close() {
104 | d.cancel()
105 | d.wg.Wait()
106 | }
107 |
108 | // ResolveNow invoke an immediate resolution of the target that this dnsResolver watches.
109 | func (d *srvResolver) ResolveNow(resolver.ResolveNowOptions) {
110 | select {
111 | case d.rn <- struct{}{}:
112 | default:
113 | }
114 | }
115 |
116 | func (d *srvResolver) watcher() {
117 | defer d.wg.Done()
118 | backoffIndex := 1
119 | for {
120 | state, err := d.lookup()
121 | if err != nil {
122 | // Report error to the underlying grpc.ClientConn.
123 | d.cc.ReportError(err)
124 | } else {
125 | err = d.cc.UpdateState(*state)
126 | }
127 |
128 | var timer *time.Timer
129 | if err == nil {
130 | // Success resolving, wait for the next ResolveNow. However, also wait 30 seconds at the very least
131 | // to prevent constantly re-resolving.
132 | backoffIndex = 1
133 | timer = time.NewTimer(minDNSResRate)
134 | select {
135 | case <-d.ctx.Done():
136 | timer.Stop()
137 | return
138 | case <-d.rn:
139 | }
140 | } else {
141 | timer = time.NewTimer(time.Second * 3)
142 | backoffIndex++
143 | }
144 | select {
145 | case <-d.ctx.Done():
146 | timer.Stop()
147 | return
148 | case <-timer.C:
149 | }
150 | }
151 | }
152 |
153 | func (d *srvResolver) lookup() (*resolver.State, error) {
154 | srvs, srvErr := d.lookupSRV()
155 | if srvErr != nil || len(srvs) == 0 {
156 | return nil, srvErr
157 | }
158 |
159 | addrs := make([]resolver.Address, 0, len(srvs))
160 | for _, srv := range srvs {
161 | addrs = append(addrs, resolver.Address{Addr: srv.Addr, ServerName: srv.ServerName})
162 | }
163 | state := resolver.State{Addresses: addrs}
164 | return &state, nil
165 | }
166 |
167 | func (d *srvResolver) lookupSRV() ([]resolver.Address, error) {
168 | var newAddrs []resolver.Address
169 | _, srvs, err := d.resolver.LookupSRV(d.ctx, "grpclb", "tcp", d.host)
170 | if err != nil {
171 | err = handleDNSError(err, "SRV") // may become nil
172 | return nil, err
173 | }
174 | for _, s := range srvs {
175 | lbAddrs, err := d.resolver.LookupHost(d.ctx, s.Target)
176 | if err != nil {
177 | err = handleDNSError(err, "A") // may become nil
178 | if err == nil {
179 | // If there are other SRV records, look them up and ignore this
180 | // one that does not exist.
181 | continue
182 | }
183 | return nil, err
184 | }
185 | for _, a := range lbAddrs {
186 | ip, ok := formatIP(a)
187 | if !ok {
188 | return nil, fmt.Errorf("dns: error parsing A record IP address %v", a)
189 | }
190 | addr := ip + ":" + strconv.Itoa(int(s.Port))
191 | newAddrs = append(newAddrs, resolver.Address{Addr: addr, ServerName: s.Target})
192 | }
193 | }
194 | return newAddrs, nil
195 | }
196 |
197 | func handleDNSError(err error, lookupType string) error {
198 | err = filterError(err)
199 | if err != nil {
200 | err = fmt.Errorf("dns: %v record lookup error: %v", lookupType, err)
201 | logger.Info(err)
202 | }
203 | return err
204 | }
205 |
206 | var filterError = func(err error) error {
207 | if dnsErr, ok := err.(*net.DNSError); ok && !dnsErr.IsTimeout && !dnsErr.IsTemporary {
208 | // Timeouts and temporary errors should be communicated to gRPC to
209 | // attempt another DNS query (with backoff). Other errors should be
210 | // suppressed (they may represent the absence of a TXT record).
211 | return nil
212 | }
213 | return err
214 | }
215 |
216 | // deadResolver is a resolver that does nothing.
217 | type deadResolver struct{}
218 |
219 | func (deadResolver) ResolveNow(resolver.ResolveNowOptions) {}
220 |
221 | func (deadResolver) Close() {}
222 |
223 | // formatIP returns ok = false if addr is not a valid textual representation of an IP address.
224 | // If addr is an IPv4 address, return the addr and ok = true.
225 | // If addr is an IPv6 address, return the addr enclosed in square brackets and ok = true.
226 | func formatIP(addr string) (addrIP string, ok bool) {
227 | ip := net.ParseIP(addr)
228 | if ip == nil {
229 | return "", false
230 | }
231 | if ip.To4() != nil {
232 | return addr, true
233 | }
234 | return "[" + addr + "]", true
235 | }
236 |
237 | // parseTarget takes the user input target string and default port, returns formatted host and port info.
238 | // If target doesn't specify a port, set the port to be the defaultPort.
239 | // If target is in IPv6 format and host-name is enclosed in square brackets, brackets
240 | // are stripped when setting the host.
241 | // examples:
242 | // target: "www.google.com" defaultPort: "443" returns host: "www.google.com", port: "443"
243 | // target: "ipv4-host:80" defaultPort: "443" returns host: "ipv4-host", port: "80"
244 | // target: "[ipv6-host]" defaultPort: "443" returns host: "ipv6-host", port: "443"
245 | // target: ":80" defaultPort: "443" returns host: "localhost", port: "80"
246 | func parseTarget(target, defaultPort string) (host, port string, err error) {
247 | if target == "" {
248 | return "", "", errMissingAddr
249 | }
250 | if ip := net.ParseIP(target); ip != nil {
251 | // target is an IPv4 or IPv6(without brackets) address
252 | return target, defaultPort, nil
253 | }
254 | if host, port, err = net.SplitHostPort(target); err == nil {
255 | if port == "" {
256 | // If the port field is empty (target ends with colon), e.g. "[::1]:", this is an error.
257 | return "", "", errEndsWithColon
258 | }
259 | // target has port, i.e ipv4-host:port, [ipv6-host]:port, host-name:port
260 | if host == "" {
261 | // Keep consistent with net.Dial(): If the host is empty, as in ":80", the local system is assumed.
262 | host = "localhost"
263 | }
264 | return host, port, nil
265 | }
266 | if host, port, err = net.SplitHostPort(target + ":" + defaultPort); err == nil {
267 | // target doesn't have port
268 | return host, port, nil
269 | }
270 | return "", "", fmt.Errorf("invalid target address %v, error info: %v", target, err)
271 | }
272 |
--------------------------------------------------------------------------------
/internal/resource/base.go:
--------------------------------------------------------------------------------
1 | package resource
2 |
3 | var (
4 | ServiceDebug bool
5 | )
6 |
--------------------------------------------------------------------------------
/internal/resource/broker.go:
--------------------------------------------------------------------------------
1 | package resource
2 |
3 | import (
4 | "context"
5 | "encoding/json"
6 | "fmt"
7 | "github.com/fatih/color"
8 | grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
9 | grpc_retry "github.com/grpc-ecosystem/go-grpc-middleware/retry"
10 | "github.com/vearne/chat/internal/config"
11 | zlog "github.com/vearne/chat/internal/log"
12 | "github.com/vearne/chat/model"
13 | pb "github.com/vearne/chat/proto"
14 | "go.uber.org/zap"
15 | "google.golang.org/grpc"
16 | "google.golang.org/grpc/balancer/roundrobin"
17 | "google.golang.org/grpc/codes"
18 | "google.golang.org/grpc/credentials/insecure"
19 | "google.golang.org/grpc/keepalive"
20 | "google.golang.org/grpc/peer"
21 | "time"
22 | )
23 |
24 | // ------broker-------
25 | var (
26 | LogicClient pb.LogicDealerClient
27 | Hub *model.BizHub
28 | )
29 |
30 | // ################## init #################################
31 | func InitBrokerResource() {
32 | // init Hub
33 | Hub = model.NewBizHub()
34 | var err error
35 | var conn *grpc.ClientConn
36 | ServiceDebug = config.GetBrokerOpts().ServiceDebug
37 |
38 | // logicClient
39 | addr := config.GetBrokerOpts().LogicDealer.Address
40 | zlog.Info("logic addr", zap.String("addr", addr))
41 |
42 | conn, err = CreateGrpcClientConn(addr, 3, time.Second*3, ServiceDebug)
43 | if err != nil {
44 | zlog.Fatal("con't connect to logic", zap.Error(err))
45 | }
46 |
47 | LogicClient = pb.NewLogicDealerClient(conn)
48 | }
49 |
50 | func CreateGrpcClientConn(addr string, maxRetryCount uint, timeout time.Duration, debug bool) (*grpc.ClientConn, error) {
51 | interceptors := make([]grpc.UnaryClientInterceptor, 0)
52 | r := grpc_retry.UnaryClientInterceptor(
53 | grpc_retry.WithCodes(
54 | codes.ResourceExhausted,
55 | codes.Unavailable,
56 | codes.Aborted,
57 | codes.Canceled,
58 | codes.DeadlineExceeded,
59 | ),
60 | grpc_retry.WithMax(maxRetryCount),
61 | grpc_retry.WithPerRetryTimeout(timeout),
62 | )
63 |
64 | interceptors = append(interceptors, r)
65 |
66 | if debug {
67 | interceptors = append(interceptors, DebugInterceptor())
68 | }
69 |
70 | dialOpts := []grpc.DialOption{
71 | grpc.WithTransportCredentials(insecure.NewCredentials()),
72 | grpc.WithDefaultServiceConfig(
73 | fmt.Sprintf(`{"LoadBalancingPolicy": "%s"}`, roundrobin.Name)),
74 | grpc.WithKeepaliveParams(keepalive.ClientParameters{
75 | Time: time.Second * 10,
76 | PermitWithoutStream: true}),
77 | //grpc.WithDefaultCallOptions(grpc.WaitForReady(true)),
78 | grpc.WithUnaryInterceptor(grpc_middleware.ChainUnaryClient(interceptors...)),
79 | }
80 | return grpc.NewClient(addr, dialOpts...)
81 | }
82 |
83 | func DebugInterceptor() grpc.UnaryClientInterceptor {
84 | return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
85 | start := time.Now()
86 | p := peer.Peer{}
87 | opts = append(opts, grpc.Peer(&p))
88 | err := invoker(ctx, method, req, reply, cc, opts...)
89 | fmt.Println("addr:", p.Addr)
90 | color.Red("Call service: %s@%s (%s)", method, p.Addr, time.Since(start))
91 |
92 | data, _ := json.MarshalIndent(req, "", " ")
93 | color.Cyan("Request(%s): %s", method, data)
94 |
95 | if err == nil {
96 | data, _ = json.MarshalIndent(reply, "", " ")
97 | color.Cyan("Response(%s): %s", method, data)
98 | } else {
99 | color.Cyan("Response(%s): error %v", method, err)
100 | }
101 |
102 | return err
103 | }
104 | }
105 |
--------------------------------------------------------------------------------
/internal/resource/logic.go:
--------------------------------------------------------------------------------
1 | package resource
2 |
3 | import (
4 | config2 "github.com/vearne/chat/internal/config"
5 | zlog "github.com/vearne/chat/internal/log"
6 | "github.com/vearne/chat/model"
7 | pb "github.com/vearne/chat/proto"
8 | "go.uber.org/zap"
9 | "gorm.io/driver/mysql"
10 | "gorm.io/gorm"
11 | "time"
12 | )
13 |
14 | // -------logic-------
15 | var (
16 | MySQLClient *gorm.DB
17 | )
18 |
19 | var (
20 | WaitToBrokerDialogueChan chan *pb.PushDialogue
21 | WaitToBrokerSignalChan chan *pb.PushSignal
22 | )
23 |
24 | var (
25 | BrokerHub *model.BrokerHub
26 | )
27 |
28 | // ################## init #################################
29 | func InitLogicResource() {
30 | ServiceDebug = config2.GetLogicOpts().ServiceDebug
31 |
32 | initLogicChan()
33 | initMySQL()
34 | initBrokerHub()
35 |
36 | }
37 |
38 | func initBrokerHub() {
39 | zlog.Info("initBrokerHub")
40 | BrokerHub = model.NewBrokerHub()
41 | }
42 |
43 | func initLogicChan() {
44 | zlog.Info("initLogicChan")
45 | WaitToBrokerDialogueChan = make(chan *pb.PushDialogue, 100)
46 | WaitToBrokerSignalChan = make(chan *pb.PushSignal, 100)
47 | }
48 |
49 | func initMySQL() {
50 | zlog.Info("initMySQL")
51 | var err error
52 | MySQLClient, err = initMySQLClientError(config2.GetLogicOpts().MySQLConf)
53 | if err != nil {
54 | zlog.Fatal("Init MySQL error", zap.Error(err))
55 | }
56 | }
57 |
58 | func initMySQLClientError(cf config2.MySQLConf) (*gorm.DB, error) {
59 | mysqldb, err := gorm.Open(mysql.Open(cf.DSN), &gorm.Config{})
60 | if err != nil {
61 | return nil, err
62 | }
63 | if cf.Debug {
64 | mysqldb = mysqldb.Debug()
65 | }
66 |
67 | sqlDB, err := mysqldb.DB()
68 | if err != nil {
69 | zlog.Fatal("initialize MySQL error", zap.Error(err))
70 | }
71 | sqlDB.SetMaxIdleConns(cf.MaxIdleConn)
72 | sqlDB.SetMaxOpenConns(cf.MaxOpenConn)
73 | sqlDB.SetConnMaxLifetime(time.Duration(cf.ConnMaxLifeSecs) * time.Second)
74 | // 赋值给全局变量
75 | return mysqldb, nil
76 | }
77 |
--------------------------------------------------------------------------------
/internal/utils/addr.go:
--------------------------------------------------------------------------------
1 | package utils
2 |
3 | import (
4 | "errors"
5 | "net"
6 | )
7 |
8 | func GetIP() (string, error){
9 | addrs, err := net.InterfaceAddrs()
10 |
11 | if err != nil {
12 | return "", err
13 | }
14 |
15 | for _, address := range addrs {
16 | // 检查ip地址判断是否回环地址
17 | if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
18 | if ipnet.IP.To4() != nil {
19 | return ipnet.IP.String(), nil
20 | }
21 |
22 | }
23 | }
24 | return "", errors.New("can't find ip")
25 | }
--------------------------------------------------------------------------------
/internal/utils/chat.go:
--------------------------------------------------------------------------------
1 | package utils
2 |
3 | type IdResult struct {
4 | IdList []uint64 `json:"id_list"`
5 | }
6 |
--------------------------------------------------------------------------------
/internal/utils/utils.go:
--------------------------------------------------------------------------------
1 | package utils
2 |
3 | func AssembleCmdReq(cmd string) string {
4 | return cmd + "_REQ"
5 | }
6 |
7 | func AssembleCmdResp(cmd string) string {
8 | return cmd + "_RESP"
9 | }
10 |
--------------------------------------------------------------------------------
/internal/utils/wait_group_wrapper.go:
--------------------------------------------------------------------------------
1 | package utils
2 |
3 | import (
4 | "sync"
5 | )
6 |
7 | type WaitGroupWrapper struct {
8 | sync.WaitGroup
9 | }
10 |
11 | func (w *WaitGroupWrapper) Wrap(cb func()) {
12 | w.Add(1)
13 | go func() {
14 | cb()
15 | w.Done()
16 | }()
17 | }
18 |
--------------------------------------------------------------------------------
/model/broker.go:
--------------------------------------------------------------------------------
1 | package model
2 |
3 | import (
4 | "encoding/json"
5 | "gopkg.in/olahol/melody.v1"
6 | "sync"
7 | "time"
8 | )
9 |
10 | // melody.Session keys 是一个Map,多线程处理有并发问题
11 | type BizHub struct {
12 | sync.RWMutex
13 | clientMap map[uint64]*Client
14 | }
15 |
16 | func NewBizHub() *BizHub {
17 | h := BizHub{}
18 | h.clientMap = make(map[uint64]*Client, 10)
19 | return &h
20 | }
21 |
22 | func (h *BizHub) SetClient(nickName string, accountId uint64, session *melody.Session) {
23 | h.Lock()
24 | defer h.Unlock()
25 | h.clientMap[accountId] = NewClient(nickName, accountId, session)
26 | }
27 |
28 | func (h *BizHub) RemoveClient(accountId uint64) {
29 | h.Lock()
30 | defer h.Unlock()
31 |
32 | delete(h.clientMap, accountId)
33 | }
34 |
35 | func (h *BizHub) GetClient(accountId uint64) (*Client, bool) {
36 | h.RLock()
37 | defer h.RUnlock()
38 | client, ok := h.clientMap[accountId]
39 | return client, ok
40 | }
41 |
42 | func (h *BizHub) SetLastPong(accountId uint64, t time.Time) {
43 | h.Lock()
44 | defer h.Unlock()
45 | if client, ok := h.clientMap[accountId]; ok {
46 | client.LastPong = t
47 | }
48 | }
49 |
50 | func (h *BizHub) GetAllClient() []*Client {
51 | h.RLock()
52 | defer h.RUnlock()
53 | res := make([]*Client, 0, len(h.clientMap))
54 | for _, v := range h.clientMap {
55 | res = append(res, v)
56 | }
57 | return res
58 | }
59 |
60 | type Client struct {
61 | Session *melody.Session `json:"-"`
62 |
63 | NickName string `json:"nickName"`
64 | AccountId uint64 `json:"accountId"`
65 | LastPong time.Time `json:"lastPong"`
66 | }
67 |
68 | func NewClient(nickName string, accountId uint64, session *melody.Session) *Client {
69 | c := Client{NickName: nickName, AccountId: accountId, Session: session}
70 | c.LastPong = time.Now()
71 | return &c
72 | }
73 |
74 | func (s *Client) Write(obj any) error {
75 | bt, err := json.Marshal(obj)
76 | if err != nil {
77 | return err
78 | }
79 | return s.Session.Write(bt)
80 | }
81 |
82 | type SessionWrapper struct {
83 | Session *melody.Session `json:"-"`
84 | }
85 |
86 | func NewSessionWrapper(s *melody.Session) *SessionWrapper {
87 | return &SessionWrapper{Session: s}
88 | }
89 |
90 | func (s *SessionWrapper) Write(obj any) error {
91 | bt, err := json.Marshal(obj)
92 | if err != nil {
93 | return err
94 | }
95 | return s.Session.Write(bt)
96 | }
97 |
--------------------------------------------------------------------------------
/model/dto.go:
--------------------------------------------------------------------------------
1 | package model
2 |
3 | import (
4 | "github.com/vearne/chat/consts"
5 | "github.com/vearne/chat/internal/utils"
6 | pb "github.com/vearne/chat/proto"
7 | )
8 |
9 | type CommonCmd struct {
10 | Cmd string `json:"cmd"`
11 | }
12 |
13 | type BaseRespCmd struct {
14 | Cmd string `json:"cmd"`
15 | Code int32 `json:"code"`
16 | }
17 |
18 | type CmdCreateAccountReq struct {
19 | Cmd string `json:"cmd"`
20 | NickName string `json:"nickName"`
21 | }
22 |
23 | func NewCmdCreateAccountReq() *CmdCreateAccountReq {
24 | var cmd CmdCreateAccountReq
25 | cmd.Cmd = utils.AssembleCmdReq(consts.CmdCreateAccount)
26 | return &cmd
27 | }
28 |
29 | type CmdCreateAccountResp struct {
30 | BaseRespCmd
31 | NickName string `json:"nickName"`
32 | AccountId uint64 `json:"accountId"`
33 | Token string `json:"token"`
34 | }
35 |
36 | func NewCmdCreateAccountResp() *CmdCreateAccountResp {
37 | var cmd CmdCreateAccountResp
38 | cmd.Cmd = utils.AssembleCmdResp(consts.CmdCreateAccount)
39 | return &cmd
40 | }
41 |
42 | type CmdMatchReq struct {
43 | Cmd string `json:"cmd"`
44 | AccountId uint64 `json:"accountId"`
45 | }
46 |
47 | func NewCmdMatchReq() *CmdMatchReq {
48 | var cmd CmdMatchReq
49 | cmd.Cmd = utils.AssembleCmdReq(consts.CmdMatch)
50 | return &cmd
51 | }
52 |
53 | type CmdMatchResp struct {
54 | BaseRespCmd
55 | PartnerId uint64 `json:"partnerId,omitempty"`
56 | PartnerName string `json:"partnerName,omitempty"`
57 | SessionId uint64 `json:"sessionId,omitempty"`
58 | }
59 |
60 | func NewCmdMatchResp() *CmdMatchResp {
61 | var cmd CmdMatchResp
62 | cmd.Cmd = utils.AssembleCmdResp(consts.CmdMatch)
63 | return &cmd
64 | }
65 |
66 | type CmdDialogueReq struct {
67 | Cmd string `json:"cmd"`
68 | RequestId string `json:"requestId"`
69 | SenderId uint64 `json:"senderId"`
70 | SessionId uint64 `json:"sessionId"`
71 | Content string `json:"content"`
72 | }
73 |
74 | func NewCmdDialogueReq() *CmdDialogueReq {
75 | var cmd CmdDialogueReq
76 | cmd.Cmd = utils.AssembleCmdReq(consts.CmdDialogue)
77 | return &cmd
78 | }
79 |
80 | type CmdDialogueResp struct {
81 | BaseRespCmd
82 | RequestId string `json:"requestId"`
83 | MsgId uint64 `json:"msgId"`
84 | }
85 |
86 | func NewCmdDialogueResp() *CmdDialogueResp {
87 | var cmd CmdDialogueResp
88 | cmd.Cmd = utils.AssembleCmdResp(consts.CmdDialogue)
89 | return &cmd
90 | }
91 |
92 | type CmdPushDialogueReq struct {
93 | Cmd string `json:"cmd"`
94 | MsgId uint64 `json:"msgId"`
95 | SenderId uint64 `json:"senderId"`
96 | SessionId uint64 `json:"sessionId"`
97 | Content string `json:"content"`
98 | }
99 |
100 | func NewCmdPushDialogueReq() *CmdPushDialogueReq {
101 | var cmd CmdPushDialogueReq
102 | cmd.Cmd = utils.AssembleCmdReq(consts.CmdPushDialogue)
103 | return &cmd
104 | }
105 |
106 | type CmdPushDialogueResp struct {
107 | BaseRespCmd
108 | }
109 |
110 | func NewCmdPushDialogueResp() *CmdPushDialogueResp {
111 | var cmd CmdPushDialogueResp
112 | cmd.Cmd = utils.AssembleCmdResp(consts.CmdPushDialogue)
113 | return &cmd
114 | }
115 |
116 | type CmdPushSignalReq struct {
117 | Cmd string `json:"cmd"`
118 | SenderId uint64 `json:"senderId"`
119 | SessionId uint64 `json:"sessionId"`
120 | ReceiverId uint64 `json:"receiverId"`
121 | SignalType string `json:"signalType"`
122 | Data interface{} `json:"data"`
123 | }
124 |
125 | func NewCmdPushSignalReq() *CmdPushSignalReq {
126 | var cmd CmdPushSignalReq
127 | cmd.Cmd = utils.AssembleCmdReq(consts.CmdPushSignal)
128 | return &cmd
129 | }
130 |
131 | type CmdPushSignalResp struct {
132 | BaseRespCmd
133 | }
134 |
135 | func NewCmdPushSignalResp() *CmdPushSignalResp {
136 | var cmd CmdPushSignalResp
137 | cmd.Cmd = utils.AssembleCmdResp(consts.CmdPushSignal)
138 | return &cmd
139 | }
140 |
141 | // 由broker发出
142 | /*
143 | {
144 | "cmd": "PING_REQ",
145 | "accountId": 12000
146 | }
147 | */
148 | type CmdPingReq struct {
149 | Cmd string `json:"cmd"`
150 | AccountId uint64 `json:"accountId"`
151 | }
152 |
153 | func NewCmdPingReq() *CmdPingReq {
154 | var cmd CmdPingReq
155 | cmd.Cmd = utils.AssembleCmdReq(consts.CmdPing)
156 | return &cmd
157 | }
158 |
159 | // 由Client发出
160 | /*
161 | {
162 | "cmd": "PING_RESP"
163 | "accountId": 12000
164 | }
165 | */
166 | type CmdPingResp struct {
167 | Cmd string `json:"cmd"`
168 | AccountId uint64 `json:"accountId"`
169 | }
170 |
171 | func NewCmdPingResp() *CmdPingResp {
172 | var cmd CmdPingResp
173 | cmd.Cmd = utils.AssembleCmdResp(consts.CmdPing)
174 | return &cmd
175 | }
176 |
177 | type CmdViewedAckReq struct {
178 | Cmd string `json:"cmd"`
179 | SessionId uint64 `json:"sessionId"`
180 | AccountId uint64 `json:"accountId"`
181 | MsgId uint64 `json:"MsgId"`
182 | }
183 |
184 | func NewCmdViewedAckReq() *CmdViewedAckReq {
185 | var cmd CmdViewedAckReq
186 | cmd.Cmd = utils.AssembleCmdReq(consts.CmdViewedAck)
187 | return &cmd
188 | }
189 |
190 | type CmdViewedAckResp struct {
191 | BaseRespCmd
192 | }
193 |
194 | func NewCmdViewedAckResp() *CmdViewedAckResp {
195 | var cmd CmdViewedAckResp
196 | cmd.Cmd = utils.AssembleCmdResp(consts.CmdViewedAck)
197 | return &cmd
198 | }
199 |
200 | type CmdPushViewedAckReq struct {
201 | Cmd string `json:"cmd"`
202 | SessionId uint64 `json:"sessionId"`
203 | AccountId uint64 `json:"accountId"`
204 | MsgId uint64 `json:"msgId"`
205 | }
206 |
207 | func NewCmdPushViewedAckReq() *CmdPushViewedAckReq {
208 | var cmd CmdPushViewedAckReq
209 | cmd.Cmd = utils.AssembleCmdReq(consts.CmdPushViewedAck)
210 | return &cmd
211 | }
212 |
213 | type CmdReConnectReq struct {
214 | Cmd string `json:"cmd"`
215 | AccountId uint64 `json:"accountId"`
216 | Token string `json:"token"`
217 | }
218 |
219 | func NewCmdReConnectReq() *CmdReConnectReq {
220 | var cmd CmdReConnectReq
221 | cmd.Cmd = utils.AssembleCmdReq(consts.CmdReConnect)
222 | return &cmd
223 | }
224 |
225 | type CmdReConnectResp struct {
226 | BaseRespCmd
227 | }
228 |
229 | func NewCmdReConnectResp() *CmdReConnectResp {
230 | var cmd CmdReConnectResp
231 | cmd.Cmd = utils.AssembleCmdResp(consts.CmdReConnect)
232 | return &cmd
233 | }
234 |
235 | type BrokerInfo struct {
236 | Addr string
237 | Client pb.BrokerClient
238 | }
239 |
--------------------------------------------------------------------------------
/model/logic.go:
--------------------------------------------------------------------------------
1 | package model
2 |
3 | import (
4 | pb "github.com/vearne/chat/proto"
5 | "sync"
6 | )
7 |
8 | // melody.Session keys 是一个Map,多线程处理有并发问题
9 | type BrokerHub struct {
10 | sync.RWMutex
11 | brokerMap map[string]pb.BrokerClient
12 | }
13 |
14 | func NewBrokerHub() *BrokerHub {
15 | h := BrokerHub{}
16 | h.brokerMap = make(map[string]pb.BrokerClient, 10)
17 | return &h
18 | }
19 |
20 | func (h *BrokerHub) GetBroker(brokerAddr string) (pb.BrokerClient, bool) {
21 | h.RLock()
22 | defer h.RUnlock()
23 | client, ok := h.brokerMap[brokerAddr]
24 | if ok {
25 | return client, true
26 | } else {
27 | return nil, false
28 | }
29 | }
30 |
31 | func (h *BrokerHub) SetBroker(brokerAddr string, client pb.BrokerClient) {
32 | h.Lock()
33 | defer h.Unlock()
34 | h.brokerMap[brokerAddr] = client
35 | }
36 |
37 | func (h *BrokerHub) Size() int {
38 | h.RLock()
39 | defer h.RUnlock()
40 | return len(h.brokerMap)
41 | }
42 |
43 | func (h *BrokerHub) GetBrokerList() []BrokerInfo {
44 | h.RLock()
45 | defer h.RUnlock()
46 | ans := make([]BrokerInfo, 0, len(h.brokerMap))
47 | for addr, client := range h.brokerMap {
48 | ans = append(ans, BrokerInfo{Addr: addr, Client: client})
49 | }
50 | return ans
51 | }
52 |
53 | func (h *BrokerHub) RemoveBroker(brokerAddr string) {
54 | h.Lock()
55 | defer h.Unlock()
56 | delete(h.brokerMap, brokerAddr)
57 | }
58 |
--------------------------------------------------------------------------------
/model/orm.go:
--------------------------------------------------------------------------------
1 | package model
2 |
3 | import "time"
4 |
5 | type Account struct {
6 | ID uint64 `gorm:"column:id" json:"id"`
7 | NickName string `gorm:"column:nickname" json:"nickname"`
8 | Status int `gorm:"column:status" json:"status"`
9 | Broker string `gorm:"column:broker" json:"broker"`
10 | Token string `gorm:"column:token" json:"token"`
11 | CreatedAt time.Time `gorm:"column:created_at" json:"-"`
12 | ModifiedAt time.Time `gorm:"column:modified_at" json:"-"`
13 | }
14 |
15 | func (Account) TableName() string {
16 | return "account"
17 | }
18 |
19 | type Session struct {
20 | ID uint64 `gorm:"column:id" json:"id"`
21 | Status int `gorm:"column:status" json:"status"`
22 | CreatedAt time.Time `gorm:"column:created_at" json:"-"`
23 | ModifiedAt time.Time `gorm:"column:modified_at" json:"-"`
24 | }
25 |
26 | func (Session) TableName() string {
27 | return "session"
28 | }
29 |
30 | type SessionAccount struct {
31 | ID uint64 `gorm:"column:id" json:"id"`
32 | SessionId uint64 `gorm:"column:session_id" json:"session_id"`
33 | AccountId uint64 `gorm:"column:account_id" json:"account_id"`
34 | }
35 |
36 | func (SessionAccount) TableName() string {
37 | return "session_account"
38 | }
39 |
40 | type OutBox struct {
41 | ID uint64 `gorm:"column:id" json:"id"`
42 | SenderId uint64 `gorm:"column:sender_id" json:"sender_id"`
43 | SessionId uint64 `gorm:"column:session_id" json:"session_id"`
44 | Status int `gorm:"column:status" json:"status"`
45 | MsgType int `gorm:"column:msg_type" json:"msg_type"`
46 | Content string `gorm:"column:content" json:"content"`
47 | CreatedAt time.Time `gorm:"column:created_at" json:"-"`
48 | ModifiedAt time.Time `gorm:"column:modified_at" json:"-"`
49 | }
50 |
51 | func (OutBox) TableName() string {
52 | return "outbox"
53 | }
54 |
55 | type InBox struct {
56 | ID uint64 `gorm:"column:id" json:"id"`
57 | SenderId uint64 `gorm:"column:sender_id" json:"sender_id"`
58 | MsgId uint64 `gorm:"column:msg_id" json:"msg_id"`
59 | ReceiverId uint64 `gorm:"column:receiver_id" json:"receiver_id"`
60 | }
61 |
62 | func (InBox) TableName() string {
63 | return "inbox"
64 | }
65 |
--------------------------------------------------------------------------------
/proto/README:
--------------------------------------------------------------------------------
1 | # generate a Go protocol buffer package
2 | # 1. install protobuf
3 | ```
4 | brew install protobuf
5 | ```
6 | # 2. Install the protoc-gen-gofast binary
7 | ```
8 | go get github.com/gogo/protobuf/protoc-gen-gofast
9 | ```
10 | # 3. generate a Go protocol buffer package
11 | ```
12 | protoc --gofast_out=plugins=grpc:. *.proto
13 | ```
--------------------------------------------------------------------------------
/proto/broker.proto:
--------------------------------------------------------------------------------
1 | syntax = "proto3";
2 | import "logic.proto";
3 | package proto;
4 |
5 | // The Customer sercie definition
6 | service Broker {
7 | // Receive data pushed by logic
8 | rpc ReceiveMsgDialogue (PushDialogue) returns (PushResp);
9 | rpc ReceiveMsgSignal (PushSignal) returns (PushResp);
10 | rpc HealthCheck (HealthCheckReq) returns (HealthCheckResp);
11 | }
12 |
13 | message HealthCheckReq{
14 | string asker = 1;
15 | }
16 |
17 | message HealthCheckResp{
18 | CodeEnum code = 1;
19 | string msg = 2;
20 | }
21 |
22 | message PushRequest{
23 | uint64 accountId = 1;
24 | }
25 |
26 | message PushResp {
27 | CodeEnum code = 1;
28 | string msg = 2;
29 | }
30 |
31 | message PushDialogue {
32 | uint64 senderId = 1;
33 | uint64 sessionId = 2;
34 | uint64 receiverId = 3;
35 | string content = 4;
36 | uint64 msgId = 5;
37 | }
38 |
39 |
40 | message PushSignal {
41 | SignalTypeEnum signalType = 1;
42 | uint64 senderId = 2;
43 | uint64 receiverId = 3;
44 | uint64 sessionId = 4;
45 | oneof data{
46 | AccountInfo partner = 5;
47 | uint64 msgId = 6;
48 | uint64 accountId = 7;
49 | }
50 | }
51 |
52 | message AccountInfo{
53 | uint64 accountId = 1;
54 | string nickName = 2;
55 | }
56 |
57 | enum SignalTypeEnum {
58 | PartnerExit = 0; // The person you were chatting with disconnected or logged out.
59 | NewSession = 1; // Create session
60 | DeleteMsg = 2; // Delete message
61 | ViewedAck = 3; // Read confirmation
62 | }
63 |
64 |
--------------------------------------------------------------------------------
/proto/logic.proto:
--------------------------------------------------------------------------------
1 | syntax = "proto3";
2 |
3 | package proto;
4 |
5 | // The Customer sercie definition
6 | service LogicDealer {
7 | rpc CreateAccount (CreateAccountRequest) returns (CreateAccountResponse);
8 | rpc Match (MatchRequest) returns (MatchResponse);
9 | rpc SendMsg (SendMsgRequest) returns (SendMsgResponse);
10 | rpc Logout (LogoutRequest) returns (LogoutResponse);
11 | rpc ViewedAck(ViewedAckRequest) returns(ViewedAckResponse);
12 | rpc Reconnect(ReConnectRequest) returns(ReConnectResponse);
13 | }
14 |
15 | message ViewedAckRequest {
16 | uint64 sessionId = 1;
17 | uint64 accountId = 2;
18 | uint64 msgId = 3;
19 |
20 | }
21 |
22 | message ViewedAckResponse {
23 | CodeEnum code = 1;
24 | string msg = 2;
25 | }
26 |
27 | enum CodeEnum {
28 | Success = 0; // success
29 | ParamErr = 1; // parameter error
30 | InternalErr = 2; // internal error
31 | UnknowErr = 3; // unknown error
32 | NoDataFound = 4; // No data found
33 | }
34 |
35 | enum StatusEnum {
36 | Deleted = 0;
37 | Normal = 1;
38 | }
39 |
40 | enum MsgTypeEnum {
41 | Dialogue = 0;
42 | Signal = 1;
43 | }
44 |
45 | message CreateAccountRequest {
46 | string nickname = 1;
47 | string broker = 2;
48 | }
49 |
50 | message CreateAccountResponse {
51 | CodeEnum code = 1;
52 | string msg = 2;
53 | uint64 accountId = 3;
54 | string token = 4;
55 | }
56 |
57 | message MatchRequest {
58 | uint64 accountId = 1;
59 | }
60 |
61 | message MatchResponse {
62 | CodeEnum code = 1;
63 | string msg = 2;
64 |
65 | uint64 partnerId = 3;
66 | string partnerName = 4;
67 | uint64 sessionId = 5;
68 | }
69 |
70 | message SendMsgRequest {
71 | uint64 senderId = 2;
72 | uint64 sessionId = 3;
73 | MsgTypeEnum msgtype = 4;
74 | string content = 5;
75 | }
76 |
77 | message SendMsgResponse {
78 | CodeEnum code = 1;
79 | string msg = 2;
80 | uint64 msgId = 3;
81 | }
82 |
83 | message LogoutRequest {
84 | uint64 accountId = 1;
85 | string broker = 2;
86 | }
87 |
88 | message LogoutResponse {
89 | CodeEnum code = 1;
90 | string msg = 2;
91 | }
92 |
93 | message ReConnectRequest {
94 | uint64 accountId = 1;
95 | string token = 2;
96 | string broker = 3;
97 | }
98 |
99 | message ReConnectResponse {
100 | CodeEnum code = 1;
101 | string msg = 2;
102 | uint64 accountId = 3;
103 | string nickname = 4;
104 | }
--------------------------------------------------------------------------------
/test/mock_client/client.sh:
--------------------------------------------------------------------------------
1 | # list
2 | grpcurl --plaintext 127.0.0.1:18223 list
3 | grpcurl -import-path ../../logic -proto logic.proto list
4 |
5 | # describe
6 | grpcurl --plaintext 127.0.0.1:18223 describe
7 | grpcurl --plaintext 127.0.0.1:18223 describe .proto.LogicDealer
8 | grpcurl --plaintext 127.0.0.1:18223 describe .proto.LogoutResponse
9 | grpcurl --plaintext 127.0.0.1:18223 describe .proto.LogicDealer.CreateAccount
10 | grpcurl --plaintext 127.0.0.1:18223 describe .proto.CreateAccountRequest
11 | grpcurl --plaintext 127.0.0.1:18223 describe .proto.CreateAccountResponse
12 |
13 | # create account
14 | grpcurl --plaintext -d '{"nickname": "zhangsan","broker": "dev1:18080"}'\
15 | 127.0.0.1:18223 proto.LogicDealer/CreateAccount
16 |
17 | grpcurl --plaintext -d '{"nickname": "lisi","broker": "dev1:18080"}'\
18 | 127.0.0.1:18223 proto.LogicDealer/CreateAccount
19 |
20 | # match
21 | grpcurl --plaintext -d '{"accountId":10}'\
22 | 127.0.0.1:18223 proto.LogicDealer/Match
23 |
24 | # ViewedAck
25 | grpcurl --plaintext -d '{"sessionId":110000,"accountId":100,"msgId":20000}'\
26 | 127.0.0.1:18223 proto.LogicDealer/ViewedAck
27 |
--------------------------------------------------------------------------------
/test/test_proto.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "github.com/golang/protobuf/proto"
6 | "github.com/json-iterator/go"
7 |
8 | //"github.com/json-iterator/go"
9 | pb "github.com/vearne/chat/proto"
10 | )
11 |
12 | func main() {
13 | temp := &pb.PushSignal{SenderId: 15,
14 | Data: &pb.PushSignal_Partner{&pb.AccountInfo{AccountId: 15, NickName: "xxxx"}}}
15 | data, err := proto.Marshal(temp)
16 | if err != nil {
17 | fmt.Println(err)
18 | }
19 | target := &pb.PushSignal{}
20 | proto.Unmarshal(data, target)
21 | fmt.Println(jsoniter.MarshalToString(target))
22 | }
23 |
--------------------------------------------------------------------------------