Merge remote-tracking branch 'upstream/main'

This commit is contained in:
skiffer-git 2024-03-19 14:33:34 +08:00
commit f1b60397de
158 changed files with 1313 additions and 15704 deletions

View File

@ -0,0 +1,27 @@
# Copyright © 2024 OpenIM. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
name: Language Check Workflow Test
on: [pull_request]
jobs:
comment-language-detector:
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v4
- name: Code Language Detector
uses: kubecub/comment-lang-detector@v1.0.0

View File

@ -12,7 +12,7 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
name: OpenIM Linux System E2E Test name: OpenIM E2E And API Test
on: on:
workflow_dispatch: workflow_dispatch:
@ -82,7 +82,7 @@ jobs:
sudo make tidy sudo make tidy
sudo make tools.verify.go-gitlint sudo make tools.verify.go-gitlint
- name: Build, Start - name: Build, Start(make build && make start)
run: | run: |
sudo ./scripts/install/install.sh -i sudo ./scripts/install/install.sh -i
@ -90,9 +90,8 @@ jobs:
run: | run: |
sudo ./scripts/install/install.sh -s sudo ./scripts/install/install.sh -s
- name: Exec OpenIM API test - name: Exec OpenIM API test (make test-api)
run: | run: |
sudo make test-api
mkdir -p ./tmp mkdir -p ./tmp
touch ./tmp/test.md touch ./tmp/test.md
echo "# OpenIM Test" >> ./tmp/test.md echo "# OpenIM Test" >> ./tmp/test.md
@ -103,9 +102,10 @@ jobs:
echo "</code></pre>" >> ./tmp/test.md echo "</code></pre>" >> ./tmp/test.md
echo "</details>" >> ./tmp/test.md echo "</details>" >> ./tmp/test.md
- name: Exec OpenIM E2E Test sudo make test-api
- name: Exec OpenIM E2E Test (make test-e2e)
run: | run: |
sudo make test-e2e
echo "" >> ./tmp/test.md echo "" >> ./tmp/test.md
echo "## OpenIM E2E Test" >> ./tmp/test.md echo "## OpenIM E2E Test" >> ./tmp/test.md
echo "<details><summary>Command Output for OpenIM E2E Test</summary>" >> ./tmp/test.md echo "<details><summary>Command Output for OpenIM E2E Test</summary>" >> ./tmp/test.md
@ -114,6 +114,8 @@ jobs:
echo "</code></pre>" >> ./tmp/test.md echo "</code></pre>" >> ./tmp/test.md
echo "</details>" >> ./tmp/test.md echo "</details>" >> ./tmp/test.md
sudo make test-e2e
- name: Comment PR with file - name: Comment PR with file
uses: thollander/actions-comment-pull-request@v2 uses: thollander/actions-comment-pull-request@v2
with: with:

View File

@ -745,7 +745,7 @@ linters:
- misspell # Spelling mistakes - misspell # Spelling mistakes
- staticcheck # Static analysis - staticcheck # Static analysis
- unused # Checks for unused code - unused # Checks for unused code
- goimports # Checks if imports are correctly sorted and formatted # - goimports # Checks if imports are correctly sorted and formatted
- godot # Checks for comment punctuation - godot # Checks for comment punctuation
- bodyclose # Ensures HTTP response body is closed - bodyclose # Ensures HTTP response body is closed
- stylecheck # Style checker for Go code - stylecheck # Style checker for Go code

View File

@ -3,16 +3,14 @@ FROM golang:1.20 AS builder
# Set go mod installation source and proxy # Set go mod installation source and proxy
ARG GO111MODULE=on ARG GO111MODULE=on
ARG GOPROXY=https://goproxy.cn,direct ARG GOPROXY=https://goproxy.io,direct
ENV GO111MODULE=$GO111MODULE ENV GO111MODULE=$GO111MODULE
ENV GOPROXY=$GOPROXY ENV GOPROXY=$GOPROXY
# Set up the working directory # Set up the working directory
WORKDIR /openim/openim-server WORKDIR /openim/openim-server
COPY go.mod go.sum ./
RUN go mod download
# Copy all files to the container # Copy all files to the container
ADD . . ADD . .

View File

@ -19,7 +19,7 @@
FROM golang:1.20 AS builder FROM golang:1.20 AS builder
ARG GO111MODULE=on ARG GO111MODULE=on
ARG GOPROXY=https://goproxy.cn,direct ARG GOPROXY=https://goproxy.io,direct
WORKDIR /openim/openim-server WORKDIR /openim/openim-server

View File

@ -19,7 +19,7 @@
FROM golang:1.20 AS builder FROM golang:1.20 AS builder
ARG GO111MODULE=on ARG GO111MODULE=on
ARG GOPROXY=https://goproxy.cn,direct ARG GOPROXY=https://goproxy.io,direct
WORKDIR /openim/openim-server WORKDIR /openim/openim-server

View File

@ -19,7 +19,7 @@
FROM golang:1.20 AS builder FROM golang:1.20 AS builder
ARG GO111MODULE=on ARG GO111MODULE=on
ARG GOPROXY=https://goproxy.cn,direct ARG GOPROXY=https://goproxy.io,direct
WORKDIR /openim/openim-server WORKDIR /openim/openim-server

View File

@ -19,7 +19,7 @@
FROM golang:1.20 AS builder FROM golang:1.20 AS builder
ARG GO111MODULE=on ARG GO111MODULE=on
ARG GOPROXY=https://goproxy.cn,direct ARG GOPROXY=https://goproxy.io,direct
WORKDIR /openim/openim-server WORKDIR /openim/openim-server

View File

@ -19,7 +19,7 @@
FROM golang:1.20 AS builder FROM golang:1.20 AS builder
ARG GO111MODULE=on ARG GO111MODULE=on
ARG GOPROXY=https://goproxy.cn,direct ARG GOPROXY=https://goproxy.io,direct
WORKDIR /openim/openim-server WORKDIR /openim/openim-server

View File

@ -19,7 +19,7 @@
FROM golang:1.20 AS builder FROM golang:1.20 AS builder
ARG GO111MODULE=on ARG GO111MODULE=on
ARG GOPROXY=https://goproxy.cn,direct ARG GOPROXY=https://goproxy.io,direct
WORKDIR /openim/openim-server WORKDIR /openim/openim-server

View File

@ -19,7 +19,7 @@
FROM golang:1.20 AS builder FROM golang:1.20 AS builder
ARG GO111MODULE=on ARG GO111MODULE=on
ARG GOPROXY=https://goproxy.cn,direct ARG GOPROXY=https://goproxy.io,direct
WORKDIR /openim/openim-server WORKDIR /openim/openim-server

View File

@ -19,7 +19,7 @@
FROM golang:1.20 AS builder FROM golang:1.20 AS builder
ARG GO111MODULE=on ARG GO111MODULE=on
ARG GOPROXY=https://goproxy.cn,direct ARG GOPROXY=https://goproxy.io,direct
WORKDIR /openim/openim-server WORKDIR /openim/openim-server

View File

@ -19,7 +19,7 @@
FROM golang:1.20 AS builder FROM golang:1.20 AS builder
ARG GO111MODULE=on ARG GO111MODULE=on
ARG GOPROXY=https://goproxy.cn,direct ARG GOPROXY=https://goproxy.io,direct
WORKDIR /openim/openim-server WORKDIR /openim/openim-server

View File

@ -19,7 +19,7 @@
FROM golang:1.20 AS builder FROM golang:1.20 AS builder
ARG GO111MODULE=on ARG GO111MODULE=on
ARG GOPROXY=https://goproxy.cn,direct ARG GOPROXY=https://goproxy.io,direct
WORKDIR /openim/openim-server WORKDIR /openim/openim-server

View File

@ -19,7 +19,7 @@
FROM golang:1.20 AS builder FROM golang:1.20 AS builder
ARG GO111MODULE=on ARG GO111MODULE=on
ARG GOPROXY=https://goproxy.cn,direct ARG GOPROXY=https://goproxy.io,direct
WORKDIR /openim/openim-server WORKDIR /openim/openim-server

View File

@ -19,7 +19,7 @@
FROM golang:1.20 AS builder FROM golang:1.20 AS builder
ARG GO111MODULE=on ARG GO111MODULE=on
ARG GOPROXY=https://goproxy.cn,direct ARG GOPROXY=https://goproxy.io,direct
WORKDIR /openim/openim-server WORKDIR /openim/openim-server

View File

@ -19,7 +19,7 @@
FROM golang:1.20 AS builder FROM golang:1.20 AS builder
ARG GO111MODULE=on ARG GO111MODULE=on
ARG GOPROXY=https://goproxy.cn,direct ARG GOPROXY=https://goproxy.io,direct
WORKDIR /openim/openim-server WORKDIR /openim/openim-server

View File

@ -19,7 +19,7 @@
FROM golang:1.20 AS builder FROM golang:1.20 AS builder
ARG GO111MODULE=on ARG GO111MODULE=on
ARG GOPROXY=https://goproxy.cn,direct ARG GOPROXY=https://goproxy.io,direct
WORKDIR /openim/openim-server WORKDIR /openim/openim-server

View File

@ -19,7 +19,7 @@
FROM golang:1.20 AS builder FROM golang:1.20 AS builder
ARG GO111MODULE=on ARG GO111MODULE=on
ARG GOPROXY=https://goproxy.cn,direct ARG GOPROXY=https://goproxy.io,direct
WORKDIR /openim/openim-server WORKDIR /openim/openim-server

View File

@ -186,23 +186,6 @@ services:
# server: # server:
# ipv4_address: ${OPENIM_SERVER_NETWORK_ADDRESS:-172.28.0.8} # ipv4_address: ${OPENIM_SERVER_NETWORK_ADDRESS:-172.28.0.8}
### TODO: mysql is required to deploy the openim-chat component
# mysql:
# image: mysql:${MYSQL_IMAGE_VERSION:-5.7}
# platform: linux/amd64
# ports:
# - "${MYSQL_PORT:-13306}:3306"
# container_name: mysql
# volumes:
# - "${DATA_DIR:-./}/components/mysql/data:/var/lib/mysql"
# - "/etc/localtime:/etc/localtime"
# environment:
# MYSQL_ROOT_PASSWORD: "${MYSQL_PASSWORD:-openIM123}"
# restart: always
# networks:
# server:
# ipv4_address: ${MYSQL_NETWORK_ADDRESS:-172.28.0.15}
# openim-chat: # openim-chat:
# image: ${IMAGE_REGISTRY:-ghcr.io/openimsdk}/openim-chat:${CHAT_IMAGE_VERSION:-main} # image: ${IMAGE_REGISTRY:-ghcr.io/openimsdk}/openim-chat:${CHAT_IMAGE_VERSION:-main}
# container_name: openim-chat # container_name: openim-chat

View File

@ -2,6 +2,8 @@
**PATH:** `scripts/lib/logging.sh` **PATH:** `scripts/lib/logging.sh`
### Introduction ### Introduction
OpenIM, an intricate project, requires a robust logging mechanism to diagnose issues, maintain system health, and provide insights. A custom-built logging system embedded within OpenIM ensures consistent and structured logs. Let's delve into the design of this logging system and understand its various functions and their usage scenarios. OpenIM, an intricate project, requires a robust logging mechanism to diagnose issues, maintain system health, and provide insights. A custom-built logging system embedded within OpenIM ensures consistent and structured logs. Let's delve into the design of this logging system and understand its various functions and their usage scenarios.

View File

