github.com/wfusion/gofusion@v1.1.14/README.md (about)

     1  - English README version: you are reading now =。= translated by openai chat gpt4
     2  - 中文 README: [README.md](assets/docs/zh/README.md)
     3  
     4  # Usage Limitations
     5  
     6  - golang: 1.18 - 1.22
     7  - os: windows / darwin / linux
     8  - arch: amd64 / arm64 / loong64
     9  
    10  # Introduction
    11  
    12  - Features: Highly configurable, highly extendable, high dependency replace ability, multi-component combinable, deeply
    13    integrated with dependency injection, facilitating efficient business development.
    14  - Supported Components: db, http, i18n, lock, cache, log, mongo, redis, mq, routine, cron, async, metrics
    15  - Special Features:
    16      - Supports YAML, JSON, TOML configuration file formats, highly configurable component parameters, with the ability
    17        to modify various component log switches at runtime.
    18      - Multiple db types supported: MySQL, Postgres, OpenGauss, SQLite, SQLServer, TiDB, ClickHouse, with nearly seamless
    19        dependency replacement.
    20      - Multiple mq types supported: RabbitMQ, Kafka, Pulsar, MySQL, Postgres, Redis, GoChannel, with seamless dependency
    21        replacement.
    22      - All components automatically register for dependency injection, aiding in building a system architecture based on
    23        dependency injection, utilizing uber/dig.
    24      - Distributed scheduled tasks, based on asynq.
    25      - Distributed asynchronous tasks, based on asynq.
    26      - HTTP services, scheduled tasks, asynchronous tasks, message queues all support router mode, with high freedom in
    27        registering function signatures.
    28      - Supports near and remote caching.
    29      - Multi-instance support for all components.
    30  - Comparison
    31      - Compared to microservice frameworks like go-zero, go-micro, kratos, jupiter, kitex, dubbo-go, tarsgo, Gofusion is not a microservices framework, but is designed for dependency integration and combination, and can be
    32        used in conjunction with other frameworks.
    33  
    34  # Quick Start
    35  
    36  > Gofusion quick start
    37  
    38  - Copy [test/config/configs/app.yml](test/config/configs/app.yml) to the `configs` directory in your business repository, or specify another location
    39    at startup with the `--config-file` parameter.
    40  - Initialize gofusion with the following code:
    41  
    42  ```go
    43  package main
    44  
    45  import "github.com/wfusion/gofusion/config"
    46  
    47  func main() {
    48  	appSetting := &struct{}{} // Business configuration object
    49  	defer config.Registry.Init(&appSetting)()
    50  }
    51  ```
    52  
    53  > fus quick start
    54  
    55  - fus currently supports compression encryption encoding, random number generation, gorm-gen, asynq official open-source
    56    command line, watermill official open-source command line.
    57  
    58  ```bash
    59  ~ > go install github.com/wfusion/gofusion/common/fus@master
    60  ~ > fus -h
    61  Gofusion CLI (v0.0.1 built with go1.18.10 darwin/arm64 from v1.1.4 on Sun Nov 12 18:05:03 CST 2023)
    62  
    63  Capability:
    64    asynq client integrated
    65    watermill client with pubsub kafka, ampq, and io enabled integerate
    66    gorm gentool integerate
    67    encoder&decoder with cipher, compress, and print encoding
    68    random bytes generater
    69  
    70  Usage:
    71    fus [command]
    72  
    73  Available Commands:
    74    asynq       A CLI for asynq
    75    completion  Generate the autocompletion script for the specified shell
    76    dec         Decode data from stdin or filename
    77    enc         Encode data from stdin or filename
    78    gorm        A CLI for gorm gen-tool
    79    help        Help about any command
    80    mill        A CLI for watermill
    81    rnd         Generate cryptographically secure random bytes
    82  
    83  Flags:
    84        --debug     print debug info
    85    -h, --help      help for fus
    86    -v, --version   version for fus
    87  
    88  Use "fus [command] --help" for more information about a command.
    89  ```
    90  
    91  # Unit Testing
    92  
    93  - Unit test report generated based on allure, [test result](assets/unittest/unittest.html)
    94  - Unit test coverage report generated based on github.com/nikolaydubina/go-cover-treemap, current coverage is 60%
    95  
    96  ![go-cover-treemap](assets/unittest/coverage.svg)
    97  
    98  # Feature Summary
    99  
   100  > Briefly describing gofusion capabilities
   101  
   102  ## Config
   103  
   104  > Configuration Component, primarily provides gofusion initialization, configuration parsing, and graceful exit
   105  > functionality for various components
   106  
   107  - Business configuration class no longer needs to declare dependent configurations; all configurations are under
   108    the `base` node in the yml file.
   109  - Components are automatically registered and gracefully exited in order based on business dependencies.
   110  - Supports specifying configuration files based on environmental variables.
   111  - Supports yaml, json, toml format configuration files (for example [app.yml](test/config/configs/app.yml)).
   112  - Supports Command line args (for example [args.example](test/config/configs/full_commandline_args.example)).
   113  - Supports multiple configuration priorities command line args > --config-file > app.local.yml > app.$env.yml > app.yml.
   114  - Supports global debug, correspondingly enables debug mode for gorm, gin.
   115  - Configurations support defining default values (`default: "{yaml format value}"`).
   116  - Supports specifying multiple configuration files using --config-file.
   117  - Supports auto reload of configuration content (mod time + sha256).
   118  - Automatically calls flag.Parse, so no need for business to call it manually.
   119  - Supports business objects implementing BeforeLoad and AfterLoad for callbacks before and after configuration loading.
   120  - Business can customize initialization context, and manage the lifecycle and metrics looping of various components'
   121    internal implementations through this context.
   122  - Supports encrypting passwords for db, mongo, redis through fus, and loading corresponding configurations from the
   123    configuration file in ciphertext.
   124  
   125  ## DB
   126  
   127  > Database Component, provides relational database encapsulation features, some types are still under development
   128  > testing...
   129  
   130  - Supports multiple DB configurations.
   131  - Based on gorm v2 supports mysql, postgres, opengauss, sqlite, sqlserver, tidb (untested), clickhouse (untested).
   132  - Supports string-specified gorm log objects, default gorm log can dynamically adjust at runtime, log level, high
   133    consumption threshold.
   134  - Supports nullable timestamp and bool soft delete fields, supports multiple soft delete field configurations in the
   135    same model, compatible with gorm.DeletedAt, compatible with sharding plugin.
   136  - Combined with lock component to provide distributed lock capability.
   137  - Encapsulated dal provides DalInterface interface, can use db.NewDAL directly, provides basic query, queryFirst,
   138    queryLast, count, pluck,
   139    take, insertOne, insertInBatch, save, update, updates, delete, firstOrCreate. For compatibility with other usages,
   140    provides ReadDB, WriteDB
   141    methods to return native -gorm.DB, provides IgnoreErr and CanIgnore encapsulation to help business avoid gorm no data
   142    return error when using first, last, pluck, task.
   143  - Encapsulated db.Scan function supports full table scan.
   144  - Encapsulated db.WithinTx function supports transactions.
   145  - Encapsulated common class definition for model.
   146  - Performance and latency dotting, currently no platform for reporting, temporarily unavailable.
   147  - Gorm auto increment id issue in associated entities, currently can be configured according to different databases,
   148    declared in the configuration file through
   149    auto_increment_increment, if mariaDB or MySQL will query database auto-increment step by default according to sql show
   150    variables like 'auto_increment_increment'. Gorm issue see [Issue #5814](https://github.com/go-gorm/gorm/issues/5814)
   151  
   152  > DB Sharding Plugin Features
   153  
   154  mysql, postgres, sqlserver all passed tests.
   155  
   156  - Supports multi-table sharding in one database, multi-column sharding in one table.
   157  - Supports raw SQL.
   158  - Supports AutoMigrate, DropTable.
   159  - Multi-columns can use expression aggregation, default large digit shift according to binary stitching.
   160  - Can shard table according to id column, default using snowflake algorithm, machine code is hash(host ip + local ip +
   161    pid) << 8 | last segment of local ipv4.
   162  - Supports custom suffix name, default is original_table_name_column1_column2_0, suffix is 1, or 01, 001 depending on
   163    the number of sharded tables.
   164  - Supports default table creation when creating, if the corresponding sharded table is not created, it will be created
   165    automatically, convenient for data migration.
   166  - Combined with DalInterface interface, its batch insert, Save, Delete all support automatic sharding, that is, entities
   167    of different tables can be processed.
   168  
   169  ## HTTP
   170  
   171  > HTTP component, provides HTTP component and error code encapsulation features
   172  
   173  - Supports function signatures other than gin.HandlerFunc, automatically parses parameters from param, query, body based
   174    on HTTP request content-type, and analyzes returned data based on returned error.
   175  - Supports various middlewares: cors cross-domain, original logic; logging for recording desensitized request logs; xss
   176    defense; trace id propagation, enhanced original logic; recover for exception capture, original logic; string-based
   177    middleware customization supported, yet this feature is temporarily unavailable.
   178  - Error message texts support i18n.
   179  - Error message texts support parameters (based on official golang text/template).
   180  - Supports custom responses, use http.Response directly or inherit http.Embed for customization, mainly for
   181    compatibility with various business usages.
   182  - Supports zero-copy gin.HandlerFunc based on gin framework, supports static filenames, supports io.ReadSeeker data
   183    streams.
   184  
   185  ## I18n
   186  
   187  > Internationalization component, provides internationalization text features
   188  
   189  - Supports multiple languages.
   190  - Supports defining variables.
   191  - Supports duplicate key detection, i.e., startup will fail if error code definitions are duplicated.
   192  
   193  ## Context
   194  
   195  > Context component, provides field passing functionality based on context
   196  
   197  - Supports initialization from gin based on HTTP component, compatible with past usages.
   198  - user id, trace id propagation.
   199  - In async component, supports user id, trace id, context.deadline propagation.
   200  - In db component, supports gorm transaction propagation.
   201  - In log component, supports automatic parsing and printing of user id, trace id information carried by context.
   202  
   203  ## Lock
   204  
   205  > Distributed Lock component, provides distributed lock functionality
   206  
   207  - Supports distributed locks based on Redis Lua, which are reentrant.
   208  - Supports distributed locks based on Redis SETNX managed with a timeout.
   209  - Supports distributed locks based on MySQL/MariaDB GET_LOCK/RELEASE_LOCK.
   210  - Supports distributed locks based on a MongoDB collection and unique key, which are reentrant.
   211  - Encapsulates lock.Within for distributed lock invocation.
   212  
   213  ## Cache
   214  
   215  > Cache component, provides data caching functionality
   216  
   217  - Supports near and remote caching, near-end uses github.com/bluele/gcache, remote currently only supports redis.
   218  - Near-end cache supports arc, lfu, lru, simple eviction policies, arc used by default.
   219  - Supports json, gob, msgpack, ctor for raw object encoding.
   220  - Supports zstd, zlib, s2, gzip, deflate for compressed cache data post-serialization.
   221  - Supports expiration time settings at the granularity of keys.
   222  - Different encoding and compression algorithm read compatibility, i.e., modifying encoding and compression algorithms
   223    does not affect the reading and parsing of historical data.
   224  
   225  ## Log
   226  
   227  > Log component, provides log printing and output functionality
   228  
   229  - Based on go.uber.org/zap, compatible with past usage.
   230  - Supports log.Fields as parameters directly brought into log printing.
   231  - Supports console and file output, configuration similar to before, mainly for compatibility with the past, console
   232    color output configurable.
   233  - Based on gopkg.in/natefinch/lumberjack.v2, supports automatic archiving of output files, defines maximum size, split
   234    cycle, maximum number, gzip compression for archived logs.
   235  - Supports printing real file location of log call records (not a fixed stack depth skipping solution, as gorm, redis,
   236    mongo custom log printing is not at a fixed stack depth).
   237  - Encapsulates TimeElapsed to record execution duration.
   238  
   239  ## Mongo
   240  
   241  > Mongo component, provides mongo functionality
   242  
   243  - Not yet encapsulated as an interface, nor provided dal encapsulation similar to db.
   244  - Supports custom log printing, filters out printable mongo commands.
   245  - Supports multiple mongo configurations.
   246  
   247  ## Redis
   248  
   249  > Redis component, provides redis functionality
   250  
   251  - Supports custom log printing, filters out non-printable redis commands.
   252  - Supports multiple redis configurations.
   253  - Supports combination with lock component, provides distributed lock capability.
   254  - Supports combination with cache component, provides caching capability.
   255  - Supports combination with cron component, provides scheduled task capability.
   256  - Supports combination with async component, provides asynchronous task capability.
   257  
   258  ## Message Queue
   259  
   260  > MQ component, provides message queue functionality
   261  
   262  - Based on github.com/ThreeDotsLabs/watermill, forked and modified for compatibility with Go1.21, adjustments made for
   263    each pubsub open-source implementation.
   264  - Supports amqp, rabbitmq, gochannel, kafka, pulsar, redis, mysql, postgres, all types passed all unit tests with
   265    consumer groups configured.
   266  - Supports both pub/sub and pub/router modes, both modes can be used simultaneously.
   267      - When using both modes with the same configuration, router and sub will compete for consumption with raw and
   268        default messages.
   269      - When using both modes with the same configuration, router and sub will consume event messages repeatedly.
   270      - When registering multiple routers with the same configuration, router and sub will compete for consumption with
   271        raw and default messages.
   272      - When registering multiple routers with the same configuration, using event will trigger panic as registration name
   273        must be event type name causing duplication.
   274  - Messages support default, raw, event types for publish/subscribe, raw is original message without encapsulation,
   275    default and event are gofusion-encoded messages.
   276      - Publish/subscribe default messages
   277          - Publisher uses Messages(), Objects() options to call Publish.
   278          - Subscriber uses Subscribe.
   279          - Router uses HandlerFunc, watermill.NoPublishHandlerFunc, watermill.HandlerFunc, custom func(ctx
   280            context.Context, payload *SerializableObj) error function for registration.
   281      - Publish/subscribe raw messages
   282          - Publisher uses Messages() option to call PublishRaw.
   283          - Subscriber uses SubscribeRaw.
   284          - Router uses HandlerFunc, watermill.NoPublishHandlerFunc, watermill.HandlerFunc, custom func(ctx
   285            context.Context, payload *SerializableObj) error function for registration.
   286      - Publish/subscribe event messages
   287          - Publisher initializes with NewEventPublisher, NewEventPublisherDI, uses Events() option to call PublishEvent.
   288          - Subscriber initializes with NewEventSubscriber, NewEventSubscriberDI, calls SubscribeEvent.
   289          - Router registers with EventHandler or EventHandlerWithMsg closure.
   290  - Consumer execution function can be customized to func(ctx context.Context, payload *SerializableObj) error.
   291  - Producers can directly pass message structures, auto-completes serialization and compression based on configuration,
   292    only valid for default and event messages.
   293  - Supports json, gob, msgpack, ctor for raw object serialization, only valid for default and event messages.
   294  - Supports post-serialization compression using zstd, zlib, s2, gzip, deflate, only valid for default and event
   295    messages.
   296  - Supports langs, user_id, trace_id, context.deadline downstream propagation.
   297  - Supports printing of business uuid and native id of messages, not propagated downstream.
   298  - Supports defining custom Event for production and consumption of events, or for distinguishing different messages
   299    within a single Topic for business distribution, TODO: message deduplication and outdated message discarding to be
   300    developed.
   301  
   302  ## Routine
   303  
   304  > Coroutine component, provides coroutine management and coroutine pool functionality
   305  
   306  - Provides global coroutine count management, defines maximum coroutine count and graceful exit for business services.
   307  - Supports debug mode, changes routine.Go, routine.Promise, and Pool.Submit calls to synchronous calls for easier
   308    testing and unit test writing.
   309  - Encapsulates routine.Go, routine.Goc for go func calls, allows graceful exit; Args option supports arbitrary function
   310    parameters, WaitGroup option supports Done call, Channel option supports receiving function returns.
   311  - routine.Loop, routine.Loopc compatible for certain business scenarios that don't require graceful exit.
   312  - Based on github.com/fanliao/go-promise, encapsulates routine.Promise, routine.WhenAll, routine.WhenAny for easy
   313    multi-coroutine calling and waiting, supports arbitrary parameters.
   314  - Based on github.com/panjf2000/ants/v2, encapsulates Pool interface for coroutine pool usage, supports arbitrary
   315    parameters.
   316  
   317  ## Cron
   318  
   319  > Distributed scheduled task component, provides distributed scheduled task scheduling and management functionality
   320  
   321  - Currently only supports asynq-based redis mode.
   322  - Single service instance supports multiple cron instances, distributed environment supports multiple triggers and
   323    workers, exhibiting stateless service characteristics when both are enabled.
   324  - Supports lock component integration to solve the issue of multiple trigger task re-distribution (without using lock
   325    component, use native unique option to avoid issue).
   326  - Scheduled task execution function can be customized to func(ctx context.Context, payload *JsonSerializable) error
   327    signature, payload will be automatically parsed in gofusion.
   328  - Scheduled task execution will carry cron_task_name and trace_id information in context.
   329  - Configuration file supports asynq timeout, payload (json format), retry, deadline feature configurations.
   330  - Besides configuring scheduled tasks in the configuration file, businesses can define custom task loader to append
   331    scheduled tasks.
   332  
   333  ## Async
   334  
   335  > Distributed asynchronous task component, provides distributed asynchronous task scheduling and management
   336  > functionality
   337  
   338  - Currently only supports asynq-based redis mode.
   339  - Supports langs, user_id, trace_id, context.deadline downstream propagation.
   340  - Single service instance supports multiple async instances, distributed environment supports multiple producers and
   341    consumers, exhibiting stateless service characteristics when both are enabled.
   342  - Asynchronous execution function can have a custom function signature, satisfying func(ctx context.Context, **selected
   343    serialization algorithm-supported one or more structures**) error, other parameters will be automatically parsed in
   344    gofusion.
   345  
   346  ## Metrics
   347  
   348  > Monitoring pinpoint
   349  
   350  - Currently only supports Prometheus, developed based on github.com/hashicorp/go-metrics, supports Prometheus's
   351    histogram pinpoint.
   352  - Supports pull and push modes.
   353  - Supports custom label constants.
   354  - Supports configuration of golang program's runtime pinpoint, each component's pinpoint as well as running program
   355    hostname, ip label appending.
   356  - Business pinpoint call passes golang channel, channel size and concurrency processing efficiency can be configured to
   357    avoid affecting business performance or duration.
   358  - Businesses can configure pinpoint, if pinpoint task channel is full, strategy is default to discard pinpoint,
   359    configurable timeout or without timeout options are available.
   360  
   361  ## Common
   362  
   363  > Common tools, providing frequently used functions and wrappers
   364  
   365  | Path            | Capability                                                                                                                                                                                                                                                                       |
   366  |:----------------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
   367  | constant        | Constants, includes: reflection types, common symbols, time format                                                                                                                                                                                                               |
   368  | constraint      | Generic constraints                                                                                                                                                                                                                                                              |
   369  | di              | Dependency Injection based on uber dig                                                                                                                                                                                                                                           |
   370  | env             | Retrieves runtime environment information                                                                                                                                                                                                                                        |
   371  | fus             | Gofusion CLI, usage details in binary, install: go install github.com/wfusion/gofusion/common/fus@master                                                                                                                                                                         |
   372  | infra           | Infrastructure, currently includes: mongo driver, common relational database drivers, redis driver, asynq asynchronous and scheduled task framework, watermill event-driven framework                                                                                            |
   373  | utils/cipher    | Encryption/Decryption, supports des, 3des, aes, sm4, rc4, chacha20poly1305, xchacha20poly1305 encryption algorithms, ebc, cbc, cfb, ctr, ofb, gcm encryption modes, supports streaming processing                                                                                |
   374  | utils/clone     | Supports deep copy of any type, based on github.com/huandu/go-clone                                                                                                                                                                                                              |
   375  | utils/cmp       | Supports comparison of common types                                                                                                                                                                                                                                              |
   376  | utils/compress  | Compression, supports zstd, zlib, s2, gzip, deflate compression algorithms, supports streaming processing, based on github.com/klauspost/compress                                                                                                                                |
   377  | utils/serialize | Serialization, supports gob, json, msgpack, cbor serialization algorithms                                                                                                                                                                                                        |
   378  | utils/sqlparser | SQL statement parsing, based on github.com/longbridgeapp/sqlparser and supports OFFSET FETCH statements                                                                                                                                                                          |
   379  | utils/encode    | Printable encoding, supports hex, base32, base32-hex, base64, base64-url, base64-raw, base64-raw-url encoding algorithms, supports streaming processing, encryption, compression, and printable encoding combinations for []byte input processing and stream processing wrapping |
   380  | utils/gomonkey  | Monkey patch, fork from github.com/agiledragon/gomonkey                                                                                                                                                                                                                          |
   381  | utils/inspect   | Supports private field read/write, supports function and reflect.Type retrieval based on string, inspired by github.com/chenzhuoyu/go-inspect                                                                                                                                    |
   382  | utils/pool.go   | Pooling generic encapsulation, by default provides pooled objects for bytes.Buffer and []byte                                                                                                                                                                                    |
   383  | utils/xxx.go    | Other common functions or wrappers, covering compare, context, conv, enum, func, heap, ip, json, map, number, options, random, reflect, sets, slice, sort, string, time                                                                                                          |
   384  
   385  # Thanks for
   386  
   387  > The repository we forked 
   388  
   389  - [hibiken/asynq](https://github.com/hibiken/asynq)
   390  - [ThreeDotsLabs/watermill](https://github.com/ThreeDotsLabs/watermill)
   391  - [hashicorp/go-metrics](https://github.com/hashicorp/go-metrics)
   392  - [huandu/go-clone](https://github.com/huandu/go-clone)
   393  - [chenzhuoyu/go-inspect](https://github.com/chenzhuoyu/go-inspect)
   394  - [agiledragon/gomonkey](https://github.com/agiledragon/gomonkey)
   395  - [fvbock/endless](https://github.com/fvbock/endless)
   396  - [longbridgeapp/sqlparser](https://github.com/longbridgeapp/sqlparser)
   397  - [jinzhu/configor](https://github.com/jinzhu/configor)
   398  - [go-gorm/postgres](https://github.com/go-gorm/postgres)
   399  - [natefinch/lumberjack](https://github.com/natefinch/lumberjack)
   400  - [glebarez/sqlite](https://github.com/glebarez/sqlite)
   401  
   402  # Todo List
   403  
   404  - [ ] metrics each component
   405  - [ ] mq component support event deduplication and outdated message discarding
   406  - [ ] config component support Apollo dynamic config with viper lib
   407  - [ ] http client wrapper for passing through trace id
   408  - [ ] support rpc component
   409  - [ ] support watermill type in cron and async components