@ -266,13 +266,61 @@ errors.New("redis connection failed")
- When specifying ranges of numbers, use inclusive ranges whenever possible. - When specifying ranges of numbers, use inclusive ranges whenever possible.
- Go 1.13 or above is recommended, and the error generation method is `fmt.Errorf("module xxx: %w", err)`. - Go 1.13 or above is recommended, and the error generation method is `fmt.Errorf("module xxx: %w", err)`.
### 1.4 panic processing ### 1.4 Panic Processing
The use of `panic` should be carefully controlled in Go applications to ensure program stability and predictable error handling. Following are revised guidelines emphasizing the restriction on using `panic` and promoting alternative strategies for error handling and program termination.
- **Prohibited in Business Logic:** Using `panic` within business logic processing is strictly prohibited. Business logic should handle errors gracefully and use error returns to propagate issues up the call stack.
- **Restricted Use in Main Package:** In the main package, the use of `panic` should be reserved for situations where the program is entirely inoperable, such as failure to open essential files, inability to connect to the database, or other critical startup issues. Even in these scenarios, prefer using structured error handling to terminate the program.
- **Use `log.Fatal` for Critical Errors:** Instead of panicking, use `log.Fatal` to log critical errors that prevent the program from operating normally. This approach allows the program to terminate while ensuring the error is properly logged for troubleshooting.
- **Prohibition on Exportable Interfaces:** Exportable interfaces must not invoke `panic`. They should handle errors gracefully and return errors as part of their contract.
- **Prefer Errors Over Panic:** It is recommended to use error returns instead of panic to convey errors within a package. This approach promotes error handling that integrates smoothly with Go's error handling idioms.
#### Alternative to Panic: Structured Program Termination
To enforce these guidelines, consider implementing structured functions to terminate the program gracefully in the face of unrecoverable errors, while providing clear error messages. Here are two recommended functions:
```go
// ExitWithError logs an error message and exits the program with a non-zero status.
func ExitWithError(err error) {
progName := filepath.Base(os.Args[0])
fmt.Fprintf(os.Stderr, "%s exit -1: %+v\n", progName, err)
os.Exit(-1)
}
// SIGTERMExit logs a warning message when the program receives a SIGTERM signal and exits with status 0.
func SIGTERMExit() {
progName := filepath.Base(os.Args[0])
fmt.Fprintf(os.Stderr, "Warning %s receive process terminal SIGTERM exit 0\n", progName)
}
```
#### Example Usage:
```go
import (
_ "net/http/pprof"
"github.com/openimsdk/open-im-server/v3/pkg/common/cmd"
util "github.com/openimsdk/open-im-server/v3/pkg/util/genutil"
)
func main() {
apiCmd := cmd.NewApiCmd()
apiCmd.AddPortFlag()
apiCmd.AddPrometheusPortFlag()
if err := apiCmd.Execute(); err != nil {
util.ExitWithError(err)
}
}
```
In this example, `ExitWithError` is used to terminate the program when an unrecoverable error occurs, providing a clear error message to stderr and exiting with a non-zero status. This approach ensures that critical errors are logged and the program exits in a controlled manner, facilitating troubleshooting and maintaining the stability of the application.
- Panic is prohibited in business logic processing.
- In the main package, panic is only used when the program is completely inoperable, for example, the file cannot be opened, the database cannot be connected, and the program cannot run normally.
- In the main package, use `log.Fatal` to record errors, so that the program can be terminated by the log, or the exception thrown by the panic can be recorded in the log file, which is convenient for troubleshooting.
- An exportable interface must not panic.
- It is recommended to use error instead of panic to convey errors in the package.
### 1.5 Unit Tests ### 1.5 Unit Tests
@ -439,10 +487,15 @@ var allowGitHook bool
- Local variables should be as short as possible, for example, use buf to refer to buffer, and use i to refer to index. - Local variables should be as short as possible, for example, use buf to refer to buffer, and use i to refer to index.
- The code automatically generated by the code generation tool can exclude this rule (such as the Id in `xxx.pb.go`) - The code automatically generated by the code generation tool can exclude this rule (such as the Id in `xxx.pb.go`)
### 2.7 Constant naming ### 2.7 Constant Naming
- The constant name must follow the camel case, and the initial letter is uppercase or lowercase according to the access control decision. In Go, constants play a critical role in defining values that do not change throughout the execution of a program. Adhering to best practices in naming constants can significantly improve the readability and maintainability of your code. Here are some guidelines for constant naming:
- If it is a constant of enumeration type, you need to create the corresponding type first:
- **Camel Case Naming:** The name of a constant must follow the camel case notation. The initial letter should be uppercase or lowercase based on the access control requirements. Uppercase indicates that the constant is exported (visible outside the package), while lowercase indicates package-private visibility (visible only within its own package).
- **Enumeration Type Constants:** For constants that represent a set of enumerated values, it's recommended to define a corresponding type first. This approach not only enhances type safety but also improves code readability by clearly indicating the purpose of the enumeration.
**Example:**
```go ```go
// Code defines an error code type. // Code defines an error code type.
@ -452,11 +505,40 @@ type Code int
const ( const (
// ErrUnknown - 0: An unknown error occurred. // ErrUnknown - 0: An unknown error occurred.
ErrUnknown Code = iota ErrUnknown Code = iota
// ErrFatal - 1: An fatal error occurred. // ErrFatal - 1: A fatal error occurred.
ErrFatal ErrFatal
) )
``` ```
In the example above, `Code` is defined as a new type based on `int`. The enumerated constants `ErrUnknown` and `ErrFatal` are then defined with explicit comments to indicate their purpose and values. This pattern is particularly useful for grouping related constants and providing additional context.
### Global Variables and Constants Across Packages
- **Use Constants for Global Variables:** When defining variables that are intended to be accessed across packages, prefer using constants to ensure immutability. This practice avoids unintended modifications to the value, which can lead to unpredictable behavior or hard-to-track bugs.
- **Lowercase for Package-Private Usage:** If a global variable or constant is intended for use only within its own package, it should start with a lowercase letter. This clearly signals its limited scope of visibility, adhering to Go's access control mechanism based on naming conventions.
**Guideline:**
- For global constants that need to be accessed across packages, declare them with an uppercase initial letter. This makes them exported, adhering to Go's visibility rules.
- For constants used within the same package, start their names with a lowercase letter to limit their scope to the package.
**Example:**
```go
package config
// MaxConnections - the maximum number of allowed connections. Visible across packages.
const MaxConnections int = 100
// minIdleTime - the minimum idle time before a connection is considered stale. Only visible within the config package.
const minIdleTime int = 30
```
In this example, `MaxConnections` is a global constant meant to be accessed across packages, hence it starts with an uppercase letter. On the other hand, `minIdleTime` is intended for use only within the `config` package, so it starts with a lowercase letter.
Following these guidelines ensures that your Go code is more readable, maintainable, and consistent with Go's design philosophy and access control mechanisms.
### 2.8 Error naming ### 2.8 Error naming
- The Error type should be written in the form of FooError. - The Error type should be written in the form of FooError.
@ -473,6 +555,190 @@ type ExitError struct {
var ErrFormat = errors. New("unknown format") var ErrFormat = errors. New("unknown format")
``` ```
For non-standard Err naming, CICD will report an error
### 2.9 Handling Errors Properly
In Go, proper error handling is crucial for creating reliable and maintainable applications. It's important to ensure that errors are not ignored or discarded, as this can lead to unpredictable behavior and difficult-to-debug issues. Here are the guidelines and examples regarding the proper handling of errors.
#### Guideline: Do Not Discard Errors
- **Mandatory Error Propagation:** When calling a function that returns an error, the calling function must handle or propagate the error, instead of ignoring it. This approach ensures that errors are not silently ignored, allowing higher-level logic to make informed decisions about error handling.
#### Incorrect Example: Discarding an Error
```go
package main
import (
"io/ioutil"
"log"
)
func ReadFileContent(filename string) string {
content, _ := ioutil.ReadFile(filename) // Incorrect: Error is ignored
return string(content)
}
func main() {
content := ReadFileContent("example.txt")
log.Println(content)
}
```
In this incorrect example, the error returned by `ioutil.ReadFile` is ignored. This can lead to situations where the program continues execution even if the file doesn't exist or cannot be accessed, potentially causing more cryptic errors downstream.
#### Correct Example: Propagating an Error
```go
package main
import (
"io/ioutil"
"log"
)
// ReadFileContent attempts to read and return the content of the specified file.
// It returns an error if reading fails.
func ReadFileContent(filename string) (string, error) {
content, err := ioutil.ReadFile(filename)
if err != nil {
// Correct: Propagate the error
return "", err
}
return string(content), nil
}
func main() {
content, err := ReadFileContent("example.txt")
if err != nil {
log.Fatalf("Failed to read file: %v", err)
}
log.Println(content)
}
```
In the correct example, the error returned by `ioutil.ReadFile` is propagated back to the caller. The `main` function then checks the error and terminates the program with an appropriate error message if an error occurred. This approach ensures that errors are handled appropriately, and the program does not proceed with invalid state.
### Best Practices for Error Handling
1. **Always check the error returned by a function.** Do not ignore it.
2. **Propagate errors up the call stack unless they can be handled gracefully at the current level.**
3. **Provide context for errors when propagating them, making it easier to trace the source of the error.** This can be achieved using `fmt.Errorf` with the `%w` verb or dedicated wrapping functions provided by some error handling packages.
4. **Log the error at the point where it is handled or makes the program to terminate, to provide insight into the failure.**
By following these guidelines, you ensure that your Go applications handle errors in a consistent and effective manner, improving their reliability and maintainability.
### 2.10 Using Context with IO or Inter-Process Communication (IPC)
In Go, `context.Context` is a powerful construct for managing deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes. It is particularly important in I/O operations or inter-process communication (IPC), where operations might need to be cancelled or timed out.
#### Guideline: Use Context for IO and IPC
- **Mandatory Use of Context:** When performing I/O operations or inter-process communication, it's crucial to use `context.Context` to manage the lifecycle of these operations. This includes setting deadlines, handling cancellation signals, and passing request-scoped values.
#### Incorrect Example: Ignoring Context in an HTTP Call
```go
package main
import (
"io/ioutil"
"net/http"
"log"
)
// FetchData makes an HTTP GET request to the specified URL and returns the response body.
// This function does not use context, making it impossible to cancel the request or set a deadline.
func FetchData(url string) (string, error) {
resp, err := http.Get(url) // Incorrect: Ignoring context
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(body), nil
}
func main() {
data, err := FetchData("http://example.com")
if err != nil {
log.Fatalf("Failed to fetch data: %v", err)
}
log.Println(data)
}
```
In this incorrect example, the `FetchData` function makes an HTTP GET request without using a `context`. This approach does not allow the request to be cancelled or a timeout to be set, potentially leading to resources being wasted if the server takes too long to respond or if the operation needs to be aborted for any reason.
#### Correct Example: Using Context in an HTTP Call
```go
package main
import (
"context"
"io/ioutil"
"net/http"
"log"
"time"
)
// FetchDataWithContext makes an HTTP GET request to the specified URL using the provided context.
// This allows the request to be cancelled or timed out according to the context's deadline.
func FetchDataWithContext(ctx context.Context, url string) (string, error) {
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil {
return "", err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(body), nil
}
func main() {
// Create a context with a 5-second timeout
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
data, err := FetchDataWithContext(ctx, "http://example.com")
if err != nil {
log.Fatalf("Failed to fetch data: %v", err)
}
log.Println(data)
}
```
In the correct example, `FetchDataWithContext` uses a context to make the HTTP GET request. This allows the operation to be cancelled or subjected to a timeout, as dictated by the context passed to it. The `context.WithTimeout` function is used in `main` to create a context that cancels the request if it takes longer than 5 seconds, demonstrating a practical use of context to manage operation lifecycle.
### Best Practices for Using Context
1. **Pass context as the first parameter of a function**, following the convention `func(ctx context.Context, ...)`.
2. **Never ignore the context** provided to you in functions that support it. Always use it in your I/O or IPC operations.
3. **Avoid storing context in a struct**. Contexts are meant to be passed around within the call stack, not stored.
4. **Use context's cancellation and deadline features** to control the lifecycle of blocking operations, especially in network I/O and IPC scenarios.
5. **Propagate context down the call stack** to any function that supports it, ensuring that your application can respond to cancellation signals and deadlines effectively.
By adhering to these guidelines and examples, you can ensure that your Go applications handle I/O and IPC operations more reliably and efficiently, with proper support for cancellation, timeouts, and request-scoped values.
## 3. Comment specification ## 3. Comment specification
- Each exportable name must have a comment, which briefly introduces the exported variables, functions, structures, interfaces, etc. - Each exportable name must have a comment, which briefly introduces the exported variables, functions, structures, interfaces, etc.

View File

@ -1,20 +1,386 @@
## Log Standards # OpenIM Logging and Error Handling Documentation
### Log Standards ## Script Logging Documentation Link
- The unified log package `github.com/openimsdk/open-im-server/internal/pkg/log` should be used for all logging; If you wish to view the script's logging documentation, you can click on this link: [Logging Documentation](https://github.com/OpenIMSDK/Open-IM-Server/blob/main/docs/contrib/bash-log.md).
- Use structured logging formats: `log.Infow`, `log.Warnw`, `log.Errorw`, etc. For example: `log.Infow("Update post function called")`;
- All logs should start with an uppercase letter and should not end with a `.`. For example: `log.Infow("Update post function called")`; Below is the documentation for logging and error handling in the OpenIM Go project.
- Use past tense. For example, use `Could not delete B` instead of `Cannot delete B`;
- Adhere to log level standards: To create a standard set of documentation that is quick to read and easy to understand, we will highlight key information about the `Logger` interface and the `CodeError` interface. This includes the purpose of each interface, key methods, and their use cases. This will help developers quickly grasp how to effectively use logging and error handling within the project.
- Debug level logs use `log.Debugw`;
- Info level logs use `log.Infow`; ## Logging (`Logger` Interface)
- Warning level logs use `log.Warnw`;
- Error level logs use `log.Errorw`; ### Purpose
- Panic level logs use `log.Panicw`; The `Logger` interface aims to provide the OpenIM project with a unified and flexible logging mechanism, supporting structured logging formats for efficient log management and analysis.
- Fatal level logs use `log.Fatalw`.
- Log settings: ### Key Methods
- Development and test environments: The log level is set to `debug`, the log format can be set to `console` / `json` as needed, and caller is enabled;
- Production environment: The log level is set to `info`, the log format is set to `json`, and caller is enabled. (**Note**: In the early stages of going online, to facilitate troubleshooting, the log level can be set to `debug`) - **Debug, Info, Warn, Error**
- When logging, avoid outputting sensitive information, such as passwords, keys, etc. Log messages of different levels to suit various logging needs and scenarios. These methods accept a context (`context.Context`), a message (`string`), and key-value pairs (`...interface{}`), allowing the log to carry rich context information.
- If you are calling a logging function in a function/method with a `context.Context` parameter, it is recommended to use `log.L(ctx).Infow()` for logging.
- **WithValues**
Append key-value pair information to log messages, returning a new `Logger` instance. This helps in adding consistent context information.
- **WithName**
Set the name of the logger, which helps in identifying the source of the logs.
- **WithCallDepth**
Adjust the call stack depth to accurately identify the source of the log message.
### Use Cases
- Developers should choose the appropriate logging level (such as `Debug`, `Info`, `Warn`, `Error`) based on the importance of the information when logging.
- Use `WithValues` and `WithName` to add richer context information to logs, facilitating subsequent tracking and analysis.
## Error Handling (`CodeError` Interface)
### Purpose
The `CodeError` interface is designed to provide a unified mechanism for error handling and wrapping, making error information more detailed and manageable.
### Key Methods
- **Code**
Return the error code to distinguish between different types of errors.
- **Msg**
Return the error message description to display to the user.
- **Detail**
Return detailed information about the error for further debugging by developers.
- **WithDetail**
Add detailed information to the error, returning a new `CodeError` instance.
- **Is**
Determine whether the current error matches a specified error, supporting a flexible error comparison mechanism.
- **Wrap**
Wrap another error with additional message description, facilitating the tracing of the error's cause.
### Use Cases
- When defining errors with specific codes and messages, use error types that implement the `CodeError` interface.
- Use `WithDetail` to add additional context information to errors for more accurate problem localization.
- Use the `Is` method to judge the type of error for conditional branching.
- Use the `Wrap` method to wrap underlying errors while adding more contextual descriptions.
## Logging Standards and Code Examples
In the OpenIM project, we use the unified logging package `github.com/OpenIMSDK/tools/log` for logging to achieve efficient log management and analysis. This logging package supports structured logging formats, making it easier for developers to handle log information.
### Logger Interface and Implementation
The logger interface is defined as follows:
```go
type Logger interface {
Debug(ctx context.Context, msg string, keysAndValues ...interface{})
Info(ctx context.Context, msg string, keysAndValues ...interface{})
Warn(ctx context.Context, msg string, err error, keysAndValues ...interface{})
Error(ctx context.Context, msg string, err error, keysAndValues ...interface{})
WithValues(keysAndValues ...interface{}) Logger
WithName(name string) Logger
WithCallDepth(depth int) Logger
}
```
Example code: Using the `Logger` interface to log at the info level.
```go
func main() {
logger := log.NewLogger().WithName("MyService")
ctx := context.Background()
logger.Info(ctx, "Service started", "port", "8080")
}
```
## Error Handling and Code Examples
We use the `github.com/OpenIMSDK/tools/errs` package for unified error handling and wrapping.
### CodeError Interface and Implementation
The error interface is defined as follows:
```go
type CodeError interface {
Code() int
Msg() string
Detail() string
WithDetail(detail string) CodeError
Is(err error, loose ...bool) bool
Wrap(msg ...string) error
error
}
```
Example code: Creating and using the `CodeError` interface to handle errors.
```go
package main
import (
"fmt"
"github.com/OpenIMSDK/tools/errs"
)
func main() {
err := errs.New(404, "Resource not found")
err = err.WithDetail("
More details")
if e, ok := err.(errs.CodeError); ok {
fmt.Println(e.Code(), e.Msg(), e.Detail())
}
}
```
### Detailed Logging Standards and Code Examples
1. **Print key information at startup**
It is crucial to print entry parameters and key process information at program startup. This helps understand the startup state and configuration of the program.
**Code Example**:
```go
package main
import (
"fmt"
"os"
)
func main() {
fmt.Println("Program startup, version: 1.0.0")
fmt.Printf("Connecting to database: %s\n", os.Getenv("DATABASE_URL"))
}
```
2. **Use `tools/log` and `fmt` for logging**
Logging should be done using a specialized logging library for unified management and formatted log output.
**Code Example**: Logging an info level message with `tools/log`.
```go
package main
import (
"context"
"github.com/OpenIMSDK/tools/log"
)
func main() {
ctx := context.Background()
log.Info(ctx, "Application started successfully")
}
```
3. **Use standard error output for startup failures or critical information**
Critical error messages or program startup failures should be indicated to the user through standard error output.
**Code Example**:
```go
package main
import (
"fmt"
"os"
)
func checkEnvironment() bool {
return os.Getenv("REQUIRED_ENV") != ""
}
func main() {
if !checkEnvironment() {
fmt.Fprintln(os.Stderr, "Missing required environment variable")
os.Exit(1)
}
}
```
We encapsulate it into separate tools, which can output error information through the `tools/log` package.
```go
package main
import (
util "github.com/openimsdk/open-im-server/v3/pkg/util/genutil"
)
func main() {
if err := apiCmd.Execute(); err != nil {
util.ExitWithError(err)
}
}
```
4. **Use `tools/log` package for runtime logging**
This ensures consistency and control over logging.
**Code Example**: Same as the above example using `tools/log`. When `tools/log` is not initialized, consider using `fmt` for standard output.
5. **Error logs should be printed by the top-level caller**
This is to avoid duplicate logging of errors, typically errors are caught and logged at the application's outermost level.
**Code Example**:
```go
package main
import (
"github.com/OpenIMSDK/tools/log"
"context"
)
func doSomething() error {
// An error occurs here
return errs.Wrap(errors.New("An error occurred"))
}
func controller() error {
err := doSomething()
if err != nil {
return err
}
return nil
}
func main() {
err := controller()
if err != nil {
log.Error(context.Background(), "Operation failed", err)
}
}
```
6. **Handling logs for API RPC calls and non-RPC applications**
For API RPC calls using gRPC, logs at the information level are printed by middleware on the gRPC server side, reducing the need to manually log in each RPC method. For non-RPC applications, it's recommended to manually log key execution paths to track the application's execution flow.
**gRPC Server-Side Logging Middleware:**
In gRPC, `UnaryInterceptor` and `StreamInterceptor` can intercept Unary and Stream type RPC calls, respectively. Here's an example of how to implement a simple Unary RPC logging middleware:
```go
package main
import (
"context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"log"
"time"
)
// unaryServerInterceptor returns a new unary server interceptor that logs each request.
func unaryServerInterceptor() grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
// Record the start time of the request
start := time.Now()
// Call the actual RPC method
resp, err = handler(ctx, req)
// After the request ends, log the duration and other information
log.Printf("Request method: %s, duration: %s, error status: %v", info.FullMethod, time.Since(start), status.Code(err))
return resp, err
}
}
func main() {
// Create a gRPC server and add the middleware
s := grpc.NewServer
(grpc.UnaryInterceptor(unaryServerInterceptor()))
// Register your service
// Start the gRPC server
log.Println("Starting gRPC server...")
// ...
}
```
**Logging for Non-RPC Applications:**
For non-RPC applications, the key is to log at appropriate places in the code to maintain an execution trace. Here's a simple example showing how to log when handling a task:
```go
package main
import (
"log"
)
func processTask(taskID string) {
// Log the start of task processing
log.Printf("Starting task processing: %s", taskID)
// Suppose this is where the task is processed
// Log after the task is completed
log.Printf("Task processing completed: %s", taskID)
}
func main() {
// Example task ID
taskID := "task123"
processTask(taskID)
}
```
In both scenarios, appropriate logging can help developers and operators monitor the health of the system, trace the source of issues, and quickly locate and resolve problems. For gRPC logging, using middleware can effectively centralize log management and control. For non-RPC applications, ensuring logs are placed at critical execution points can help understand the program's operational flow and state changes.
### When to Wrap Errors?
1. **Wrap errors generated within the function**
When an error occurs within a function, use `errs.Wrap` to add context information to the original error.
**Code Example**:
```go
func doSomething() error {
// Suppose an error occurs here
err, _ := someFunc()
if err != nil {
return errs.Wrap(err, "doSomething failed")
}
}
```
2. **Wrap errors from system calls or other packages**
When calling external libraries or system functions that return errors, also add context information to wrap the error.
**Code Example**:
```go
func readConfig(file string) error {
_, err := os.ReadFile(file)
if err != nil {
return errs.Wrap(err, "Failed to read config file")
}
return nil
}
```
3. **No need to re-wrap errors for internal module calls**
If an error has been appropriately wrapped with sufficient context information in an internal module call, there's no need to wrap it again.
**Code Example**:
```go
func doSomething() error {
err := doAnotherThing()
if err != nil {
return err
}
return nil
}
```
4. **Ensure comprehensive wrapping of errors with detailed messages**
When wrapping errors, ensure to provide ample context information to make the error more understandable and easier to debug.
**Code Example**:
```go
func connectDatabase() error {
err := db.Connect(config.DatabaseURL)
if err != nil {
return errs.Wrap(err, fmt.Sprintf("Failed to connect to database, URL: %s", config.DatabaseURL))
}
return nil
}
```

View File

@ -96,7 +96,6 @@ We reinforce our approach to branch management and versioning with stringent tes
This document describes the maximum version skew supported between various openim components. Specific cluster deployment tools may place additional restrictions on version skew. This document describes the maximum version skew supported between various openim components. Specific cluster deployment tools may place additional restrictions on version skew.
### Supported version skew ### Supported version skew
In highly-available (HA) clusters, the newest and oldest `openim-api` instances must be within one minor version. In highly-available (HA) clusters, the newest and oldest `openim-api` instances must be within one minor version.
@ -210,6 +209,7 @@ git merge release-v3.1
# Push the updates to the main branch # Push the updates to the main branch
git push origin main git push origin main
``` ```
## Release Process ## Release Process
``` ```
@ -232,5 +232,7 @@ For more details on managing Docker image versions, visit [OpenIM Docker Images
More on multi-branch version management design and version management design at helm charts More on multi-branch version management design and version management design at helm charts
+ https://github.com/openimsdk/open-im-server/issues/1695 About Helm's version management strategy for Multiple Apps and multiple Services:
+ https://github.com/openimsdk/open-im-server/issues/1662
+ [中文版本管理文档](https://github.com/openimsdk/helm-charts/blob/main/docs/contrib/version-zh.md)
+ [English version management documents](https://github.com/openimsdk/helm-charts/blob/main/docs/contrib/version.md)

2
go.mod
View File

@ -4,7 +4,7 @@ go 1.19
require ( require (
firebase.google.com/go v3.13.0+incompatible firebase.google.com/go v3.13.0+incompatible
github.com/OpenIMSDK/protocol v0.0.55 github.com/OpenIMSDK/protocol v0.0.56
github.com/OpenIMSDK/tools v0.0.37 github.com/OpenIMSDK/tools v0.0.37
github.com/bwmarrin/snowflake v0.3.0 // indirect github.com/bwmarrin/snowflake v0.3.0 // indirect
github.com/dtm-labs/rockscache v0.1.1 github.com/dtm-labs/rockscache v0.1.1

4
go.sum
View File

@ -18,8 +18,8 @@ firebase.google.com/go v3.13.0+incompatible/go.mod h1:xlah6XbEyW6tbfSklcfe5FHJIw
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/IBM/sarama v1.42.2 h1:VoY4hVIZ+WQJ8G9KNY/SQlWguBQXQ9uvFPOnrcu8hEw= github.com/IBM/sarama v1.42.2 h1:VoY4hVIZ+WQJ8G9KNY/SQlWguBQXQ9uvFPOnrcu8hEw=
github.com/IBM/sarama v1.42.2/go.mod h1:FLPGUGwYqEs62hq2bVG6Io2+5n+pS6s/WOXVKWSLFtE= github.com/IBM/sarama v1.42.2/go.mod h1:FLPGUGwYqEs62hq2bVG6Io2+5n+pS6s/WOXVKWSLFtE=
github.com/OpenIMSDK/protocol v0.0.55 h1:eBjg8DyuhxGmuCUjpoZjg6MJJJXU/xJ3xJwFhrn34yA= github.com/OpenIMSDK/protocol v0.0.56 h1:mbVFyDBachEsmJLfYW5AU1z2KL8AUEpoHG8RPCIxjgg=
github.com/OpenIMSDK/protocol v0.0.55/go.mod h1:F25dFrwrIx3lkNoiuf6FkCfxuwf8L4Z8UIsdTHP/r0Y= github.com/OpenIMSDK/protocol v0.0.56/go.mod h1:F25dFrwrIx3lkNoiuf6FkCfxuwf8L4Z8UIsdTHP/r0Y=
github.com/OpenIMSDK/tools v0.0.37 h1:qvDqmA4RbEJtPjZouWCkVuf/pjm6Y8nUrG5iH2gcnOg= github.com/OpenIMSDK/tools v0.0.37 h1:qvDqmA4RbEJtPjZouWCkVuf/pjm6Y8nUrG5iH2gcnOg=
github.com/OpenIMSDK/tools v0.0.37/go.mod h1:wBfR5CYmEyvxl03QJbTkhz1CluK6J4/lX0lviu8JAjE= github.com/OpenIMSDK/tools v0.0.37/go.mod h1:wBfR5CYmEyvxl03QJbTkhz1CluK6J4/lX0lviu8JAjE=
github.com/QcloudApi/qcloud_sign_golang v0.0.0-20141224014652-e4130a326409/go.mod h1:1pk82RBxDY/JZnPQrtqHlUFfCctgdorsd9M06fMynOM= github.com/QcloudApi/qcloud_sign_golang v0.0.0-20141224014652-e4130a326409/go.mod h1:1pk82RBxDY/JZnPQrtqHlUFfCctgdorsd9M06fMynOM=

View File

@ -3,16 +3,13 @@ go 1.19
use ( use (
. .
./test/typecheck ./test/typecheck
./tools/codescan
./tools/changelog ./tools/changelog
./tools/component ./tools/component
./tools/data-conversion
./tools/formitychecker ./tools/formitychecker
./tools/imctl ./tools/imctl
./tools/infra ./tools/infra
./tools/ncpu ./tools/ncpu
./tools/openim-web ./tools/openim-web
./tools/up35
./tools/url2im ./tools/url2im
./tools/versionchecker ./tools/versionchecker
./tools/yamlfmt ./tools/yamlfmt

View File

@ -215,25 +215,22 @@ func (m *MessageApi) SendMessage(c *gin.Context) {
// Set the receiver ID in the message data. // Set the receiver ID in the message data.
sendMsgReq.MsgData.RecvID = req.RecvID sendMsgReq.MsgData.RecvID = req.RecvID
// Declare a variable to store the message sending status.
var status int
// Attempt to send the message using the client. // Attempt to send the message using the client.
respPb, err := m.Client.SendMsg(c, sendMsgReq) respPb, err := m.Client.SendMsg(c, sendMsgReq)
if err != nil { if err != nil {
// Set the status to failed and respond with an error if sending fails. // Set the status to failed and respond with an error if sending fails.
status = constant.MsgSendFailed
apiresp.GinError(c, err) apiresp.GinError(c, err)
return return
} }
// Set the status to successful if the message is sent. // Set the status to successful if the message is sent.
status = constant.MsgSendSuccessed var status int = constant.MsgSendSuccessed
// Attempt to update the message sending status in the system. // Attempt to update the message sending status in the system.
_, err = m.Client.SetSendMsgStatus(c, &msg.SetSendMsgStatusReq{ _, err = m.Client.SetSendMsgStatus(c, &msg.SetSendMsgStatusReq{
Status: int32(status), Status: int32(status),
}) })
if err != nil { if err != nil {
// Log the error if updating the status fails. // Log the error if updating the status fails.
apiresp.GinError(c, err) apiresp.GinError(c, err)

View File

@ -50,7 +50,6 @@ import (
) )
func Start(config *config.GlobalConfig, port int, proPort int) error { func Start(config *config.GlobalConfig, port int, proPort int) error {
log.ZDebug(context.Background(), "configAPI1111111111111111111", config, "port", port, "javafdasfs")
if port == 0 || proPort == 0 { if port == 0 || proPort == 0 {
err := "port or proPort is empty:" + strconv.Itoa(port) + "," + strconv.Itoa(proPort) err := "port or proPort is empty:" + strconv.Itoa(port) + "," + strconv.Itoa(proPort)
return errs.Wrap(fmt.Errorf(err)) return errs.Wrap(fmt.Errorf(err))

View File

@ -141,7 +141,6 @@ func (c *UserConnContext) GetBackground() bool {
b, err := strconv.ParseBool(c.Req.URL.Query().Get(BackgroundStatus)) b, err := strconv.ParseBool(c.Req.URL.Query().Get(BackgroundStatus))
if err != nil { if err != nil {
return false return false
} else {
return b
} }
return b
} }

View File

@ -19,7 +19,6 @@ import (
"sync" "sync"
"github.com/OpenIMSDK/tools/log" "github.com/OpenIMSDK/tools/log"
"github.com/OpenIMSDK/tools/utils"
) )
type UserMap struct { type UserMap struct {
@ -71,48 +70,65 @@ func (u *UserMap) Set(key string, v *Client) {
} }
func (u *UserMap) delete(key string, connRemoteAddr string) (isDeleteUser bool) { func (u *UserMap) delete(key string, connRemoteAddr string) (isDeleteUser bool) {
// Attempt to load the clients associated with the key.
allClients, existed := u.m.Load(key) allClients, existed := u.m.Load(key)
if existed { if !existed {
oldClients := allClients.([]*Client) // Return false immediately if the key does not exist.
var a []*Client
for _, client := range oldClients {
if client.ctx.GetRemoteAddr() != connRemoteAddr {
a = append(a, client)
}
}
if len(a) == 0 {
u.m.Delete(key)
return true
} else {
u.m.Store(key, a)
return false return false
} }
// Convert allClients to a slice of *Client.
oldClients := allClients.([]*Client)
var remainingClients []*Client
for _, client := range oldClients {
// Keep clients that do not match the connRemoteAddr.
if client.ctx.GetRemoteAddr() != connRemoteAddr {
remainingClients = append(remainingClients, client)
} }
return existed }
// If no clients remain after filtering, delete the key from the map.
if len(remainingClients) == 0 {
u.m.Delete(key)
return true
}
// Otherwise, update the key with the remaining clients.
u.m.Store(key, remainingClients)
return false
} }
func (u *UserMap) deleteClients(key string, clients []*Client) (isDeleteUser bool) { func (u *UserMap) deleteClients(key string, clientsToDelete []*Client) (isDeleteUser bool) {
m := utils.SliceToMapAny(clients, func(c *Client) (string, struct{}) { // Convert the slice of clients to delete into a map for efficient lookup.
return c.ctx.GetRemoteAddr(), struct{}{} deleteMap := make(map[string]struct{})
}) for _, client := range clientsToDelete {
deleteMap[client.ctx.GetRemoteAddr()] = struct{}{}
}
// Load the current clients associated with the key.
allClients, existed := u.m.Load(key) allClients, existed := u.m.Load(key)
if existed { if !existed {
oldClients := allClients.([]*Client) // If the key doesn't exist, return false.
var a []*Client
for _, client := range oldClients {
if _, ok := m[client.ctx.GetRemoteAddr()]; !ok {
a = append(a, client)
}
}
if len(a) == 0 {
u.m.Delete(key)
return true
} else {
u.m.Store(key, a)
return false return false
} }
// Filter out clients that are in the deleteMap.
oldClients := allClients.([]*Client)
var remainingClients []*Client
for _, client := range oldClients {
if _, shouldBeDeleted := deleteMap[client.ctx.GetRemoteAddr()]; !shouldBeDeleted {
remainingClients = append(remainingClients, client)
} }
return existed }
// Update or delete the key based on the remaining clients.
if len(remainingClients) == 0 {
u.m.Delete(key)
return true
}
u.m.Store(key, remainingClients)
return false
} }
func (u *UserMap) DeleteAll(key string) { func (u *UserMap) DeleteAll(key string) {

View File

@ -184,13 +184,12 @@ func (och *OnlineHistoryRedisConsumerHandler) getPushStorageMsgList(
options2 := msgprocessor.Options(msg.Options) options2 := msgprocessor.Options(msg.Options)
if options2.IsHistory() { if options2.IsHistory() {
return true return true
} else { }
// if !(!options2.IsSenderSync() && conversationID == msg.MsgData.SendID) { // if !(!options2.IsSenderSync() && conversationID == msg.MsgData.SendID) {
// return false // return false
// } // }
return false return false
} }
}
for _, v := range totalMsgs { for _, v := range totalMsgs {
options := msgprocessor.Options(v.message.Options) options := msgprocessor.Options(v.message.Options)
if !options.IsNotNotification() { if !options.IsNotNotification() {

View File

@ -90,9 +90,8 @@ func (g *Client) Push(ctx context.Context, userIDs []string, title, content stri
for i, v := range s.GetSplitResult() { for i, v := range s.GetSplitResult() {
go func(index int, userIDs []string) { go func(index int, userIDs []string) {
defer wg.Done() defer wg.Done()
if err := g.batchPush(ctx, token, userIDs, pushReq); err != nil { if err = g.batchPush(ctx, token, userIDs, pushReq); err != nil {
log.ZError(ctx, "batchPush failed", err, "index", index, "token", token, "req", pushReq) log.ZError(ctx, "batchPush failed", err, "index", index, "token", token, "req", pushReq)
err = err
} }
}(i, v.Item) }(i, v.Item)
} }

View File

@ -16,7 +16,6 @@ package push
import ( import (
"context" "context"
"github.com/openimsdk/open-im-server/v3/pkg/rpccache"
"github.com/OpenIMSDK/protocol/constant" "github.com/OpenIMSDK/protocol/constant"
pbpush "github.com/OpenIMSDK/protocol/push" pbpush "github.com/OpenIMSDK/protocol/push"
@ -26,6 +25,7 @@ import (
"github.com/openimsdk/open-im-server/v3/pkg/common/config" "github.com/openimsdk/open-im-server/v3/pkg/common/config"
"github.com/openimsdk/open-im-server/v3/pkg/common/db/cache" "github.com/openimsdk/open-im-server/v3/pkg/common/db/cache"
"github.com/openimsdk/open-im-server/v3/pkg/common/db/controller" "github.com/openimsdk/open-im-server/v3/pkg/common/db/controller"
"github.com/openimsdk/open-im-server/v3/pkg/rpccache"
"github.com/openimsdk/open-im-server/v3/pkg/rpcclient" "github.com/openimsdk/open-im-server/v3/pkg/rpcclient"
"google.golang.org/grpc" "google.golang.org/grpc"
) )
@ -90,9 +90,8 @@ func (r *pushServer) PushMsg(ctx context.Context, pbData *pbpush.PushMsgReq) (re
if err != nil { if err != nil {
if err != errNoOfflinePusher { if err != errNoOfflinePusher {
return nil, err return nil, err
} else {
log.ZWarn(ctx, "offline push failed", err, "msg", pbData.String())
} }
log.ZWarn(ctx, "offline push failed", err, "msg", pbData.String())
} }
return &pbpush.PushMsgResp{}, nil return &pbpush.PushMsgResp{}, nil
} }

View File

@ -18,7 +18,6 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"errors" "errors"
"github.com/openimsdk/open-im-server/v3/pkg/rpccache"
"sync" "sync"
"github.com/OpenIMSDK/protocol/constant" "github.com/OpenIMSDK/protocol/constant"
@ -39,6 +38,7 @@ import (
"github.com/openimsdk/open-im-server/v3/pkg/common/db/controller" "github.com/openimsdk/open-im-server/v3/pkg/common/db/controller"
"github.com/openimsdk/open-im-server/v3/pkg/common/prommetrics" "github.com/openimsdk/open-im-server/v3/pkg/common/prommetrics"
"github.com/openimsdk/open-im-server/v3/pkg/msgprocessor" "github.com/openimsdk/open-im-server/v3/pkg/msgprocessor"
"github.com/openimsdk/open-im-server/v3/pkg/rpccache"
"github.com/openimsdk/open-im-server/v3/pkg/rpcclient" "github.com/openimsdk/open-im-server/v3/pkg/rpcclient"
"golang.org/x/sync/errgroup" "golang.org/x/sync/errgroup"
"google.golang.org/grpc" "google.golang.org/grpc"

View File

@ -26,7 +26,6 @@ func GetContent(msg *sdkws.MsgData) string {
_ = proto.Unmarshal(msg.Content, &tips) _ = proto.Unmarshal(msg.Content, &tips)
content := tips.JsonDetail content := tips.JsonDetail
return content return content
} else {
return string(msg.Content)
} }
return string(msg.Content)
} }

View File

@ -506,19 +506,27 @@ func (c *conversationServer) getConversationInfo(
switch chatLog.SessionType { switch chatLog.SessionType {
case constant.SingleChatType: case constant.SingleChatType:
if chatLog.SendID == userID { if chatLog.SendID == userID {
msgInfo.FaceURL = sendMap[chatLog.RecvID].FaceURL if recv, ok := sendMap[chatLog.RecvID]; ok {
msgInfo.SenderName = sendMap[chatLog.RecvID].Nickname msgInfo.FaceURL = recv.FaceURL
msgInfo.SenderName = recv.Nickname
}
break break
} }
msgInfo.FaceURL = sendMap[chatLog.SendID].FaceURL if send, ok := sendMap[chatLog.SendID]; ok {
msgInfo.SenderName = sendMap[chatLog.SendID].Nickname msgInfo.FaceURL = send.FaceURL
msgInfo.SenderName = send.Nickname
}
case constant.GroupChatType, constant.SuperGroupChatType: case constant.GroupChatType, constant.SuperGroupChatType:
msgInfo.GroupName = groupMap[chatLog.GroupID].GroupName
msgInfo.GroupFaceURL = groupMap[chatLog.GroupID].FaceURL
msgInfo.GroupMemberCount = groupMap[chatLog.GroupID].MemberCount
msgInfo.GroupID = chatLog.GroupID msgInfo.GroupID = chatLog.GroupID
msgInfo.GroupType = groupMap[chatLog.GroupID].GroupType if group, ok := groupMap[chatLog.GroupID]; ok {
msgInfo.SenderName = sendMap[chatLog.SendID].Nickname msgInfo.GroupName = group.GroupName
msgInfo.GroupFaceURL = group.FaceURL
msgInfo.GroupMemberCount = group.MemberCount
msgInfo.GroupType = group.GroupType
}
if send, ok := sendMap[chatLog.SendID]; ok {
msgInfo.SenderName = send.Nickname
}
} }
pbchatLog.ConversationID = conversationID pbchatLog.ConversationID = conversationID
msgInfo.LatestMsgRecvTime = chatLog.SendTime msgInfo.LatestMsgRecvTime = chatLog.SendTime
@ -528,7 +536,10 @@ func (c *conversationServer) getConversationInfo(
return conversationMsg, nil return conversationMsg, nil
} }
func (c *conversationServer) GetConversationNotReceiveMessageUserIDs(ctx context.Context, req *pbconversation.GetConversationNotReceiveMessageUserIDsReq) (*pbconversation.GetConversationNotReceiveMessageUserIDsResp, error) { func (c *conversationServer) GetConversationNotReceiveMessageUserIDs(
ctx context.Context,
req *pbconversation.GetConversationNotReceiveMessageUserIDsReq,
) (*pbconversation.GetConversationNotReceiveMessageUserIDsResp, error) {
userIDs, err := c.conversationDatabase.GetConversationNotReceiveMessageUserIDs(ctx, req.ConversationID) userIDs, err := c.conversationDatabase.GetConversationNotReceiveMessageUserIDs(ctx, req.ConversationID)
if err != nil { if err != nil {
return nil, err return nil, err

View File

@ -79,9 +79,14 @@ func (s *friendServer) AddBlack(ctx context.Context, req *pbfriend.AddBlackReq)
CreateTime: time.Now(), CreateTime: time.Now(),
Ex: req.Ex, Ex: req.Ex,
} }
if err := s.blackDatabase.Create(ctx, []*relation.BlackModel{&black}); err != nil { if err := s.blackDatabase.Create(ctx, []*relation.BlackModel{&black}); err != nil {
return nil, err return nil, err
} }
s.notificationSender.BlackAddedNotification(ctx, req)
if err := s.notificationSender.BlackAddedNotification(ctx, req); err != nil {
return nil, err
}
return &pbfriend.AddBlackResp{}, nil return &pbfriend.AddBlackResp{}, nil
} }

View File

@ -16,31 +16,26 @@ package friend
import ( import (
"context" "context"
"github.com/OpenIMSDK/tools/tx"
"github.com/OpenIMSDK/protocol/sdkws"
"github.com/openimsdk/open-im-server/v3/pkg/authverify"
"github.com/OpenIMSDK/tools/log"
"github.com/openimsdk/open-im-server/v3/pkg/common/convert"
"github.com/openimsdk/open-im-server/v3/pkg/rpcclient"
"google.golang.org/grpc"
"github.com/OpenIMSDK/protocol/constant" "github.com/OpenIMSDK/protocol/constant"
pbfriend "github.com/OpenIMSDK/protocol/friend" pbfriend "github.com/OpenIMSDK/protocol/friend"
"github.com/OpenIMSDK/protocol/sdkws"
registry "github.com/OpenIMSDK/tools/discoveryregistry" registry "github.com/OpenIMSDK/tools/discoveryregistry"
"github.com/OpenIMSDK/tools/errs" "github.com/OpenIMSDK/tools/errs"
"github.com/OpenIMSDK/tools/log"
"github.com/OpenIMSDK/tools/tx"
"github.com/OpenIMSDK/tools/utils" "github.com/OpenIMSDK/tools/utils"
"github.com/openimsdk/open-im-server/v3/pkg/authverify"
"github.com/openimsdk/open-im-server/v3/pkg/common/config" "github.com/openimsdk/open-im-server/v3/pkg/common/config"
"github.com/openimsdk/open-im-server/v3/pkg/common/convert"
"github.com/openimsdk/open-im-server/v3/pkg/common/db/cache" "github.com/openimsdk/open-im-server/v3/pkg/common/db/cache"
"github.com/openimsdk/open-im-server/v3/pkg/common/db/controller" "github.com/openimsdk/open-im-server/v3/pkg/common/db/controller"
"github.com/openimsdk/open-im-server/v3/pkg/common/db/mgo" "github.com/openimsdk/open-im-server/v3/pkg/common/db/mgo"
tablerelation "github.com/openimsdk/open-im-server/v3/pkg/common/db/table/relation" tablerelation "github.com/openimsdk/open-im-server/v3/pkg/common/db/table/relation"
"github.com/openimsdk/open-im-server/v3/pkg/common/db/unrelation" "github.com/openimsdk/open-im-server/v3/pkg/common/db/unrelation"
"github.com/openimsdk/open-im-server/v3/pkg/rpcclient"
"github.com/openimsdk/open-im-server/v3/pkg/rpcclient/notification" "github.com/openimsdk/open-im-server/v3/pkg/rpcclient/notification"
"google.golang.org/grpc"
) )
type friendServer struct { type friendServer struct {
@ -119,26 +114,36 @@ func (s *friendServer) ApplyToAddFriend(ctx context.Context, req *pbfriend.Apply
if err := authverify.CheckAccessV3(ctx, req.FromUserID, s.config); err != nil { if err := authverify.CheckAccessV3(ctx, req.FromUserID, s.config); err != nil {
return nil, err return nil, err
} }
if req.ToUserID == req.FromUserID { if req.ToUserID == req.FromUserID {
return nil, errs.ErrCanNotAddYourself.Wrap("req.ToUserID", req.ToUserID) return nil, errs.ErrCanNotAddYourself.Wrap("req.ToUserID", req.ToUserID)
} }
if err = CallbackBeforeAddFriend(ctx, s.config, req); err != nil && err != errs.ErrCallbackContinue { if err = CallbackBeforeAddFriend(ctx, s.config, req); err != nil && err != errs.ErrCallbackContinue {
return nil, err return nil, err
} }
if _, err := s.userRpcClient.GetUsersInfoMap(ctx, []string{req.ToUserID, req.FromUserID}); err != nil { if _, err := s.userRpcClient.GetUsersInfoMap(ctx, []string{req.ToUserID, req.FromUserID}); err != nil {
return nil, err return nil, err
} }
in1, in2, err := s.friendDatabase.CheckIn(ctx, req.FromUserID, req.ToUserID) in1, in2, err := s.friendDatabase.CheckIn(ctx, req.FromUserID, req.ToUserID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
if in1 && in2 { if in1 && in2 {
return nil, errs.ErrRelationshipAlready.Wrap() return nil, errs.ErrRelationshipAlready.Wrap()
} }
if err = s.friendDatabase.AddFriendRequest(ctx, req.FromUserID, req.ToUserID, req.ReqMsg, req.Ex); err != nil { if err = s.friendDatabase.AddFriendRequest(ctx, req.FromUserID, req.ToUserID, req.ReqMsg, req.Ex); err != nil {
return nil, err return nil, err
} }
s.notificationSender.FriendApplicationAddNotification(ctx, req)
if err = s.notificationSender.FriendApplicationAddNotification(ctx, req); err != nil {
return nil, err
}
if err = CallbackAfterAddFriend(ctx, s.config, req); err != nil && err != errs.ErrCallbackContinue { if err = CallbackAfterAddFriend(ctx, s.config, req); err != nil && err != errs.ErrCallbackContinue {
return nil, err return nil, err
} }
@ -202,7 +207,9 @@ func (s *friendServer) RespondFriendApply(ctx context.Context, req *pbfriend.Res
if err != nil { if err != nil {
return nil, err return nil, err
} }
s.notificationSender.FriendApplicationAgreedNotification(ctx, req) if err := s.notificationSender.FriendApplicationAgreedNotification(ctx, req); err != nil {
return nil, err
}
return resp, nil return resp, nil
} }
if req.HandleResult == constant.FriendResponseRefuse { if req.HandleResult == constant.FriendResponseRefuse {

View File

@ -33,10 +33,7 @@ func (s *groupServer) GetGroupInfoCache(
return resp, nil return resp, nil
} }
func (s *groupServer) GetGroupMemberCache( func (s *groupServer) GetGroupMemberCache(ctx context.Context, req *pbgroup.GetGroupMemberCacheReq) (resp *pbgroup.GetGroupMemberCacheResp, err error) {
ctx context.Context,
req *pbgroup.GetGroupMemberCacheReq,
) (resp *pbgroup.GetGroupMemberCacheResp, err error) {
members, err := s.db.TakeGroupMember(ctx, req.GroupID, req.GroupMemberID) members, err := s.db.TakeGroupMember(ctx, req.GroupID, req.GroupMemberID)
if err != nil { if err != nil {
return nil, err return nil, err

View File

@ -637,6 +637,7 @@ func (s *groupServer) GetGroupMembersInfo(ctx context.Context, req *pbgroup.GetG
return resp, nil return resp, nil
} }
// GetGroupApplicationList handles functions that get a list of group requests.
func (s *groupServer) GetGroupApplicationList(ctx context.Context, req *pbgroup.GetGroupApplicationListReq) (*pbgroup.GetGroupApplicationListResp, error) { func (s *groupServer) GetGroupApplicationList(ctx context.Context, req *pbgroup.GetGroupApplicationListReq) (*pbgroup.GetGroupApplicationListResp, error) {
groupIDs, err := s.db.FindUserManagedGroupID(ctx, req.FromUserID) groupIDs, err := s.db.FindUserManagedGroupID(ctx, req.FromUserID)
if err != nil { if err != nil {
@ -951,6 +952,7 @@ func (s *groupServer) SetGroupInfo(ctx context.Context, req *pbgroup.SetGroupInf
return nil, errs.Wrap(errs.ErrDismissedAlready) return nil, errs.Wrap(errs.ErrDismissedAlready)
} }
resp := &pbgroup.SetGroupInfoResp{} resp := &pbgroup.SetGroupInfoResp{}
count, err := s.db.FindGroupMemberNum(ctx, group.GroupID) count, err := s.db.FindGroupMemberNum(ctx, group.GroupID)
if err != nil { if err != nil {
return nil, err return nil, err
@ -1068,6 +1070,7 @@ func (s *groupServer) GetGroups(ctx context.Context, req *pbgroup.GetGroupsReq)
group []*relationtb.GroupModel group []*relationtb.GroupModel
err error err error
) )
if req.GroupID != "" { if req.GroupID != "" {
group, err = s.db.FindGroup(ctx, []string{req.GroupID}) group, err = s.db.FindGroup(ctx, []string{req.GroupID})
resp.Total = uint32(len(group)) resp.Total = uint32(len(group))
@ -1076,25 +1079,20 @@ func (s *groupServer) GetGroups(ctx context.Context, req *pbgroup.GetGroupsReq)
total, group, err = s.db.SearchGroup(ctx, req.GroupName, req.Pagination) total, group, err = s.db.SearchGroup(ctx, req.GroupName, req.Pagination)
resp.Total = uint32(total) resp.Total = uint32(total)
} }
if err != nil { if err != nil {
return nil, err return nil, err
} }
var groups []*relationtb.GroupModel groupIDs := utils.Slice(group, func(e *relationtb.GroupModel) string {
for _, v := range group {
if v.Status == constant.GroupStatusDismissed {
resp.Total--
continue
}
groups = append(groups, v)
}
groupIDs := utils.Slice(groups, func(e *relationtb.GroupModel) string {
return e.GroupID return e.GroupID
}) })
ownerMembers, err := s.db.FindGroupsOwner(ctx, groupIDs) ownerMembers, err := s.db.FindGroupsOwner(ctx, groupIDs)
if err != nil { if err != nil {
return nil, err return nil, err
} }
ownerMemberMap := utils.SliceToMap(ownerMembers, func(e *relationtb.GroupMemberModel) string { ownerMemberMap := utils.SliceToMap(ownerMembers, func(e *relationtb.GroupMemberModel) string {
return e.GroupID return e.GroupID
}) })
@ -1102,7 +1100,7 @@ func (s *groupServer) GetGroups(ctx context.Context, req *pbgroup.GetGroupsReq)
if err != nil { if err != nil {
return nil, err return nil, err
} }
resp.Groups = utils.Slice(groups, func(group *relationtb.GroupModel) *pbgroup.CMSGroup { resp.Groups = utils.Slice(group, func(group *relationtb.GroupModel) *pbgroup.CMSGroup {
var ( var (
userID string userID string
username string username string

View File

@ -15,8 +15,6 @@
package msg package msg
import ( import (
"github.com/openimsdk/open-im-server/v3/pkg/rpccache"
"github.com/OpenIMSDK/protocol/constant" "github.com/OpenIMSDK/protocol/constant"
"github.com/OpenIMSDK/protocol/conversation" "github.com/OpenIMSDK/protocol/conversation"
"github.com/OpenIMSDK/protocol/msg" "github.com/OpenIMSDK/protocol/msg"
@ -25,6 +23,7 @@ import (
"github.com/openimsdk/open-im-server/v3/pkg/common/db/cache" "github.com/openimsdk/open-im-server/v3/pkg/common/db/cache"
"github.com/openimsdk/open-im-server/v3/pkg/common/db/controller" "github.com/openimsdk/open-im-server/v3/pkg/common/db/controller"
"github.com/openimsdk/open-im-server/v3/pkg/common/db/unrelation" "github.com/openimsdk/open-im-server/v3/pkg/common/db/unrelation"
"github.com/openimsdk/open-im-server/v3/pkg/rpccache"
"github.com/openimsdk/open-im-server/v3/pkg/rpcclient" "github.com/openimsdk/open-im-server/v3/pkg/rpcclient"
"google.golang.org/grpc" "google.golang.org/grpc"
) )

View File

@ -131,12 +131,13 @@ func (m *msgServer) SearchMessage(ctx context.Context, req *msg.SearchMessageReq
sendIDs = append(sendIDs, chatLog.SendID) sendIDs = append(sendIDs, chatLog.SendID)
} }
switch chatLog.SessionType { switch chatLog.SessionType {
case constant.SingleChatType: case constant.SingleChatType, constant.NotificationChatType:
recvIDs = append(recvIDs, chatLog.RecvID) recvIDs = append(recvIDs, chatLog.RecvID)
case constant.GroupChatType, constant.SuperGroupChatType: case constant.GroupChatType, constant.SuperGroupChatType:
groupIDs = append(groupIDs, chatLog.GroupID) groupIDs = append(groupIDs, chatLog.GroupID)
} }
} }
// Retrieve sender and receiver information
if len(sendIDs) != 0 { if len(sendIDs) != 0 {
sendInfos, err := m.UserLocalCache.GetUsersInfo(ctx, sendIDs) sendInfos, err := m.UserLocalCache.GetUsersInfo(ctx, sendIDs)
if err != nil { if err != nil {
@ -155,6 +156,8 @@ func (m *msgServer) SearchMessage(ctx context.Context, req *msg.SearchMessageReq
recvMap[recvInfo.UserID] = recvInfo.Nickname recvMap[recvInfo.UserID] = recvInfo.Nickname
} }
} }
// Retrieve group information including member counts
if len(groupIDs) != 0 { if len(groupIDs) != 0 {
groupInfos, err := m.GroupLocalCache.GetGroupInfos(ctx, groupIDs) groupInfos, err := m.GroupLocalCache.GetGroupInfos(ctx, groupIDs)
if err != nil { if err != nil {
@ -162,8 +165,14 @@ func (m *msgServer) SearchMessage(ctx context.Context, req *msg.SearchMessageReq
} }
for _, groupInfo := range groupInfos { for _, groupInfo := range groupInfos {
groupMap[groupInfo.GroupID] = groupInfo groupMap[groupInfo.GroupID] = groupInfo
// Get actual member count
memberIDs, err := m.GroupLocalCache.GetGroupMemberIDs(ctx, groupInfo.GroupID)
if err == nil {
groupInfo.MemberCount = uint32(len(memberIDs)) // Update the member count with actual number
} }
} }
}
// Construct response with updated information
for _, chatLog := range chatLogs { for _, chatLog := range chatLogs {
pbchatLog := &msg.ChatLog{} pbchatLog := &msg.ChatLog{}
utils.CopyStructFields(pbchatLog, chatLog) utils.CopyStructFields(pbchatLog, chatLog)
@ -173,16 +182,16 @@ func (m *msgServer) SearchMessage(ctx context.Context, req *msg.SearchMessageReq
pbchatLog.SenderNickname = sendMap[chatLog.SendID] pbchatLog.SenderNickname = sendMap[chatLog.SendID]
} }
switch chatLog.SessionType { switch chatLog.SessionType {
case constant.SingleChatType: case constant.SingleChatType, constant.NotificationChatType:
pbchatLog.RecvNickname = recvMap[chatLog.RecvID] pbchatLog.RecvNickname = recvMap[chatLog.RecvID]
case constant.GroupChatType, constant.SuperGroupChatType: case constant.GroupChatType, constant.SuperGroupChatType:
pbchatLog.SenderFaceURL = groupMap[chatLog.GroupID].FaceURL groupInfo := groupMap[chatLog.GroupID]
pbchatLog.GroupMemberCount = groupMap[chatLog.GroupID].MemberCount pbchatLog.SenderFaceURL = groupInfo.FaceURL
pbchatLog.RecvID = groupMap[chatLog.GroupID].GroupID pbchatLog.GroupMemberCount = groupInfo.MemberCount // Reflects actual member count
pbchatLog.GroupName = groupMap[chatLog.GroupID].GroupName pbchatLog.RecvID = groupInfo.GroupID
pbchatLog.GroupOwner = groupMap[chatLog.GroupID].OwnerUserID pbchatLog.GroupName = groupInfo.GroupName
pbchatLog.GroupType = groupMap[chatLog.GroupID].GroupType pbchatLog.GroupOwner = groupInfo.OwnerUserID
pbchatLog.GroupType = groupInfo.GroupType
} }
resp.ChatLogs = append(resp.ChatLogs, pbchatLog) resp.ChatLogs = append(resp.ChatLogs, pbchatLog)
} }

View File

@ -16,7 +16,6 @@ package msg
import ( import (
"context" "context"
"github.com/OpenIMSDK/tools/log"
"math/rand" "math/rand"
"strconv" "strconv"
"time" "time"
@ -25,6 +24,7 @@ import (
"github.com/OpenIMSDK/protocol/msg" "github.com/OpenIMSDK/protocol/msg"
"github.com/OpenIMSDK/protocol/sdkws" "github.com/OpenIMSDK/protocol/sdkws"
"github.com/OpenIMSDK/tools/errs" "github.com/OpenIMSDK/tools/errs"
"github.com/OpenIMSDK/tools/log"
"github.com/OpenIMSDK/tools/utils" "github.com/OpenIMSDK/tools/utils"
) )
@ -158,9 +158,6 @@ func (m *msgServer) encapsulateMsgData(msg *sdkws.MsgData) {
case constant.Custom: case constant.Custom:
fallthrough fallthrough
case constant.Quote: case constant.Quote:
utils.SetSwitchFromOptions(msg.Options, constant.IsConversationUpdate, true)
utils.SetSwitchFromOptions(msg.Options, constant.IsUnreadCount, true)
utils.SetSwitchFromOptions(msg.Options, constant.IsSenderSync, true)
case constant.Revoke: case constant.Revoke:
utils.SetSwitchFromOptions(msg.Options, constant.IsUnreadCount, false) utils.SetSwitchFromOptions(msg.Options, constant.IsUnreadCount, false)
utils.SetSwitchFromOptions(msg.Options, constant.IsOfflinePush, false) utils.SetSwitchFromOptions(msg.Options, constant.IsOfflinePush, false)

View File

@ -133,6 +133,13 @@ func (t *thirdServer) SearchLogs(ctx context.Context, req *third.SearchLogsReq)
if req.StartTime > req.EndTime { if req.StartTime > req.EndTime {
return nil, errs.ErrArgs.Wrap("startTime>endTime") return nil, errs.ErrArgs.Wrap("startTime>endTime")
} }
if req.StartTime == 0 && req.EndTime == 0 {
t := time.Date(2019, time.January, 1, 0, 0, 0, 0, time.UTC)
timestampMills := t.UnixNano() / int64(time.Millisecond)
req.StartTime = timestampMills
req.EndTime = time.Now().UnixNano() / int64(time.Millisecond)
}
total, logs, err := t.thirdDatabase.SearchLogs(ctx, req.Keyword, time.UnixMilli(req.StartTime), time.UnixMilli(req.EndTime), req.Pagination) total, logs, err := t.thirdDatabase.SearchLogs(ctx, req.Keyword, time.UnixMilli(req.StartTime), time.UnixMilli(req.EndTime), req.Pagination)
if err != nil { if err != nil {
return nil, err return nil, err

View File

@ -60,6 +60,7 @@ func CheckAdmin(ctx context.Context, config *config.GlobalConfig) error {
} }
return errs.ErrNoPermission.Wrap(fmt.Sprintf("user %s is not admin userID", mcontext.GetOpUserID(ctx))) return errs.ErrNoPermission.Wrap(fmt.Sprintf("user %s is not admin userID", mcontext.GetOpUserID(ctx)))
} }
func CheckIMAdmin(ctx context.Context, config *config.GlobalConfig) error { func CheckIMAdmin(ctx context.Context, config *config.GlobalConfig) error {
if utils.IsContain(mcontext.GetOpUserID(ctx), config.IMAdmin.UserID) { if utils.IsContain(mcontext.GetOpUserID(ctx), config.IMAdmin.UserID) {
return nil return nil

View File

@ -1,3 +1,17 @@
// Copyright © 2024 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cachekey package cachekey
const ( const (

View File

@ -1,3 +1,17 @@
// Copyright © 2024 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cachekey package cachekey
const ( const (

View File

@ -1,3 +1,17 @@
// Copyright © 2024 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cachekey package cachekey
const ( const (

View File

@ -1,3 +1,17 @@
// Copyright © 2024 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cachekey package cachekey
import ( import (

View File

@ -1,3 +1,17 @@
// Copyright © 2024 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cachekey package cachekey
const ( const (

View File

@ -17,10 +17,11 @@ package config
import ( import (
_ "embed" _ "embed"
"fmt" "fmt"
"gopkg.in/yaml.v3"
"reflect" "reflect"
"testing" "testing"
"gopkg.in/yaml.v3"
"github.com/openimsdk/open-im-server/v3/pkg/msgprocessor" "github.com/openimsdk/open-im-server/v3/pkg/msgprocessor"
) )

View File

@ -16,12 +16,12 @@ package cache
import ( import (
"context" "context"
"github.com/OpenIMSDK/tools/log"
"github.com/openimsdk/open-im-server/v3/pkg/common/cachekey"
"github.com/openimsdk/open-im-server/v3/pkg/common/config"
"time" "time"
"github.com/OpenIMSDK/tools/log"
"github.com/dtm-labs/rockscache" "github.com/dtm-labs/rockscache"
"github.com/openimsdk/open-im-server/v3/pkg/common/cachekey"
"github.com/openimsdk/open-im-server/v3/pkg/common/config"
relationtb "github.com/openimsdk/open-im-server/v3/pkg/common/db/table/relation" relationtb "github.com/openimsdk/open-im-server/v3/pkg/common/db/table/relation"
"github.com/redis/go-redis/v9" "github.com/redis/go-redis/v9"
) )

View File

@ -1,10 +1,25 @@
// Copyright © 2024 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cache package cache
import ( import (
"github.com/openimsdk/open-im-server/v3/pkg/common/cachekey"
"github.com/openimsdk/open-im-server/v3/pkg/common/config"
"strings" "strings"
"sync" "sync"
"github.com/openimsdk/open-im-server/v3/pkg/common/cachekey"
"github.com/openimsdk/open-im-server/v3/pkg/common/config"
) )
var ( var (

View File

@ -16,15 +16,15 @@ package cache
import ( import (
"context" "context"
"github.com/OpenIMSDK/tools/log"
"github.com/openimsdk/open-im-server/v3/pkg/common/cachekey"
"github.com/openimsdk/open-im-server/v3/pkg/common/config"
"math/big" "math/big"
"strings" "strings"
"time" "time"
"github.com/OpenIMSDK/tools/log"
"github.com/OpenIMSDK/tools/utils" "github.com/OpenIMSDK/tools/utils"
"github.com/dtm-labs/rockscache" "github.com/dtm-labs/rockscache"
"github.com/openimsdk/open-im-server/v3/pkg/common/cachekey"
"github.com/openimsdk/open-im-server/v3/pkg/common/config"
relationtb "github.com/openimsdk/open-im-server/v3/pkg/common/db/table/relation" relationtb "github.com/openimsdk/open-im-server/v3/pkg/common/db/table/relation"
"github.com/redis/go-redis/v9" "github.com/redis/go-redis/v9"
) )
@ -37,7 +37,7 @@ const (
//recvMsgOptKey = "RECV_MSG_OPT:" //recvMsgOptKey = "RECV_MSG_OPT:"
//superGroupRecvMsgNotNotifyUserIDsKey = "SUPER_GROUP_RECV_MSG_NOT_NOTIFY_USER_IDS:" //superGroupRecvMsgNotNotifyUserIDsKey = "SUPER_GROUP_RECV_MSG_NOT_NOTIFY_USER_IDS:"
//superGroupRecvMsgNotNotifyUserIDsHashKey = "SUPER_GROUP_RECV_MSG_NOT_NOTIFY_USER_IDS_HASH:" //superGroupRecvMsgNotNotifyUserIDsHashKey = "SUPER_GROUP_RECV_MSG_NOT_NOTIFY_USER_IDS_HASH:"
//conversationNotReceiveMessageUserIDsKey = "CONVERSATION_NOT_RECEIVE_MESSAGE_USER_IDS:" //conversationNotReceiveMessageUserIDsKey = "CONVERSATION_NOT_RECEIVE_MESSAGE_USER_IDS:".
conversationExpireTime = time.Second * 60 * 60 * 12 conversationExpireTime = time.Second * 60 * 60 * 12
) )

View File

@ -16,13 +16,13 @@ package cache
import ( import (
"context" "context"
"github.com/OpenIMSDK/tools/log"
"github.com/openimsdk/open-im-server/v3/pkg/common/cachekey"
"github.com/openimsdk/open-im-server/v3/pkg/common/config"
"time" "time"
"github.com/OpenIMSDK/tools/log"
"github.com/OpenIMSDK/tools/utils" "github.com/OpenIMSDK/tools/utils"
"github.com/dtm-labs/rockscache" "github.com/dtm-labs/rockscache"
"github.com/openimsdk/open-im-server/v3/pkg/common/cachekey"
"github.com/openimsdk/open-im-server/v3/pkg/common/config"
relationtb "github.com/openimsdk/open-im-server/v3/pkg/common/db/table/relation" relationtb "github.com/openimsdk/open-im-server/v3/pkg/common/db/table/relation"
"github.com/redis/go-redis/v9" "github.com/redis/go-redis/v9"
) )
@ -31,7 +31,7 @@ const (
friendExpireTime = time.Second * 60 * 60 * 12 friendExpireTime = time.Second * 60 * 60 * 12
//friendIDsKey = "FRIEND_IDS:" //friendIDsKey = "FRIEND_IDS:"
//TwoWayFriendsIDsKey = "COMMON_FRIENDS_IDS:" //TwoWayFriendsIDsKey = "COMMON_FRIENDS_IDS:"
//friendKey = "FRIEND_INFO:" //friendKey = "FRIEND_INFO:".
) )
// FriendCache is an interface for caching friend-related data. // FriendCache is an interface for caching friend-related data.

View File

@ -17,8 +17,6 @@ package cache
import ( import (
"context" "context"
"fmt" "fmt"
"github.com/openimsdk/open-im-server/v3/pkg/common/cachekey"
"github.com/openimsdk/open-im-server/v3/pkg/common/config"
"time" "time"
"github.com/OpenIMSDK/protocol/constant" "github.com/OpenIMSDK/protocol/constant"
@ -26,6 +24,8 @@ import (
"github.com/OpenIMSDK/tools/log" "github.com/OpenIMSDK/tools/log"
"github.com/OpenIMSDK/tools/utils" "github.com/OpenIMSDK/tools/utils"
"github.com/dtm-labs/rockscache" "github.com/dtm-labs/rockscache"
"github.com/openimsdk/open-im-server/v3/pkg/common/cachekey"
"github.com/openimsdk/open-im-server/v3/pkg/common/config"
relationtb "github.com/openimsdk/open-im-server/v3/pkg/common/db/table/relation" relationtb "github.com/openimsdk/open-im-server/v3/pkg/common/db/table/relation"
"github.com/redis/go-redis/v9" "github.com/redis/go-redis/v9"
) )
@ -38,7 +38,7 @@ const (
//groupMemberInfoKey = "GROUP_MEMBER_INFO:" //groupMemberInfoKey = "GROUP_MEMBER_INFO:"
//joinedGroupsKey = "JOIN_GROUPS_KEY:" //joinedGroupsKey = "JOIN_GROUPS_KEY:"
//groupMemberNumKey = "GROUP_MEMBER_NUM_CACHE:" //groupMemberNumKey = "GROUP_MEMBER_NUM_CACHE:"
//groupRoleLevelMemberIDsKey = "GROUP_ROLE_LEVEL_MEMBER_IDS:" //groupRoleLevelMemberIDsKey = "GROUP_ROLE_LEVEL_MEMBER_IDS:".
) )
type GroupHash interface { type GroupHash interface {

View File

@ -18,7 +18,6 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"errors" "errors"
"github.com/redis/go-redis/v9"
"fmt" "fmt"
"time" "time"
@ -27,6 +26,7 @@ import (
"github.com/OpenIMSDK/tools/mw/specialerror" "github.com/OpenIMSDK/tools/mw/specialerror"
"github.com/OpenIMSDK/tools/utils" "github.com/OpenIMSDK/tools/utils"
"github.com/dtm-labs/rockscache" "github.com/dtm-labs/rockscache"
"github.com/redis/go-redis/v9"
) )
const ( const (

View File

@ -38,11 +38,11 @@ const (
conversationUserMinSeq = "CON_USER_MIN_SEQ:" conversationUserMinSeq = "CON_USER_MIN_SEQ:"
hasReadSeq = "HAS_READ_SEQ:" hasReadSeq = "HAS_READ_SEQ:"
//appleDeviceToken = "DEVICE_TOKEN" //appleDeviceToken = "DEVICE_TOKEN".
getuiToken = "GETUI_TOKEN" getuiToken = "GETUI_TOKEN"
getuiTaskID = "GETUI_TASK_ID" getuiTaskID = "GETUI_TASK_ID"
//signalCache = "SIGNAL_CACHE:" //signalCache = "SIGNAL_CACHE:"
//signalListCache = "SIGNAL_LIST_CACHE:" //signalListCache = "SIGNAL_LIST_CACHE:".
FCM_TOKEN = "FCM_TOKEN:" FCM_TOKEN = "FCM_TOKEN:"
messageCache = "MESSAGE_CACHE:" messageCache = "MESSAGE_CACHE:"

View File

@ -18,8 +18,6 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"errors" "errors"
"github.com/openimsdk/open-im-server/v3/pkg/common/cachekey"
"github.com/openimsdk/open-im-server/v3/pkg/common/config"
"hash/crc32" "hash/crc32"
"strconv" "strconv"
"time" "time"
@ -29,13 +27,15 @@ import (
"github.com/OpenIMSDK/tools/errs" "github.com/OpenIMSDK/tools/errs"
"github.com/OpenIMSDK/tools/log" "github.com/OpenIMSDK/tools/log"
"github.com/dtm-labs/rockscache" "github.com/dtm-labs/rockscache"
"github.com/openimsdk/open-im-server/v3/pkg/common/cachekey"
"github.com/openimsdk/open-im-server/v3/pkg/common/config"
relationtb "github.com/openimsdk/open-im-server/v3/pkg/common/db/table/relation" relationtb "github.com/openimsdk/open-im-server/v3/pkg/common/db/table/relation"
"github.com/redis/go-redis/v9" "github.com/redis/go-redis/v9"
) )
const ( const (
userExpireTime = time.Second * 60 * 60 * 12 userExpireTime = time.Second * 60 * 60 * 12
//userInfoKey = "USER_INFO:" //userInfoKey = "USER_INFO:".
userGlobalRecvMsgOptKey = "USER_GLOBAL_RECV_MSG_OPT_KEY:" userGlobalRecvMsgOptKey = "USER_GLOBAL_RECV_MSG_OPT_KEY:"
olineStatusKey = "ONLINE_STATUS:" olineStatusKey = "ONLINE_STATUS:"
userOlineStatusExpireTime = time.Second * 60 * 60 * 24 userOlineStatusExpireTime = time.Second * 60 * 60 * 24

View File

@ -18,6 +18,7 @@ import (
"context" "context"
"time" "time"
"github.com/OpenIMSDK/protocol/constant"
"github.com/OpenIMSDK/tools/errs" "github.com/OpenIMSDK/tools/errs"
"github.com/OpenIMSDK/tools/mgoutil" "github.com/OpenIMSDK/tools/mgoutil"
"github.com/OpenIMSDK/tools/pagination" "github.com/OpenIMSDK/tools/pagination"
@ -69,7 +70,12 @@ func (g *GroupMgo) Take(ctx context.Context, groupID string) (group *relation.Gr
} }
func (g *GroupMgo) Search(ctx context.Context, keyword string, pagination pagination.Pagination) (total int64, groups []*relation.GroupModel, err error) { func (g *GroupMgo) Search(ctx context.Context, keyword string, pagination pagination.Pagination) (total int64, groups []*relation.GroupModel, err error) {
return mgoutil.FindPage[*relation.GroupModel](ctx, g.coll, bson.M{"group_name": bson.M{"$regex": keyword}}, pagination) opts := options.Find().SetSort(bson.D{{Key: "created_at", Value: -1}})
return mgoutil.FindPage[*relation.GroupModel](ctx, g.coll, bson.M{
"group_name": bson.M{"$regex": keyword},
"status": bson.M{"$ne": constant.GroupStatusDismissed},
}, pagination, opts)
} }
func (g *GroupMgo) CountTotal(ctx context.Context, before *time.Time) (count int64, err error) { func (g *GroupMgo) CountTotal(ctx context.Context, before *time.Time) (count int64, err error) {

View File

@ -1063,8 +1063,8 @@ func (m *MsgMongoDriver) searchMessage(ctx context.Context, req *msg.SearchMessa
// Changed to keyed fields for bson.M to avoid govet errors // Changed to keyed fields for bson.M to avoid govet errors
condition = append(condition, bson.M{"$eq": bson.A{bson.M{"$dateToString": bson.M{"format": "%Y-%m-%d", "date": bson.M{"$toDate": "$$item.msg.send_time"}}}, req.SendTime}}) condition = append(condition, bson.M{"$eq": bson.A{bson.M{"$dateToString": bson.M{"format": "%Y-%m-%d", "date": bson.M{"$toDate": "$$item.msg.send_time"}}}, req.SendTime}})
} }
if req.MsgType != 0 { if req.ContentType != 0 {
condition = append(condition, bson.M{"$eq": bson.A{"$$item.msg.content_type", req.MsgType}}) condition = append(condition, bson.M{"$eq": bson.A{"$$item.msg.content_type", req.ContentType}})
} }
if req.SessionType != 0 { if req.SessionType != 0 {
condition = append(condition, bson.M{"$eq": bson.A{"$$item.msg.session_type", req.SessionType}}) condition = append(condition, bson.M{"$eq": bson.A{"$$item.msg.session_type", req.SessionType}})

View File

@ -1,3 +1,17 @@
// Copyright © 2024 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package redispubsub package redispubsub
import "github.com/redis/go-redis/v9" import "github.com/redis/go-redis/v9"

View File

@ -1,7 +1,22 @@
// Copyright © 2024 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package redispubsub package redispubsub
import ( import (
"context" "context"
"github.com/redis/go-redis/v9" "github.com/redis/go-redis/v9"
) )

View File

@ -1,11 +1,26 @@
// Copyright © 2024 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package localcache package localcache
import ( import (
"context" "context"
"github.com/openimsdk/localcache/link"
"github.com/openimsdk/localcache/lru"
"hash/fnv" "hash/fnv"
"unsafe" "unsafe"
"github.com/openimsdk/localcache/link"
"github.com/openimsdk/localcache/lru"
) )
type Cache[V any] interface { type Cache[V any] interface {

View File

@ -1,3 +1,17 @@
// Copyright © 2024 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package localcache package localcache
import ( import (

View File

@ -1,3 +1,17 @@
// Copyright © 2024 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package link package link
import ( import (

View File

@ -1,3 +1,17 @@
// Copyright © 2024 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package link package link
import ( import (

View File

@ -1,3 +1,17 @@
// Copyright © 2024 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package lru package lru
import "github.com/hashicorp/golang-lru/v2/simplelru" import "github.com/hashicorp/golang-lru/v2/simplelru"

View File

@ -1,9 +1,24 @@
// Copyright © 2024 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package lru package lru
import ( import (
"github.com/hashicorp/golang-lru/v2/expirable"
"sync" "sync"
"time" "time"
"github.com/hashicorp/golang-lru/v2/expirable"
) )
func NewExpirationLRU[K comparable, V any](size int, successTTL, failedTTL time.Duration, target Target, onEvict EvictCallback[K, V]) LRU[K, V] { func NewExpirationLRU[K comparable, V any](size int, successTTL, failedTTL time.Duration, target Target, onEvict EvictCallback[K, V]) LRU[K, V] {

View File

@ -1,9 +1,24 @@
// Copyright © 2024 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package lru package lru
import ( import (
"github.com/hashicorp/golang-lru/v2/simplelru"
"sync" "sync"
"time" "time"
"github.com/hashicorp/golang-lru/v2/simplelru"
) )
type layLruItem[V any] struct { type layLruItem[V any] struct {

View File

@ -1,3 +1,17 @@
// Copyright © 2024 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package lru package lru
import ( import (

View File

@ -1,3 +1,17 @@
// Copyright © 2024 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package lru package lru
func NewSlotLRU[K comparable, V any](slotNum int, hash func(K) uint64, create func() LRU[K, V]) LRU[K, V] { func NewSlotLRU[K comparable, V any](slotNum int, hash func(K) uint64, create func() LRU[K, V]) LRU[K, V] {

View File

@ -1,9 +1,24 @@
// Copyright © 2024 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package localcache package localcache
import ( import (
"context" "context"
"github.com/openimsdk/localcache/lru"
"time" "time"
"github.com/openimsdk/localcache/lru"
) )
func defaultOption() *option { func defaultOption() *option {

View File

@ -1,3 +1,17 @@
// Copyright © 2024 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package localcache package localcache
func AnyValue[V any](v any, err error) (V, error) { func AnyValue[V any](v any, err error) (V, error) {

View File

@ -1,3 +1,17 @@
// Copyright © 2024 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package rpccache package rpccache
func newListMap[V comparable](values []V, err error) (*listMap[V], error) { func newListMap[V comparable](values []V, err error) (*listMap[V], error) {

View File

@ -1,7 +1,22 @@
// Copyright © 2024 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package rpccache package rpccache
import ( import (
"context" "context"
pbconversation "github.com/OpenIMSDK/protocol/conversation" pbconversation "github.com/OpenIMSDK/protocol/conversation"
"github.com/OpenIMSDK/tools/errs" "github.com/OpenIMSDK/tools/errs"
"github.com/OpenIMSDK/tools/log" "github.com/OpenIMSDK/tools/log"

View File

@ -1,7 +1,22 @@
// Copyright © 2024 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package rpccache package rpccache
import ( import (
"context" "context"
"github.com/OpenIMSDK/tools/log" "github.com/OpenIMSDK/tools/log"
"github.com/openimsdk/localcache" "github.com/openimsdk/localcache"
"github.com/openimsdk/open-im-server/v3/pkg/common/cachekey" "github.com/openimsdk/open-im-server/v3/pkg/common/cachekey"
@ -49,7 +64,7 @@ func (f *FriendLocalCache) IsFriend(ctx context.Context, possibleFriendUserID, u
}, cachekey.GetFriendIDsKey(possibleFriendUserID))) }, cachekey.GetFriendIDsKey(possibleFriendUserID)))
} }
// IsBlack possibleBlackUserID selfUserID // IsBlack possibleBlackUserID selfUserID.
func (f *FriendLocalCache) IsBlack(ctx context.Context, possibleBlackUserID, userID string) (val bool, err error) { func (f *FriendLocalCache) IsBlack(ctx context.Context, possibleBlackUserID, userID string) (val bool, err error) {
log.ZDebug(ctx, "FriendLocalCache IsBlack req", "possibleBlackUserID", possibleBlackUserID, "userID", userID) log.ZDebug(ctx, "FriendLocalCache IsBlack req", "possibleBlackUserID", possibleBlackUserID, "userID", userID)
defer func() { defer func() {

View File

@ -1,7 +1,22 @@
// Copyright © 2024 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package rpccache package rpccache
import ( import (
"context" "context"
"github.com/OpenIMSDK/protocol/sdkws" "github.com/OpenIMSDK/protocol/sdkws"
"github.com/OpenIMSDK/tools/errs" "github.com/OpenIMSDK/tools/errs"
"github.com/OpenIMSDK/tools/log" "github.com/OpenIMSDK/tools/log"

View File

@ -1,8 +1,23 @@
// Copyright © 2024 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package rpccache package rpccache
import ( import (
"context" "context"
"encoding/json" "encoding/json"
"github.com/OpenIMSDK/tools/log" "github.com/OpenIMSDK/tools/log"
"github.com/redis/go-redis/v9" "github.com/redis/go-redis/v9"
) )

View File

@ -1,7 +1,22 @@
// Copyright © 2024 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package rpccache package rpccache
import ( import (
"context" "context"
"github.com/OpenIMSDK/protocol/sdkws" "github.com/OpenIMSDK/protocol/sdkws"
"github.com/OpenIMSDK/tools/errs" "github.com/OpenIMSDK/tools/errs"
"github.com/OpenIMSDK/tools/log" "github.com/OpenIMSDK/tools/log"

View File

@ -49,11 +49,7 @@ func NewGroupRpcClient(discov discoveryregistry.SvcDiscoveryRegistry, config *co
return GroupRpcClient(*NewGroup(discov, config)) return GroupRpcClient(*NewGroup(discov, config))
} }
func (g *GroupRpcClient) GetGroupInfos( func (g *GroupRpcClient) GetGroupInfos(ctx context.Context, groupIDs []string, complete bool) ([]*sdkws.GroupInfo, error) {
ctx context.Context,
groupIDs []string,
complete bool,
) ([]*sdkws.GroupInfo, error) {
resp, err := g.Client.GetGroupsInfo(ctx, &group.GetGroupsInfoReq{ resp, err := g.Client.GetGroupsInfo(ctx, &group.GetGroupsInfoReq{
GroupIDs: groupIDs, GroupIDs: groupIDs,
}) })
@ -184,11 +180,7 @@ func (g *GroupRpcClient) GetGroupInfoCache(ctx context.Context, groupID string)
return resp.GroupInfo, nil return resp.GroupInfo, nil
} }
func (g *GroupRpcClient) GetGroupMemberCache( func (g *GroupRpcClient) GetGroupMemberCache(ctx context.Context, groupID string, groupMemberID string) (*sdkws.GroupMemberFullInfo, error) {
ctx context.Context,
groupID string,
groupMemberID string,
) (*sdkws.GroupMemberFullInfo, error) {
resp, err := g.Client.GetGroupMemberCache(ctx, &group.GetGroupMemberCacheReq{ resp, err := g.Client.GetGroupMemberCache(ctx, &group.GetGroupMemberCacheReq{
GroupID: groupID, GroupID: groupID,
GroupMemberID: groupMemberID, GroupMemberID: groupMemberID,

View File

@ -126,10 +126,7 @@ func (f *FriendNotificationSender) UserInfoUpdatedNotification(ctx context.Conte
return f.Notification(ctx, mcontext.GetOpUserID(ctx), changedUserID, constant.UserInfoUpdatedNotification, &tips) return f.Notification(ctx, mcontext.GetOpUserID(ctx), changedUserID, constant.UserInfoUpdatedNotification, &tips)
} }
func (f *FriendNotificationSender) FriendApplicationAddNotification( func (f *FriendNotificationSender) FriendApplicationAddNotification(ctx context.Context, req *pbfriend.ApplyToAddFriendReq) error {
ctx context.Context,
req *pbfriend.ApplyToAddFriendReq,
) error {
tips := sdkws.FriendApplicationTips{FromToUserID: &sdkws.FromToUserID{ tips := sdkws.FriendApplicationTips{FromToUserID: &sdkws.FromToUserID{
FromUserID: req.FromUserID, FromUserID: req.FromUserID,
ToUserID: req.ToUserID, ToUserID: req.ToUserID,

View File

@ -21,10 +21,6 @@
# checks them out to a branch named: # checks them out to a branch named:
# automated-cherry-pick-of-<pr>-<target branch>-<timestamp> # automated-cherry-pick-of-<pr>-<target branch>-<timestamp>
OPENIM_ROOT=$(dirname "${BASH_SOURCE[0]}")/.. OPENIM_ROOT=$(dirname "${BASH_SOURCE[0]}")/..
source "${OPENIM_ROOT}/scripts/lib/init.sh" source "${OPENIM_ROOT}/scripts/lib/init.sh"

View File

@ -25,5 +25,5 @@ OPENIM_ROOT=$(dirname "${BASH_SOURCE[0]}")/..
source "${OPENIM_ROOT}/scripts/install/common.sh" source "${OPENIM_ROOT}/scripts/install/common.sh"
openim::log::info "\n# Use Docker to start all openim service" openim::log::info "\n# Use Docker to start all openim service"
trap 'openim::util::onCtrlC' INT trap 'openim::util::onCtrlC' INT
"${OPENIM_ROOT}"/scripts/start-all.sh "${OPENIM_ROOT}"/scripts/start-all.sh 2>&1 &
tail -f ${DOCKER_LOG_FILE} tail -f ${DOCKER_LOG_FILE}

View File

@ -150,6 +150,12 @@ process_file() {
exit 1 exit 1
fi fi
if [[ -n "${env_cmd}" ]]; then if [[ -n "${env_cmd}" ]]; then
{
printf "debugggggggggggggggggggg file: %s template: %s\n" "${ENV_FILE}" "${template}"
} | tee /tmp/debug.log
eval "$env_cmd ${OPENIM_ROOT}/scripts/genconfig.sh '${ENV_FILE}' '${template}' > '${output_file}'" || { eval "$env_cmd ${OPENIM_ROOT}/scripts/genconfig.sh '${ENV_FILE}' '${template}' > '${output_file}'" || {
openim::log::error "Error processing template file ${template}" openim::log::error "Error processing template file ${template}"
exit 1 exit 1

View File

@ -58,7 +58,6 @@ openim::tools::pre_start_name() {
local targets=( local targets=(
ncpu ncpu
component component
up35
) )
echo "${targets[@]}" echo "${targets[@]}"
} }

View File

@ -932,7 +932,7 @@ openim::test::set_group_info() {
{ {
"groupInfoForSet": { "groupInfoForSet": {
"groupID": "${1}", "groupID": "${1}",
"groupName": "new-name", "groupName": "new group name",
"notification": "new notification", "notification": "new notification",
"introduction": "new introduction", "introduction": "new introduction",
"faceURL": "www.newfaceURL.com", "faceURL": "www.newfaceURL.com",
@ -1076,6 +1076,7 @@ function openim::test::group() {
local GROUP_ID=$RANDOM local GROUP_ID=$RANDOM
local GROUP_ID2=$RANDOM local GROUP_ID2=$RANDOM
# Assumes that TEST_GROUP_ID, USER_ID, and other necessary IDs are set as environment variables before running this suite. # Assumes that TEST_GROUP_ID, USER_ID, and other necessary IDs are set as environment variables before running this suite.
# 0. Register a friend user. # 0. Register a friend user.
openim::test::user_register "${USER_ID}" "group00" "new_face_url" openim::test::user_register "${USER_ID}" "group00" "new_face_url"
@ -1272,7 +1273,7 @@ openim::test::search_msg() {
{ {
"sendID": "${sendID}", "sendID": "${sendID}",
"recvID": "${recvID}", "recvID": "${recvID}",
"msgType": ${msgType}, "contentType": ${msgType},
"sendTime": "${sendTime}", "sendTime": "${sendTime}",
"sessionType": ${sessionType}, "sessionType": ${sessionType},
"pagination": { "pagination": {

View File

@ -1,46 +0,0 @@
#!/usr/bin/env bash
# Copyright © 2023 OpenIM. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# This script verifies whether codes follow golang convention.
# Usage: `scripts/verify-pkg-names.sh`.
set -o errexit
OPENIM_ROOT=$(dirname "${BASH_SOURCE[0]}")/..
source "${OPENIM_ROOT}/scripts/lib/init.sh"
openim::golang::verify_go_version
openim::golang::verify_go_version
OPENIM_OUTPUT_HOSTBIN_TOOLS="${OPENIM_ROOT}/_output/bin/tools/linux/amd64"
CODESCAN_BINARY="${OPENIM_OUTPUT_HOSTBIN_TOOLS}/codescan"
if [[ ! -f "${CODESCAN_BINARY}" ]]; then
echo "codescan binary not found, building..."
pushd "${OPENIM_ROOT}" >/dev/null
make build BINS="codescan"
popd >/dev/null
fi
if [[ ! -f "${CODESCAN_BINARY}" ]]; then
echo "Failed to build codescan binary."
exit 1
fi
CONFIG_PATH="${OPENIM_ROOT}/tools/codescan/config.yaml"
"${CODESCAN_BINARY}" -config "${CONFIG_PATH}"

View File

@ -87,6 +87,7 @@ disabled=(
2178 2178
2064 2064
2260 2260
2261
2043 2043
2178 2178
2044 2044

View File

@ -1,104 +0,0 @@
// Copyright © 2024 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package checker
import (
"bufio"
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
"github.com/openimsdk/open-im-server/tools/codescan/config"
)
type CheckResult struct {
FilePath string
Lines []int
}
func checkFileForChineseComments(filePath string) ([]CheckResult, error) {
file, err := os.Open(filePath)
if err != nil {
return nil, err
}
defer file.Close()
var results []CheckResult
scanner := bufio.NewScanner(file)
reg := regexp.MustCompile(`[\p{Han}]+`)
lineNumber := 0
var linesWithChinese []int
for scanner.Scan() {
lineNumber++
if reg.FindString(scanner.Text()) != "" {
linesWithChinese = append(linesWithChinese, lineNumber)
}
}
if len(linesWithChinese) > 0 {
results = append(results, CheckResult{
FilePath: filePath,
Lines: linesWithChinese,
})
}
if err := scanner.Err(); err != nil {
return nil, err
}
return results, nil
}
func WalkDirAndCheckComments(cfg config.Config) error {
var allResults []CheckResult
err := filepath.Walk(cfg.Directory, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return nil
}
for _, fileType := range cfg.FileTypes {
if filepath.Ext(path) == fileType {
results, err := checkFileForChineseComments(path)
if err != nil {
return err
}
if len(results) > 0 {
allResults = append(allResults, results...)
}
}
}
return nil
})
if err != nil {
return err
}
if len(allResults) > 0 {
var errMsg strings.Builder
errMsg.WriteString("Files containing Chinese comments:\n")
for _, result := range allResults {
errMsg.WriteString(fmt.Sprintf("%s: Lines %v\n", result.FilePath, result.Lines))
}
return fmt.Errorf(errMsg.String())
}
return nil
}

View File

@ -1,34 +0,0 @@
// Copyright © 2024 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"log"
"github.com/openimsdk/open-im-server/tools/codescan/checker"
"github.com/openimsdk/open-im-server/tools/codescan/config"
)
func main() {
cfg, err := config.ParseConfig()
if err != nil {
log.Fatalf("Error parsing config: %v", err)
}
err = checker.WalkDirAndCheckComments(cfg)
if err != nil {
panic(err)
}
}

View File

@ -1,49 +0,0 @@
// Copyright © 2024 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package config
import (
"flag"
"log"
"os"
"gopkg.in/yaml.v2"
)
type Config struct {
Directory string `yaml:"directory"`
FileTypes []string `yaml:"file_types"`
Languages []string `yaml:"languages"`
}
func ParseConfig() (Config, error) {
var configPath string
flag.StringVar(&configPath, "config", "./", "Path to config file")
flag.Parse()
var config Config
if configPath != "" {
configFile, err := os.ReadFile(configPath)
if err != nil {
return Config{}, err
}
if err := yaml.Unmarshal(configFile, &config); err != nil {
return Config{}, err
}
} else {
log.Fatal("Config file must be provided")
}
return config, nil
}

View File

@ -1,3 +0,0 @@
module github.com/openimsdk/open-im-server/tools/codescan
go 1.19

View File

@ -30,8 +30,9 @@ import (
"github.com/OpenIMSDK/tools/component" "github.com/OpenIMSDK/tools/component"
"github.com/OpenIMSDK/tools/errs" "github.com/OpenIMSDK/tools/errs"
"github.com/openimsdk/open-im-server/v3/pkg/common/config"
"gopkg.in/yaml.v3" "gopkg.in/yaml.v3"
"github.com/openimsdk/open-im-server/v3/pkg/common/config"
) )
const ( const (
@ -65,6 +66,23 @@ type checkFunc struct {
config *config.GlobalConfig config *config.GlobalConfig
} }
// colorErrPrint prints formatted string in red to stderr
func colorErrPrint(msg string) {
// ANSI escape code for red text
const redColor = "\033[31m"
// ANSI escape code to reset color
const resetColor = "\033[0m"
msg = redColor + msg + resetColor
// Print to stderr in red
fmt.Fprintf(os.Stderr, "%s\n", msg)
}
func colorSuccessPrint(format string, a ...interface{}) {
// ANSI escape code for green text is \033[32m
// \033[0m resets the color
fmt.Printf("\033[32m"+format+"\033[0m", a...)
}
func main() { func main() {
flag.Parse() flag.Parse()
@ -81,13 +99,14 @@ func main() {
} }
checks := []checkFunc{ checks := []checkFunc{
//{name: "Mysql", function: checkMysql},
{name: "Mongo", function: checkMongo, config: conf}, {name: "Mongo", function: checkMongo, config: conf},
{name: "Redis", function: checkRedis, config: conf}, {name: "Redis", function: checkRedis, config: conf},
{name: "Minio", function: checkMinio, config: conf},
{name: "Zookeeper", function: checkZookeeper, config: conf}, {name: "Zookeeper", function: checkZookeeper, config: conf},
{name: "Kafka", function: checkKafka, config: conf}, {name: "Kafka", function: checkKafka, config: conf},
} }
if conf.Object.Enable == "minio" {
checks = append(checks, checkFunc{name: "Minio", function: checkMinio, config: conf})
}
for i := 0; i < maxRetry; i++ { for i := 0; i < maxRetry; i++ {
if i != 0 { if i != 0 {
@ -102,12 +121,12 @@ func main() {
err = check.function(check.config) err = check.function(check.config)
if err != nil { if err != nil {
allSuccess = false allSuccess = false
component.ErrorPrint(fmt.Sprintf("Check component: %s, failed: %s", check.name, err.Error())) colorErrPrint(fmt.Sprintf("Check component: %s, failed: %v", check.name, err.Error()))
if check.name == "Minio" { if check.name == "Minio" {
if errors.Is(err, errMinioNotEnabled) || if errors.Is(err, errMinioNotEnabled) ||
errors.Is(err, errSignEndPoint) || errors.Is(err, errSignEndPoint) ||
errors.Is(err, errApiURL) { errors.Is(err, errApiURL) {
fmt.Fprintf(os.Stderr, err.Error(), " check ", check.name)
checks[index].flag = true checks[index].flag = true
continue continue
} }
@ -118,6 +137,7 @@ func main() {
component.SuccessPrint(fmt.Sprintf("%s connected successfully", check.name)) component.SuccessPrint(fmt.Sprintf("%s connected successfully", check.name))
} }
} }
} }
if allSuccess { if allSuccess {
component.SuccessPrint("All components started successfully!") component.SuccessPrint("All components started successfully!")
@ -296,7 +316,7 @@ func configGetEnv(config *config.GlobalConfig) error {
config.Redis.Username = getEnv("REDIS_USERNAME", config.Redis.Username) config.Redis.Username = getEnv("REDIS_USERNAME", config.Redis.Username)
config.Redis.Password = getEnv("REDIS_PASSWORD", config.Redis.Password) config.Redis.Password = getEnv("REDIS_PASSWORD", config.Redis.Password)
config.Redis.Address = getArrEnv("REDIS_ADDRESS", "REDIS_PASSWORD", config.Redis.Address) config.Redis.Address = getArrEnv("REDIS_ADDRESS", "REDIS_PORT", config.Redis.Address)
config.Object.ApiURL = getEnv("OBJECT_APIURL", config.Object.ApiURL) config.Object.ApiURL = getEnv("OBJECT_APIURL", config.Object.ApiURL)
config.Object.Minio.Endpoint = getEnv("MINIO_ENDPOINT", config.Object.Minio.Endpoint) config.Object.Minio.Endpoint = getEnv("MINIO_ENDPOINT", config.Object.Minio.Endpoint)

View File

@ -1,98 +0,0 @@
# OpenIM V2 至 V3 数据迁移指南
该指南提供了从 OpenIM V2 迁移至 V3 的详细步骤。请确保在开始迁移过程之前,熟悉所有步骤,并按照指南准确执行。
+ [OpenIM Chat](https://github.com/OpenIMSDK/chat)
+ [OpenIM Server](https://github.com/OpenIMSDK/Open-IM-Server)
### 1. 数据备份
在开始数据迁移之前,强烈建议备份所有相关的数据以防止任何可能的数据丢失。
### 2. 迁移 OpenIM MySQL 数据
+ 位置: `open-im-server/tools/data-conversion/openim/cmd/conversion-mysql.go`
+ 配置 `conversion-mysql.go` 文件中的数据库信息。
+ 手动创建 V3 版本的数据库,并确保字符集为 `utf8mb4`
```bash
// V2 数据库配置
var (
usernameV2 = "root"
passwordV2 = "openIM"
addrV2 = "127.0.0.1:13306"
databaseV2 = "openIM_v2"
)
// V3 数据库配置
var (
usernameV3 = "root"
passwordV3 = "openIM123"
addrV3 = "127.0.0.1:13306"
databaseV3 = "openim_v3"
)
```
**执行数据迁移命令:**
```bash
make build BINS="conversion-mysql"
```
启动的二进制在 `_output/bin/tools`
### 3. 转换聊天消息(可选)
+ 只支持转换存储在 Kafka 中的消息。
+ 位置: `open-im-server/tools/data-conversion/openim/conversion-msg/conversion-msg.go`
+ 配置 `msg.go` 文件中的消息和服务器信息。
```bash
var (
topic = "ws2ms_chat" // V2 版本 Kafka 主题
kafkaAddr = "127.0.0.1:9092" // V2 版本 Kafka 地址
rpcAddr = "127.0.0.1:10130" // V3 版本 RPC 地址
adminUserID = "openIM123456" // V3 版本管理员用户ID
concurrency = 4 // 并发数量
)
```
**执行数据迁移命令:**
```bash
make build BINS="conversion-msg"
```
### 4. 转换业务服务器数据
+ 只支持转换存储在 Kafka 中的消息。
+ 位置: `open-im-server/tools/data-conversion/chat/cmd/conversion-chat/chat.go`
+ 需要手动创建 V3 版本的数据库,并确保字符集为 `utf8mb4`
+ 配置 `main.go` 文件中的数据库信息。
```bash
// V2 数据库配置
var (
usernameV2 = "root"
passwordV2 = "openIM"
addrV2 = "127.0.0.1:13306"
databaseV2 = "admin_chat"
)
// V3 数据库配置
var (
usernameV3 = "root"
passwordV3 = "openIM123"
addrV3 = "127.0.0.1:13306"
databaseV3 = "openim_enterprise"
)
```
**执行数据迁移命令:**
```bash
make build BINS="conversion-chat"
```

View File

@ -1,77 +0,0 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"fmt"
"log"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"github.com/openimsdk/open-im-server/v3/tools/data-conversion/chat/conversion"
"github.com/openimsdk/open-im-server/v3/tools/data-conversion/utils"
)
func main() {
var (
usernameV2 = "root" // Username for MySQL v2 version
passwordV2 = "openIM" // Password for MySQL v2 version
addrV2 = "127.0.0.1:13306" // Address for MySQL v2 version
databaseV2 = "admin_chat" // Database name for MySQL v2 version
)
var (
usernameV3 = "root" // Username for MySQL v3 version
passwordV3 = "openIM123" // Password for MySQL v3 version
addrV3 = "127.0.0.1:13306" // Address for MySQL v3 version
databaseV3 = "openim_enterprise" // Database name for MySQL v3 version
)
var concurrency = 1 // Concurrency quantity
log.SetFlags(log.LstdFlags | log.Llongfile)
dsnV2 := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", usernameV2, passwordV2, addrV2, databaseV2)
dsnV3 := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", usernameV3, passwordV3, addrV3, databaseV3)
dbV2, err := gorm.Open(mysql.Open(dsnV2), &gorm.Config{Logger: logger.Discard})
if err != nil {
log.Println("open v2 db failed", err)
return
}
dbV3, err := gorm.Open(mysql.Open(dsnV3), &gorm.Config{Logger: logger.Discard})
if err != nil {
log.Println("open v3 db failed", err)
return
}
var tasks utils.TakeList
tasks.Append(func() (string, error) { return utils.FindAndInsert(dbV2, dbV3, conversion.Account) })
tasks.Append(func() (string, error) { return utils.FindAndInsert(dbV2, dbV3, conversion.Attribute) })
tasks.Append(func() (string, error) { return utils.FindAndInsert(dbV2, dbV3, conversion.Register) })
tasks.Append(func() (string, error) { return utils.FindAndInsert(dbV2, dbV3, conversion.UserLoginRecord) })
tasks.Append(func() (string, error) { return utils.FindAndInsert(dbV2, dbV3, conversion.Admin) })
tasks.Append(func() (string, error) { return utils.FindAndInsert(dbV2, dbV3, conversion.Applet) })
tasks.Append(func() (string, error) { return utils.FindAndInsert(dbV2, dbV3, conversion.ForbiddenAccount) })
tasks.Append(func() (string, error) { return utils.FindAndInsert(dbV2, dbV3, conversion.InvitationRegister) })
tasks.Append(func() (string, error) { return utils.FindAndInsert(dbV2, dbV3, conversion.IPForbidden) })
tasks.Append(func() (string, error) { return utils.FindAndInsert(dbV2, dbV3, conversion.LimitUserLoginIP) })
tasks.Append(func() (string, error) { return utils.FindAndInsert(dbV2, dbV3, conversion.RegisterAddFriend) })
tasks.Append(func() (string, error) { return utils.FindAndInsert(dbV2, dbV3, conversion.RegisterAddGroup) })
utils.RunTask(concurrency, tasks)
}

View File

@ -1,167 +0,0 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package conversion
import (
v2 "github.com/openimsdk/open-im-server/v3/tools/data-conversion/chat/v2"
"github.com/openimsdk/open-im-server/v3/tools/data-conversion/chat/v3/admin"
"github.com/openimsdk/open-im-server/v3/tools/data-conversion/chat/v3/chat"
"github.com/openimsdk/open-im-server/v3/tools/data-conversion/utils"
)
// ########## chat ##########
func Account(v v2.Account) (chat.Account, bool) {
utils.InitTime(&v.CreateTime, &v.ChangeTime)
return chat.Account{
UserID: v.UserID,
Password: v.Password,
CreateTime: v.CreateTime,
ChangeTime: v.ChangeTime,
OperatorUserID: v.OperatorUserID,
}, true
}
func Attribute(v v2.Attribute) (chat.Attribute, bool) {
utils.InitTime(&v.CreateTime, &v.ChangeTime, &v.BirthTime)
return chat.Attribute{
UserID: v.UserID,
Account: v.Account,
PhoneNumber: v.PhoneNumber,
AreaCode: v.AreaCode,
Email: v.Email,
Nickname: v.Nickname,
FaceURL: v.FaceURL,
Gender: v.Gender,
CreateTime: v.CreateTime,
ChangeTime: v.ChangeTime,
BirthTime: v.BirthTime,
Level: v.Level,
AllowVibration: v.AllowVibration,
AllowBeep: v.AllowBeep,
AllowAddFriend: v.AllowAddFriend,
GlobalRecvMsgOpt: 0,
}, true
}
func Register(v v2.Register) (chat.Register, bool) {
utils.InitTime(&v.CreateTime)
return chat.Register{
UserID: v.UserID,
DeviceID: v.DeviceID,
IP: v.IP,
Platform: v.Platform,
AccountType: v.AccountType,
Mode: v.Mode,
CreateTime: v.CreateTime,
}, true
}
func UserLoginRecord(v v2.UserLoginRecord) (chat.UserLoginRecord, bool) {
utils.InitTime(&v.LoginTime)
return chat.UserLoginRecord{
UserID: v.UserID,
LoginTime: v.LoginTime,
IP: v.IP,
DeviceID: v.DeviceID,
Platform: v.Platform,
}, true
}
// ########## admin ##########
func Admin(v v2.Admin) (admin.Admin, bool) {
utils.InitTime(&v.CreateTime)
return admin.Admin{
Account: v.Account,
Password: v.Password,
FaceURL: v.FaceURL,
Nickname: v.Nickname,
UserID: v.UserID,
Level: v.Level,
CreateTime: v.CreateTime,
}, true
}
func Applet(v v2.Applet) (admin.Applet, bool) {
utils.InitTime(&v.CreateTime)
return admin.Applet{
ID: v.ID,
Name: v.Name,
AppID: v.AppID,
Icon: v.Icon,
URL: v.URL,
MD5: v.MD5,
Size: v.Size,
Version: v.Version,
Priority: v.Priority,
Status: v.Status,
CreateTime: v.CreateTime,
}, true
}
func ForbiddenAccount(v v2.ForbiddenAccount) (admin.ForbiddenAccount, bool) {
utils.InitTime(&v.CreateTime)
return admin.ForbiddenAccount{
UserID: v.UserID,
Reason: v.Reason,
OperatorUserID: v.OperatorUserID,
CreateTime: v.CreateTime,
}, true
}
func InvitationRegister(v v2.InvitationRegister) (admin.InvitationRegister, bool) {
utils.InitTime(&v.CreateTime)
return admin.InvitationRegister{
InvitationCode: v.InvitationCode,
UsedByUserID: v.UsedByUserID,
CreateTime: v.CreateTime,
}, true
}
func IPForbidden(v v2.IPForbidden) (admin.IPForbidden, bool) {
utils.InitTime(&v.CreateTime)
return admin.IPForbidden{
IP: v.IP,
LimitRegister: v.LimitRegister > 0,
LimitLogin: v.LimitLogin > 0,
CreateTime: v.CreateTime,
}, true
}
func LimitUserLoginIP(v v2.LimitUserLoginIP) (admin.LimitUserLoginIP, bool) {
utils.InitTime(&v.CreateTime)
return admin.LimitUserLoginIP{
UserID: v.UserID,
IP: v.IP,
CreateTime: v.CreateTime,
}, true
}
func RegisterAddFriend(v v2.RegisterAddFriend) (admin.RegisterAddFriend, bool) {
utils.InitTime(&v.CreateTime)
return admin.RegisterAddFriend{
UserID: v.UserID,
CreateTime: v.CreateTime,
}, true
}
func RegisterAddGroup(v v2.RegisterAddGroup) (admin.RegisterAddGroup, bool) {
utils.InitTime(&v.CreateTime)
return admin.RegisterAddGroup{
GroupID: v.GroupID,
CreateTime: v.CreateTime,
}, true
}

View File

@ -1,77 +0,0 @@
// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package v2
import (
"time"
)
// AppVersion manages PC client versions
type AppVersion struct {
Version string `gorm:"column:version;size:64" json:"version"`
Type int `gorm:"column:type;primary_key" json:"type"`
UpdateTime int `gorm:"column:update_time" json:"update_time"`
ForceUpdate bool `gorm:"column:force_update" json:"force_update"`
FileName string `gorm:"column:file_name" json:"file_name"`
YamlName string `gorm:"column:yaml_name" json:"yaml_name"`
UpdateLog string `gorm:"column:update_log" json:"update_log"`
}
// Admin manages backend administrators
type Admin struct {
Account string `gorm:"column:account;primary_key;type:char(64)" json:"account"`
Password string `gorm:"column:Password;type:char(64)" json:"password"`
FaceURL string `gorm:"column:FaceURL;type:char(64)" json:"faceURL"`
Nickname string `gorm:"column:Nickname;type:char(64)" json:"nickname"`
UserID string `gorm:"column:UserID;type:char(64)" json:"userID"` //openIM userID
Level int32 `gorm:"column:level;default:1" json:"level"`
CreateTime time.Time `gorm:"column:create_time" json:"createTime"`
}
// RegisterAddFriend specifies default friends when registering
type RegisterAddFriend struct {
UserID string `gorm:"column:user_id;primary_key;type:char(64)" json:"userID"`
CreateTime time.Time `gorm:"column:create_time" json:"createTime"`
}
// RegisterAddGroup specifies default groups when registering
type RegisterAddGroup struct {
GroupID string `gorm:"column:group_id;primary_key;type:char(64)" json:"userID"`
CreateTime time.Time `gorm:"column:create_time" json:"createTime"`
}
// ClientInitConfig contains system-related configuration items
type ClientInitConfig struct {
DiscoverPageURL string `gorm:"column:discover_page_url;size:128" json:"discoverPageURL"`
OrdinaryUserAddFriend int32 `gorm:"column:ordinary_user_add_friend; default:1" json:"ordinaryUserAddFriend"`
BossUserID string `gorm:"column:boss_user_id;type:char(64)" json:"bossUserID"`
AdminURL string `gorm:"column:admin_url;type:char(128)" json:"adminURL"`
AllowSendMsgNotFriend int32 `gorm:"column:allow_send_msg_not_friend;default:1" json:"allowSendMsgNotFriend"`
NeedInvitationCodeRegister int32 `gorm:"column:need_invitation_code_register;default:0" json:"needInvitationCodeRegister"`
}
type Applet struct {
ID string `gorm:"column:id;primary_key;size:64"`
Name string `gorm:"column:name;uniqueIndex;size:64"`
AppID string `gorm:"column:app_id;uniqueIndex;size:255"`
Icon string `gorm:"column:icon;size:255"`
URL string `gorm:"column:url;size:255"`
MD5 string `gorm:"column:md5;size:255"`
Size int64 `gorm:"column:size"`
Version string `gorm:"column:version;size:64"`
Priority uint32 `gorm:"column:priority;size:64"`
Status uint8 `gorm:"column:status"`
CreateTime time.Time `gorm:"column:create_time;autoCreateTime;size:64"`
}

Some files were not shown because too many files have changed in this diff Show More