This commit is contained in:
sk 2024-04-12 10:18:26 +08:00
parent 8102413ee5
commit cee39cff43
315 changed files with 28397 additions and 89 deletions

3
.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
.idea
.vscode

201
LICENSE Normal file
View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
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.

129
README.md
View File

@ -1,93 +1,44 @@
# goserver
## goserver
goserver 旨在做一个传统的CS结构的服务器框架
目前主要用于游戏服务器开发
框架还在不断努力完善中,如果你对它感兴趣,请关注它的动态或者参与进来
## Features
## Getting started
* 组件通过package的概念统一管理(可以理解为win32下的dll)由config来配置各个组件的特性参数
* goroutine通过Object进行包装以树型结构组织Object间的通信通过command(内部是chan),主要是为了预防chan滥用、失控从而造成各种死锁问题
* 提供了时间,任务,事务,计划工作,网络通讯,模块管理的内置组件
* 提供一套传统的游戏服务器架构(制作中...)
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
```
cd existing_repo
git remote add origin https://git.pogorockgames.com/mango-games/server/goserver.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](https://git.pogorockgames.com/mango-games/server/goserver/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## License
For open source projects, say how it is licensed.
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
## 模块说明
* +core 核心模块
* admin : http管理接口主要提供一种外部可以操控进程的可能
* basic : 基础的线程对象封装对象间内部通讯避免chan环锁现象树形管理object
* bulletin: 框架内建元素,提供通讯层的一些基础过滤器和通讯协议
* cmdline: 自建命令行,给控制台进程提供一种命令模式
* container: 框架用到的一些容器队列回收器线程安全list线程安全map
* i18n: 国际化配置
* logger: 日志接口
* module: 业务模块管理,提供统一的心跳管理,模块通过注册挂载到管理器
* mongo: mogodb相关配置
* netlib: 通讯模块支持TCP和WebSocket两种通讯方式
* profile: 性能统计相关,用于辅助查找性能热点
* schedule: 定时任务调度模块用于周期job处理每日凌晨400进行日志清理
* signal: 信号管理模块,hook操作系统的信号进行回调处理kill -2 PID
* task: 线程模块,提供线程池、实名线程和独立线程多种模式
* timer: 定时器有别于go内置的timer主要用于确保线程安全问题
* transact: 分布式事务,基于二段提交实现,协调多节点配合完成一件原子性操作
* utils: 工具接口
* zk: zookeeper接口用于分布式协调
* +srvlib core/netlib的扩展封装提供常用的客户端session和服务端service管理以及服务发现进一步封装使框架层达到拆箱即用
* action 内置常用的包重定向和中转操作
* handler 提供基本的session和service管理
* protocol 内置协议定义
* +examples 示例程序
* echoclient 回声客户端程序
* echoserver 回声服务端程序
* other timer和task使用示例
* txserver1 分布式事务节点1
* txserver2 分布式事务节点2
* +mmo 提供一套基本的服务器架构模板

Binary file not shown.

View File

@ -0,0 +1,149 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
syntax = "proto3";
package google.protobuf;
option csharp_namespace = "Google.Protobuf.WellKnownTypes";
option go_package = "github.com/golang/protobuf/ptypes/any";
option java_package = "com.google.protobuf";
option java_outer_classname = "AnyProto";
option java_multiple_files = true;
option objc_class_prefix = "GPB";
// `Any` contains an arbitrary serialized protocol buffer message along with a
// URL that describes the type of the serialized message.
//
// Protobuf library provides support to pack/unpack Any values in the form
// of utility functions or additional generated methods of the Any type.
//
// Example 1: Pack and unpack a message in C++.
//
// Foo foo = ...;
// Any any;
// any.PackFrom(foo);
// ...
// if (any.UnpackTo(&foo)) {
// ...
// }
//
// Example 2: Pack and unpack a message in Java.
//
// Foo foo = ...;
// Any any = Any.pack(foo);
// ...
// if (any.is(Foo.class)) {
// foo = any.unpack(Foo.class);
// }
//
// Example 3: Pack and unpack a message in Python.
//
// foo = Foo(...)
// any = Any()
// any.Pack(foo)
// ...
// if any.Is(Foo.DESCRIPTOR):
// any.Unpack(foo)
// ...
//
// Example 4: Pack and unpack a message in Go
//
// foo := &pb.Foo{...}
// any, err := ptypes.MarshalAny(foo)
// ...
// foo := &pb.Foo{}
// if err := ptypes.UnmarshalAny(any, foo); err != nil {
// ...
// }
//
// The pack methods provided by protobuf library will by default use
// 'type.googleapis.com/full.type.name' as the type URL and the unpack
// methods only use the fully qualified type name after the last '/'
// in the type URL, for example "foo.bar.com/x/y.z" will yield type
// name "y.z".
//
//
// JSON
// ====
// The JSON representation of an `Any` value uses the regular
// representation of the deserialized, embedded message, with an
// additional field `@type` which contains the type URL. Example:
//
// package google.profile;
// message Person {
// string first_name = 1;
// string last_name = 2;
// }
//
// {
// "@type": "type.googleapis.com/google.profile.Person",
// "firstName": <string>,
// "lastName": <string>
// }
//
// If the embedded message type is well-known and has a custom JSON
// representation, that representation will be embedded adding a field
// `value` which holds the custom JSON in addition to the `@type`
// field. Example (for message [google.protobuf.Duration][]):
//
// {
// "@type": "type.googleapis.com/google.protobuf.Duration",
// "value": "1.212s"
// }
//
message Any {
// A URL/resource name whose content describes the type of the
// serialized protocol buffer message.
//
// For URLs which use the scheme `http`, `https`, or no scheme, the
// following restrictions and interpretations apply:
//
// * If no scheme is provided, `https` is assumed.
// * The last segment of the URL's path must represent the fully
// qualified name of the type (as in `path/google.protobuf.Duration`).
// The name should be in a canonical form (e.g., leading "." is
// not accepted).
// * An HTTP GET on the URL must yield a [google.protobuf.Type][]
// value in binary format, or produce an error.
// * Applications are allowed to cache lookup results based on the
// URL, or have them precompiled into a binary to avoid any
// lookup. Therefore, binary compatibility needs to be preserved
// on changes to types. (Use versioned type names to manage
// breaking changes.)
//
// Schemes other than `http`, `https` (or the empty scheme) might be
// used with implementation specific semantics.
//
string type_url = 1;
// Must be a valid serialized protocol buffer of the above specified type.
bytes value = 2;
}

View File

@ -0,0 +1,210 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
syntax = "proto3";
package google.protobuf;
import "google/protobuf/source_context.proto";
import "google/protobuf/type.proto";
option csharp_namespace = "Google.Protobuf.WellKnownTypes";
option java_package = "com.google.protobuf";
option java_outer_classname = "ApiProto";
option java_multiple_files = true;
option objc_class_prefix = "GPB";
option go_package = "google.golang.org/genproto/protobuf/api;api";
// Api is a light-weight descriptor for an API Interface.
//
// Interfaces are also described as "protocol buffer services" in some contexts,
// such as by the "service" keyword in a .proto file, but they are different
// from API Services, which represent a concrete implementation of an interface
// as opposed to simply a description of methods and bindings. They are also
// sometimes simply referred to as "APIs" in other contexts, such as the name of
// this message itself. See https://cloud.google.com/apis/design/glossary for
// detailed terminology.
message Api {
// The fully qualified name of this interface, including package name
// followed by the interface's simple name.
string name = 1;
// The methods of this interface, in unspecified order.
repeated Method methods = 2;
// Any metadata attached to the interface.
repeated Option options = 3;
// A version string for this interface. If specified, must have the form
// `major-version.minor-version`, as in `1.10`. If the minor version is
// omitted, it defaults to zero. If the entire version field is empty, the
// major version is derived from the package name, as outlined below. If the
// field is not empty, the version in the package name will be verified to be
// consistent with what is provided here.
//
// The versioning schema uses [semantic
// versioning](http://semver.org) where the major version number
// indicates a breaking change and the minor version an additive,
// non-breaking change. Both version numbers are signals to users
// what to expect from different versions, and should be carefully
// chosen based on the product plan.
//
// The major version is also reflected in the package name of the
// interface, which must end in `v<major-version>`, as in
// `google.feature.v1`. For major versions 0 and 1, the suffix can
// be omitted. Zero major versions must only be used for
// experimental, non-GA interfaces.
//
//
string version = 4;
// Source context for the protocol buffer service represented by this
// message.
SourceContext source_context = 5;
// Included interfaces. See [Mixin][].
repeated Mixin mixins = 6;
// The source syntax of the service.
Syntax syntax = 7;
}
// Method represents a method of an API interface.
message Method {
// The simple name of this method.
string name = 1;
// A URL of the input message type.
string request_type_url = 2;
// If true, the request is streamed.
bool request_streaming = 3;
// The URL of the output message type.
string response_type_url = 4;
// If true, the response is streamed.
bool response_streaming = 5;
// Any metadata attached to the method.
repeated Option options = 6;
// The source syntax of this method.
Syntax syntax = 7;
}
// Declares an API Interface to be included in this interface. The including
// interface must redeclare all the methods from the included interface, but
// documentation and options are inherited as follows:
//
// - If after comment and whitespace stripping, the documentation
// string of the redeclared method is empty, it will be inherited
// from the original method.
//
// - Each annotation belonging to the service config (http,
// visibility) which is not set in the redeclared method will be
// inherited.
//
// - If an http annotation is inherited, the path pattern will be
// modified as follows. Any version prefix will be replaced by the
// version of the including interface plus the [root][] path if
// specified.
//
// Example of a simple mixin:
//
// package google.acl.v1;
// service AccessControl {
// // Get the underlying ACL object.
// rpc GetAcl(GetAclRequest) returns (Acl) {
// option (google.api.http).get = "/v1/{resource=**}:getAcl";
// }
// }
//
// package google.storage.v2;
// service Storage {
// rpc GetAcl(GetAclRequest) returns (Acl);
//
// // Get a data record.
// rpc GetData(GetDataRequest) returns (Data) {
// option (google.api.http).get = "/v2/{resource=**}";
// }
// }
//
// Example of a mixin configuration:
//
// apis:
// - name: google.storage.v2.Storage
// mixins:
// - name: google.acl.v1.AccessControl
//
// The mixin construct implies that all methods in `AccessControl` are
// also declared with same name and request/response types in
// `Storage`. A documentation generator or annotation processor will
// see the effective `Storage.GetAcl` method after inherting
// documentation and annotations as follows:
//
// service Storage {
// // Get the underlying ACL object.
// rpc GetAcl(GetAclRequest) returns (Acl) {
// option (google.api.http).get = "/v2/{resource=**}:getAcl";
// }
// ...
// }
//
// Note how the version in the path pattern changed from `v1` to `v2`.
//
// If the `root` field in the mixin is specified, it should be a
// relative path under which inherited HTTP paths are placed. Example:
//
// apis:
// - name: google.storage.v2.Storage
// mixins:
// - name: google.acl.v1.AccessControl
// root: acls
//
// This implies the following inherited HTTP annotation:
//
// service Storage {
// // Get the underlying ACL object.
// rpc GetAcl(GetAclRequest) returns (Acl) {
// option (google.api.http).get = "/v2/acls/{resource=**}:getAcl";
// }
// ...
// }
message Mixin {
// The fully qualified name of the interface which is included.
string name = 1;
// If non-empty specifies a path under which inherited HTTP paths
// are rooted.
string root = 2;
}

View File

@ -0,0 +1,167 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
//
// WARNING: The plugin interface is currently EXPERIMENTAL and is subject to
// change.
//
// protoc (aka the Protocol Compiler) can be extended via plugins. A plugin is
// just a program that reads a CodeGeneratorRequest from stdin and writes a
// CodeGeneratorResponse to stdout.
//
// Plugins written using C++ can use google/protobuf/compiler/plugin.h instead
// of dealing with the raw protocol defined here.
//
// A plugin executable needs only to be placed somewhere in the path. The
// plugin should be named "protoc-gen-$NAME", and will then be used when the
// flag "--${NAME}_out" is passed to protoc.
syntax = "proto2";
package google.protobuf.compiler;
option java_package = "com.google.protobuf.compiler";
option java_outer_classname = "PluginProtos";
option go_package = "github.com/golang/protobuf/protoc-gen-go/plugin;plugin_go";
import "google/protobuf/descriptor.proto";
// The version number of protocol compiler.
message Version {
optional int32 major = 1;
optional int32 minor = 2;
optional int32 patch = 3;
// A suffix for alpha, beta or rc release, e.g., "alpha-1", "rc2". It should
// be empty for mainline stable releases.
optional string suffix = 4;
}
// An encoded CodeGeneratorRequest is written to the plugin's stdin.
message CodeGeneratorRequest {
// The .proto files that were explicitly listed on the command-line. The
// code generator should generate code only for these files. Each file's
// descriptor will be included in proto_file, below.
repeated string file_to_generate = 1;
// The generator parameter passed on the command-line.
optional string parameter = 2;
// FileDescriptorProtos for all files in files_to_generate and everything
// they import. The files will appear in topological order, so each file
// appears before any file that imports it.
//
// protoc guarantees that all proto_files will be written after
// the fields above, even though this is not technically guaranteed by the
// protobuf wire format. This theoretically could allow a plugin to stream
// in the FileDescriptorProtos and handle them one by one rather than read
// the entire set into memory at once. However, as of this writing, this
// is not similarly optimized on protoc's end -- it will store all fields in
// memory at once before sending them to the plugin.
//
// Type names of fields and extensions in the FileDescriptorProto are always
// fully qualified.
repeated FileDescriptorProto proto_file = 15;
// The version number of protocol compiler.
optional Version compiler_version = 3;
}
// The plugin writes an encoded CodeGeneratorResponse to stdout.
message CodeGeneratorResponse {
// Error message. If non-empty, code generation failed. The plugin process
// should exit with status code zero even if it reports an error in this way.
//
// This should be used to indicate errors in .proto files which prevent the
// code generator from generating correct code. Errors which indicate a
// problem in protoc itself -- such as the input CodeGeneratorRequest being
// unparseable -- should be reported by writing a message to stderr and
// exiting with a non-zero status code.
optional string error = 1;
// Represents a single generated file.
message File {
// The file name, relative to the output directory. The name must not
// contain "." or ".." components and must be relative, not be absolute (so,
// the file cannot lie outside the output directory). "/" must be used as
// the path separator, not "\".
//
// If the name is omitted, the content will be appended to the previous
// file. This allows the generator to break large files into small chunks,
// and allows the generated text to be streamed back to protoc so that large
// files need not reside completely in memory at one time. Note that as of
// this writing protoc does not optimize for this -- it will read the entire
// CodeGeneratorResponse before writing files to disk.
optional string name = 1;
// If non-empty, indicates that the named file should already exist, and the
// content here is to be inserted into that file at a defined insertion
// point. This feature allows a code generator to extend the output
// produced by another code generator. The original generator may provide
// insertion points by placing special annotations in the file that look
// like:
// @@protoc_insertion_point(NAME)
// The annotation can have arbitrary text before and after it on the line,
// which allows it to be placed in a comment. NAME should be replaced with
// an identifier naming the point -- this is what other generators will use
// as the insertion_point. Code inserted at this point will be placed
// immediately above the line containing the insertion point (thus multiple
// insertions to the same point will come out in the order they were added).
// The double-@ is intended to make it unlikely that the generated code
// could contain things that look like insertion points by accident.
//
// For example, the C++ code generator places the following line in the
// .pb.h files that it generates:
// // @@protoc_insertion_point(namespace_scope)
// This line appears within the scope of the file's package namespace, but
// outside of any particular class. Another plugin can then specify the
// insertion_point "namespace_scope" to generate additional classes or
// other declarations that should be placed in this scope.
//
// Note that if the line containing the insertion point begins with
// whitespace, the same whitespace will be added to every line of the
// inserted text. This is useful for languages like Python, where
// indentation matters. In these languages, the insertion point comment
// should be indented the same amount as any inserted code will need to be
// in order to work correctly in that context.
//
// The code generator that generates the initial file and the one which
// inserts into it must both run as part of a single invocation of protoc.
// Code generators are executed in the order in which they appear on the
// command line.
//
// If |insertion_point| is present, |name| must also be present.
optional string insertion_point = 2;
// The file contents.
optional string content = 15;
}
repeated File file = 15;
}

View File

@ -0,0 +1,872 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
//
// The messages in this file describe the definitions found in .proto files.
// A valid .proto file can be translated directly to a FileDescriptorProto
// without any other information (e.g. without reading its imports).
syntax = "proto2";
package google.protobuf;
option go_package = "github.com/golang/protobuf/protoc-gen-go/descriptor;descriptor";
option java_package = "com.google.protobuf";
option java_outer_classname = "DescriptorProtos";
option csharp_namespace = "Google.Protobuf.Reflection";
option objc_class_prefix = "GPB";
option cc_enable_arenas = true;
// descriptor.proto must be optimized for speed because reflection-based
// algorithms don't work during bootstrapping.
option optimize_for = SPEED;
// The protocol compiler can output a FileDescriptorSet containing the .proto
// files it parses.
message FileDescriptorSet {
repeated FileDescriptorProto file = 1;
}
// Describes a complete .proto file.
message FileDescriptorProto {
optional string name = 1; // file name, relative to root of source tree
optional string package = 2; // e.g. "foo", "foo.bar", etc.
// Names of files imported by this file.
repeated string dependency = 3;
// Indexes of the public imported files in the dependency list above.
repeated int32 public_dependency = 10;
// Indexes of the weak imported files in the dependency list.
// For Google-internal migration only. Do not use.
repeated int32 weak_dependency = 11;
// All top-level definitions in this file.
repeated DescriptorProto message_type = 4;
repeated EnumDescriptorProto enum_type = 5;
repeated ServiceDescriptorProto service = 6;
repeated FieldDescriptorProto extension = 7;
optional FileOptions options = 8;
// This field contains optional information about the original source code.
// You may safely remove this entire field without harming runtime
// functionality of the descriptors -- the information is needed only by
// development tools.
optional SourceCodeInfo source_code_info = 9;
// The syntax of the proto file.
// The supported values are "proto2" and "proto3".
optional string syntax = 12;
}
// Describes a message type.
message DescriptorProto {
optional string name = 1;
repeated FieldDescriptorProto field = 2;
repeated FieldDescriptorProto extension = 6;
repeated DescriptorProto nested_type = 3;
repeated EnumDescriptorProto enum_type = 4;
message ExtensionRange {
optional int32 start = 1;
optional int32 end = 2;
optional ExtensionRangeOptions options = 3;
}
repeated ExtensionRange extension_range = 5;
repeated OneofDescriptorProto oneof_decl = 8;
optional MessageOptions options = 7;
// Range of reserved tag numbers. Reserved tag numbers may not be used by
// fields or extension ranges in the same message. Reserved ranges may
// not overlap.
message ReservedRange {
optional int32 start = 1; // Inclusive.
optional int32 end = 2; // Exclusive.
}
repeated ReservedRange reserved_range = 9;
// Reserved field names, which may not be used by fields in the same message.
// A given name may only be reserved once.
repeated string reserved_name = 10;
}
message ExtensionRangeOptions {
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
// Clients can define custom options in extensions of this message. See above.
extensions 1000 to max;
}
// Describes a field within a message.
message FieldDescriptorProto {
enum Type {
// 0 is reserved for errors.
// Order is weird for historical reasons.
TYPE_DOUBLE = 1;
TYPE_FLOAT = 2;
// Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if
// negative values are likely.
TYPE_INT64 = 3;
TYPE_UINT64 = 4;
// Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if
// negative values are likely.
TYPE_INT32 = 5;
TYPE_FIXED64 = 6;
TYPE_FIXED32 = 7;
TYPE_BOOL = 8;
TYPE_STRING = 9;
// Tag-delimited aggregate.
// Group type is deprecated and not supported in proto3. However, Proto3
// implementations should still be able to parse the group wire format and
// treat group fields as unknown fields.
TYPE_GROUP = 10;
TYPE_MESSAGE = 11; // Length-delimited aggregate.
// New in version 2.
TYPE_BYTES = 12;
TYPE_UINT32 = 13;
TYPE_ENUM = 14;
TYPE_SFIXED32 = 15;
TYPE_SFIXED64 = 16;
TYPE_SINT32 = 17; // Uses ZigZag encoding.
TYPE_SINT64 = 18; // Uses ZigZag encoding.
};
enum Label {
// 0 is reserved for errors
LABEL_OPTIONAL = 1;
LABEL_REQUIRED = 2;
LABEL_REPEATED = 3;
};
optional string name = 1;
optional int32 number = 3;
optional Label label = 4;
// If type_name is set, this need not be set. If both this and type_name
// are set, this must be one of TYPE_ENUM, TYPE_MESSAGE or TYPE_GROUP.
optional Type type = 5;
// For message and enum types, this is the name of the type. If the name
// starts with a '.', it is fully-qualified. Otherwise, C++-like scoping
// rules are used to find the type (i.e. first the nested types within this
// message are searched, then within the parent, on up to the root
// namespace).
optional string type_name = 6;
// For extensions, this is the name of the type being extended. It is
// resolved in the same manner as type_name.
optional string extendee = 2;
// For numeric types, contains the original text representation of the value.
// For booleans, "true" or "false".
// For strings, contains the default text contents (not escaped in any way).
// For bytes, contains the C escaped value. All bytes >= 128 are escaped.
// TODO(kenton): Base-64 encode?
optional string default_value = 7;
// If set, gives the index of a oneof in the containing type's oneof_decl
// list. This field is a member of that oneof.
optional int32 oneof_index = 9;
// JSON name of this field. The value is set by protocol compiler. If the
// user has set a "json_name" option on this field, that option's value
// will be used. Otherwise, it's deduced from the field's name by converting
// it to camelCase.
optional string json_name = 10;
optional FieldOptions options = 8;
}
// Describes a oneof.
message OneofDescriptorProto {
optional string name = 1;
optional OneofOptions options = 2;
}
// Describes an enum type.
message EnumDescriptorProto {
optional string name = 1;
repeated EnumValueDescriptorProto value = 2;
optional EnumOptions options = 3;
// Range of reserved numeric values. Reserved values may not be used by
// entries in the same enum. Reserved ranges may not overlap.
//
// Note that this is distinct from DescriptorProto.ReservedRange in that it
// is inclusive such that it can appropriately represent the entire int32
// domain.
message EnumReservedRange {
optional int32 start = 1; // Inclusive.
optional int32 end = 2; // Inclusive.
}
// Range of reserved numeric values. Reserved numeric values may not be used
// by enum values in the same enum declaration. Reserved ranges may not
// overlap.
repeated EnumReservedRange reserved_range = 4;
// Reserved enum value names, which may not be reused. A given name may only
// be reserved once.
repeated string reserved_name = 5;
}
// Describes a value within an enum.
message EnumValueDescriptorProto {
optional string name = 1;
optional int32 number = 2;
optional EnumValueOptions options = 3;
}
// Describes a service.
message ServiceDescriptorProto {
optional string name = 1;
repeated MethodDescriptorProto method = 2;
optional ServiceOptions options = 3;
}
// Describes a method of a service.
message MethodDescriptorProto {
optional string name = 1;
// Input and output type names. These are resolved in the same way as
// FieldDescriptorProto.type_name, but must refer to a message type.
optional string input_type = 2;
optional string output_type = 3;
optional MethodOptions options = 4;
// Identifies if client streams multiple client messages
optional bool client_streaming = 5 [default=false];
// Identifies if server streams multiple server messages
optional bool server_streaming = 6 [default=false];
}
// ===================================================================
// Options
// Each of the definitions above may have "options" attached. These are
// just annotations which may cause code to be generated slightly differently
// or may contain hints for code that manipulates protocol messages.
//
// Clients may define custom options as extensions of the *Options messages.
// These extensions may not yet be known at parsing time, so the parser cannot
// store the values in them. Instead it stores them in a field in the *Options
// message called uninterpreted_option. This field must have the same name
// across all *Options messages. We then use this field to populate the
// extensions when we build a descriptor, at which point all protos have been
// parsed and so all extensions are known.
//
// Extension numbers for custom options may be chosen as follows:
// * For options which will only be used within a single application or
// organization, or for experimental options, use field numbers 50000
// through 99999. It is up to you to ensure that you do not use the
// same number for multiple options.
// * For options which will be published and used publicly by multiple
// independent entities, e-mail protobuf-global-extension-registry@google.com
// to reserve extension numbers. Simply provide your project name (e.g.
// Objective-C plugin) and your project website (if available) -- there's no
// need to explain how you intend to use them. Usually you only need one
// extension number. You can declare multiple options with only one extension
// number by putting them in a sub-message. See the Custom Options section of
// the docs for examples:
// https://developers.google.com/protocol-buffers/docs/proto#options
// If this turns out to be popular, a web service will be set up
// to automatically assign option numbers.
message FileOptions {
// Sets the Java package where classes generated from this .proto will be
// placed. By default, the proto package is used, but this is often
// inappropriate because proto packages do not normally start with backwards
// domain names.
optional string java_package = 1;
// If set, all the classes from the .proto file are wrapped in a single
// outer class with the given name. This applies to both Proto1
// (equivalent to the old "--one_java_file" option) and Proto2 (where
// a .proto always translates to a single class, but you may want to
// explicitly choose the class name).
optional string java_outer_classname = 8;
// If set true, then the Java code generator will generate a separate .java
// file for each top-level message, enum, and service defined in the .proto
// file. Thus, these types will *not* be nested inside the outer class
// named by java_outer_classname. However, the outer class will still be
// generated to contain the file's getDescriptor() method as well as any
// top-level extensions defined in the file.
optional bool java_multiple_files = 10 [default=false];
// This option does nothing.
optional bool java_generate_equals_and_hash = 20 [deprecated=true];
// If set true, then the Java2 code generator will generate code that
// throws an exception whenever an attempt is made to assign a non-UTF-8
// byte sequence to a string field.
// Message reflection will do the same.
// However, an extension field still accepts non-UTF-8 byte sequences.
// This option has no effect on when used with the lite runtime.
optional bool java_string_check_utf8 = 27 [default=false];
// Generated classes can be optimized for speed or code size.
enum OptimizeMode {
SPEED = 1; // Generate complete code for parsing, serialization,
// etc.
CODE_SIZE = 2; // Use ReflectionOps to implement these methods.
LITE_RUNTIME = 3; // Generate code using MessageLite and the lite runtime.
}
optional OptimizeMode optimize_for = 9 [default=SPEED];
// Sets the Go package where structs generated from this .proto will be
// placed. If omitted, the Go package will be derived from the following:
// - The basename of the package import path, if provided.
// - Otherwise, the package statement in the .proto file, if present.
// - Otherwise, the basename of the .proto file, without extension.
optional string go_package = 11;
// Should generic services be generated in each language? "Generic" services
// are not specific to any particular RPC system. They are generated by the
// main code generators in each language (without additional plugins).
// Generic services were the only kind of service generation supported by
// early versions of google.protobuf.
//
// Generic services are now considered deprecated in favor of using plugins
// that generate code specific to your particular RPC system. Therefore,
// these default to false. Old code which depends on generic services should
// explicitly set them to true.
optional bool cc_generic_services = 16 [default=false];
optional bool java_generic_services = 17 [default=false];
optional bool py_generic_services = 18 [default=false];
optional bool php_generic_services = 42 [default=false];
// Is this file deprecated?
// Depending on the target platform, this can emit Deprecated annotations
// for everything in the file, or it will be completely ignored; in the very
// least, this is a formalization for deprecating files.
optional bool deprecated = 23 [default=false];
// Enables the use of arenas for the proto messages in this file. This applies
// only to generated classes for C++.
optional bool cc_enable_arenas = 31 [default=false];
// Sets the objective c class prefix which is prepended to all objective c
// generated classes from this .proto. There is no default.
optional string objc_class_prefix = 36;
// Namespace for generated classes; defaults to the package.
optional string csharp_namespace = 37;
// By default Swift generators will take the proto package and CamelCase it
// replacing '.' with underscore and use that to prefix the types/symbols
// defined. When this options is provided, they will use this value instead
// to prefix the types/symbols defined.
optional string swift_prefix = 39;
// Sets the php class prefix which is prepended to all php generated classes
// from this .proto. Default is empty.
optional string php_class_prefix = 40;
// Use this option to change the namespace of php generated classes. Default
// is empty. When this option is empty, the package name will be used for
// determining the namespace.
optional string php_namespace = 41;
// The parser stores options it doesn't recognize here.
// See the documentation for the "Options" section above.
repeated UninterpretedOption uninterpreted_option = 999;
// Clients can define custom options in extensions of this message.
// See the documentation for the "Options" section above.
extensions 1000 to max;
reserved 38;
}
message MessageOptions {
// Set true to use the old proto1 MessageSet wire format for extensions.
// This is provided for backwards-compatibility with the MessageSet wire
// format. You should not use this for any other reason: It's less
// efficient, has fewer features, and is more complicated.
//
// The message must be defined exactly as follows:
// message Foo {
// option message_set_wire_format = true;
// extensions 4 to max;
// }
// Note that the message cannot have any defined fields; MessageSets only
// have extensions.
//
// All extensions of your type must be singular messages; e.g. they cannot
// be int32s, enums, or repeated messages.
//
// Because this is an option, the above two restrictions are not enforced by
// the protocol compiler.
optional bool message_set_wire_format = 1 [default=false];
// Disables the generation of the standard "descriptor()" accessor, which can
// conflict with a field of the same name. This is meant to make migration
// from proto1 easier; new code should avoid fields named "descriptor".
optional bool no_standard_descriptor_accessor = 2 [default=false];
// Is this message deprecated?
// Depending on the target platform, this can emit Deprecated annotations
// for the message, or it will be completely ignored; in the very least,
// this is a formalization for deprecating messages.
optional bool deprecated = 3 [default=false];
// Whether the message is an automatically generated map entry type for the
// maps field.
//
// For maps fields:
// map<KeyType, ValueType> map_field = 1;
// The parsed descriptor looks like:
// message MapFieldEntry {
// option map_entry = true;
// optional KeyType key = 1;
// optional ValueType value = 2;
// }
// repeated MapFieldEntry map_field = 1;
//
// Implementations may choose not to generate the map_entry=true message, but
// use a native map in the target language to hold the keys and values.
// The reflection APIs in such implementions still need to work as
// if the field is a repeated message field.
//
// NOTE: Do not set the option in .proto files. Always use the maps syntax
// instead. The option should only be implicitly set by the proto compiler
// parser.
optional bool map_entry = 7;
reserved 8; // javalite_serializable
reserved 9; // javanano_as_lite
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
// Clients can define custom options in extensions of this message. See above.
extensions 1000 to max;
}
message FieldOptions {
// The ctype option instructs the C++ code generator to use a different
// representation of the field than it normally would. See the specific
// options below. This option is not yet implemented in the open source
// release -- sorry, we'll try to include it in a future version!
optional CType ctype = 1 [default = STRING];
enum CType {
// Default mode.
STRING = 0;
CORD = 1;
STRING_PIECE = 2;
}
// The packed option can be enabled for repeated primitive fields to enable
// a more efficient representation on the wire. Rather than repeatedly
// writing the tag and type for each element, the entire array is encoded as
// a single length-delimited blob. In proto3, only explicit setting it to
// false will avoid using packed encoding.
optional bool packed = 2;
// The jstype option determines the JavaScript type used for values of the
// field. The option is permitted only for 64 bit integral and fixed types
// (int64, uint64, sint64, fixed64, sfixed64). A field with jstype JS_STRING
// is represented as JavaScript string, which avoids loss of precision that
// can happen when a large value is converted to a floating point JavaScript.
// Specifying JS_NUMBER for the jstype causes the generated JavaScript code to
// use the JavaScript "number" type. The behavior of the default option
// JS_NORMAL is implementation dependent.
//
// This option is an enum to permit additional types to be added, e.g.
// goog.math.Integer.
optional JSType jstype = 6 [default = JS_NORMAL];
enum JSType {
// Use the default type.
JS_NORMAL = 0;
// Use JavaScript strings.
JS_STRING = 1;
// Use JavaScript numbers.
JS_NUMBER = 2;
}
// Should this field be parsed lazily? Lazy applies only to message-type
// fields. It means that when the outer message is initially parsed, the
// inner message's contents will not be parsed but instead stored in encoded
// form. The inner message will actually be parsed when it is first accessed.
//
// This is only a hint. Implementations are free to choose whether to use
// eager or lazy parsing regardless of the value of this option. However,
// setting this option true suggests that the protocol author believes that
// using lazy parsing on this field is worth the additional bookkeeping
// overhead typically needed to implement it.
//
// This option does not affect the public interface of any generated code;
// all method signatures remain the same. Furthermore, thread-safety of the
// interface is not affected by this option; const methods remain safe to
// call from multiple threads concurrently, while non-const methods continue
// to require exclusive access.
//
//
// Note that implementations may choose not to check required fields within
// a lazy sub-message. That is, calling IsInitialized() on the outer message
// may return true even if the inner message has missing required fields.
// This is necessary because otherwise the inner message would have to be
// parsed in order to perform the check, defeating the purpose of lazy
// parsing. An implementation which chooses not to check required fields
// must be consistent about it. That is, for any particular sub-message, the
// implementation must either *always* check its required fields, or *never*
// check its required fields, regardless of whether or not the message has
// been parsed.
optional bool lazy = 5 [default=false];
// Is this field deprecated?
// Depending on the target platform, this can emit Deprecated annotations
// for accessors, or it will be completely ignored; in the very least, this
// is a formalization for deprecating fields.
optional bool deprecated = 3 [default=false];
// For Google-internal migration only. Do not use.
optional bool weak = 10 [default=false];
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
// Clients can define custom options in extensions of this message. See above.
extensions 1000 to max;
reserved 4; // removed jtype
}
message OneofOptions {
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
// Clients can define custom options in extensions of this message. See above.
extensions 1000 to max;
}
message EnumOptions {
// Set this option to true to allow mapping different tag names to the same
// value.
optional bool allow_alias = 2;
// Is this enum deprecated?
// Depending on the target platform, this can emit Deprecated annotations
// for the enum, or it will be completely ignored; in the very least, this
// is a formalization for deprecating enums.
optional bool deprecated = 3 [default=false];
reserved 5; // javanano_as_lite
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
// Clients can define custom options in extensions of this message. See above.
extensions 1000 to max;
}
message EnumValueOptions {
// Is this enum value deprecated?
// Depending on the target platform, this can emit Deprecated annotations
// for the enum value, or it will be completely ignored; in the very least,
// this is a formalization for deprecating enum values.
optional bool deprecated = 1 [default=false];
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
// Clients can define custom options in extensions of this message. See above.
extensions 1000 to max;
}
message ServiceOptions {
// Note: Field numbers 1 through 32 are reserved for Google's internal RPC
// framework. We apologize for hoarding these numbers to ourselves, but
// we were already using them long before we decided to release Protocol
// Buffers.
// Is this service deprecated?
// Depending on the target platform, this can emit Deprecated annotations
// for the service, or it will be completely ignored; in the very least,
// this is a formalization for deprecating services.
optional bool deprecated = 33 [default=false];
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
// Clients can define custom options in extensions of this message. See above.
extensions 1000 to max;
}
message MethodOptions {
// Note: Field numbers 1 through 32 are reserved for Google's internal RPC
// framework. We apologize for hoarding these numbers to ourselves, but
// we were already using them long before we decided to release Protocol
// Buffers.
// Is this method deprecated?
// Depending on the target platform, this can emit Deprecated annotations
// for the method, or it will be completely ignored; in the very least,
// this is a formalization for deprecating methods.
optional bool deprecated = 33 [default=false];
// Is this method side-effect-free (or safe in HTTP parlance), or idempotent,
// or neither? HTTP based RPC implementation may choose GET verb for safe
// methods, and PUT verb for idempotent methods instead of the default POST.
enum IdempotencyLevel {
IDEMPOTENCY_UNKNOWN = 0;
NO_SIDE_EFFECTS = 1; // implies idempotent
IDEMPOTENT = 2; // idempotent, but may have side effects
}
optional IdempotencyLevel idempotency_level =
34 [default=IDEMPOTENCY_UNKNOWN];
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
// Clients can define custom options in extensions of this message. See above.
extensions 1000 to max;
}
// A message representing a option the parser does not recognize. This only
// appears in options protos created by the compiler::Parser class.
// DescriptorPool resolves these when building Descriptor objects. Therefore,
// options protos in descriptor objects (e.g. returned by Descriptor::options(),
// or produced by Descriptor::CopyTo()) will never have UninterpretedOptions
// in them.
message UninterpretedOption {
// The name of the uninterpreted option. Each string represents a segment in
// a dot-separated name. is_extension is true iff a segment represents an
// extension (denoted with parentheses in options specs in .proto files).
// E.g.,{ ["foo", false], ["bar.baz", true], ["qux", false] } represents
// "foo.(bar.baz).qux".
message NamePart {
required string name_part = 1;
required bool is_extension = 2;
}
repeated NamePart name = 2;
// The value of the uninterpreted option, in whatever type the tokenizer
// identified it as during parsing. Exactly one of these should be set.
optional string identifier_value = 3;
optional uint64 positive_int_value = 4;
optional int64 negative_int_value = 5;
optional double double_value = 6;
optional bytes string_value = 7;
optional string aggregate_value = 8;
}
// ===================================================================
// Optional source code info
// Encapsulates information about the original source file from which a
// FileDescriptorProto was generated.
message SourceCodeInfo {
// A Location identifies a piece of source code in a .proto file which
// corresponds to a particular definition. This information is intended
// to be useful to IDEs, code indexers, documentation generators, and similar
// tools.
//
// For example, say we have a file like:
// message Foo {
// optional string foo = 1;
// }
// Let's look at just the field definition:
// optional string foo = 1;
// ^ ^^ ^^ ^ ^^^
// a bc de f ghi
// We have the following locations:
// span path represents
// [a,i) [ 4, 0, 2, 0 ] The whole field definition.
// [a,b) [ 4, 0, 2, 0, 4 ] The label (optional).
// [c,d) [ 4, 0, 2, 0, 5 ] The type (string).
// [e,f) [ 4, 0, 2, 0, 1 ] The name (foo).
// [g,h) [ 4, 0, 2, 0, 3 ] The number (1).
//
// Notes:
// - A location may refer to a repeated field itself (i.e. not to any
// particular index within it). This is used whenever a set of elements are
// logically enclosed in a single code segment. For example, an entire
// extend block (possibly containing multiple extension definitions) will
// have an outer location whose path refers to the "extensions" repeated
// field without an index.
// - Multiple locations may have the same path. This happens when a single
// logical declaration is spread out across multiple places. The most
// obvious example is the "extend" block again -- there may be multiple
// extend blocks in the same scope, each of which will have the same path.
// - A location's span is not always a subset of its parent's span. For
// example, the "extendee" of an extension declaration appears at the
// beginning of the "extend" block and is shared by all extensions within
// the block.
// - Just because a location's span is a subset of some other location's span
// does not mean that it is a descendent. For example, a "group" defines
// both a type and a field in a single declaration. Thus, the locations
// corresponding to the type and field and their components will overlap.
// - Code which tries to interpret locations should probably be designed to
// ignore those that it doesn't understand, as more types of locations could
// be recorded in the future.
repeated Location location = 1;
message Location {
// Identifies which part of the FileDescriptorProto was defined at this
// location.
//
// Each element is a field number or an index. They form a path from
// the root FileDescriptorProto to the place where the definition. For
// example, this path:
// [ 4, 3, 2, 7, 1 ]
// refers to:
// file.message_type(3) // 4, 3
// .field(7) // 2, 7
// .name() // 1
// This is because FileDescriptorProto.message_type has field number 4:
// repeated DescriptorProto message_type = 4;
// and DescriptorProto.field has field number 2:
// repeated FieldDescriptorProto field = 2;
// and FieldDescriptorProto.name has field number 1:
// optional string name = 1;
//
// Thus, the above path gives the location of a field name. If we removed
// the last element:
// [ 4, 3, 2, 7 ]
// this path refers to the whole field declaration (from the beginning
// of the label to the terminating semicolon).
repeated int32 path = 1 [packed=true];
// Always has exactly three or four elements: start line, start column,
// end line (optional, otherwise assumed same as start line), end column.
// These are packed into a single field for efficiency. Note that line
// and column numbers are zero-based -- typically you will want to add
// 1 to each before displaying to a user.
repeated int32 span = 2 [packed=true];
// If this SourceCodeInfo represents a complete declaration, these are any
// comments appearing before and after the declaration which appear to be
// attached to the declaration.
//
// A series of line comments appearing on consecutive lines, with no other
// tokens appearing on those lines, will be treated as a single comment.
//
// leading_detached_comments will keep paragraphs of comments that appear
// before (but not connected to) the current element. Each paragraph,
// separated by empty lines, will be one comment element in the repeated
// field.
//
// Only the comment content is provided; comment markers (e.g. //) are
// stripped out. For block comments, leading whitespace and an asterisk
// will be stripped from the beginning of each line other than the first.
// Newlines are included in the output.
//
// Examples:
//
// optional int32 foo = 1; // Comment attached to foo.
// // Comment attached to bar.
// optional int32 bar = 2;
//
// optional string baz = 3;
// // Comment attached to baz.
// // Another line attached to baz.
//
// // Comment attached to qux.
// //
// // Another line attached to qux.
// optional double qux = 4;
//
// // Detached comment for corge. This is not leading or trailing comments
// // to qux or corge because there are blank lines separating it from
// // both.
//
// // Detached comment for corge paragraph 2.
//
// optional string corge = 5;
// /* Block comment attached
// * to corge. Leading asterisks
// * will be removed. */
// /* Block comment attached to
// * grault. */
// optional int32 grault = 6;
//
// // ignored detached comments.
optional string leading_comments = 3;
optional string trailing_comments = 4;
repeated string leading_detached_comments = 6;
}
}
// Describes the relationship between generated code and its original source
// file. A GeneratedCodeInfo message is associated with only one generated
// source file, but may contain references to different source .proto files.
message GeneratedCodeInfo {
// An Annotation connects some span of text in generated code to an element
// of its generating .proto file.
repeated Annotation annotation = 1;
message Annotation {
// Identifies the element in the original source .proto file. This field
// is formatted the same as SourceCodeInfo.Location.path.
repeated int32 path = 1 [packed=true];
// Identifies the filesystem path to the original source .proto.
optional string source_file = 2;
// Identifies the starting offset in bytes in the generated code
// that relates to the identified object.
optional int32 begin = 3;
// Identifies the ending offset in bytes in the generated code that
// relates to the identified offset. The end offset should be one past
// the last relevant byte (so the length of the text = end - begin).
optional int32 end = 4;
}
}

View File

@ -0,0 +1,117 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
syntax = "proto3";
package google.protobuf;
option csharp_namespace = "Google.Protobuf.WellKnownTypes";
option cc_enable_arenas = true;
option go_package = "github.com/golang/protobuf/ptypes/duration";
option java_package = "com.google.protobuf";
option java_outer_classname = "DurationProto";
option java_multiple_files = true;
option objc_class_prefix = "GPB";
// A Duration represents a signed, fixed-length span of time represented
// as a count of seconds and fractions of seconds at nanosecond
// resolution. It is independent of any calendar and concepts like "day"
// or "month". It is related to Timestamp in that the difference between
// two Timestamp values is a Duration and it can be added or subtracted
// from a Timestamp. Range is approximately +-10,000 years.
//
// # Examples
//
// Example 1: Compute Duration from two Timestamps in pseudo code.
//
// Timestamp start = ...;
// Timestamp end = ...;
// Duration duration = ...;
//
// duration.seconds = end.seconds - start.seconds;
// duration.nanos = end.nanos - start.nanos;
//
// if (duration.seconds < 0 && duration.nanos > 0) {
// duration.seconds += 1;
// duration.nanos -= 1000000000;
// } else if (durations.seconds > 0 && duration.nanos < 0) {
// duration.seconds -= 1;
// duration.nanos += 1000000000;
// }
//
// Example 2: Compute Timestamp from Timestamp + Duration in pseudo code.
//
// Timestamp start = ...;
// Duration duration = ...;
// Timestamp end = ...;
//
// end.seconds = start.seconds + duration.seconds;
// end.nanos = start.nanos + duration.nanos;
//
// if (end.nanos < 0) {
// end.seconds -= 1;
// end.nanos += 1000000000;
// } else if (end.nanos >= 1000000000) {
// end.seconds += 1;
// end.nanos -= 1000000000;
// }
//
// Example 3: Compute Duration from datetime.timedelta in Python.
//
// td = datetime.timedelta(days=3, minutes=10)
// duration = Duration()
// duration.FromTimedelta(td)
//
// # JSON Mapping
//
// In JSON format, the Duration type is encoded as a string rather than an
// object, where the string ends in the suffix "s" (indicating seconds) and
// is preceded by the number of seconds, with nanoseconds expressed as
// fractional seconds. For example, 3 seconds with 0 nanoseconds should be
// encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should
// be expressed in JSON format as "3.000000001s", and 3 seconds and 1
// microsecond should be expressed in JSON format as "3.000001s".
//
//
message Duration {
// Signed seconds of the span of time. Must be from -315,576,000,000
// to +315,576,000,000 inclusive. Note: these bounds are computed from:
// 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years
int64 seconds = 1;
// Signed fractions of a second at nanosecond resolution of the span
// of time. Durations less than one second are represented with a 0
// `seconds` field and a positive or negative `nanos` field. For durations
// of one second or more, a non-zero value for the `nanos` field must be
// of the same sign as the `seconds` field. Must be from -999,999,999
// to +999,999,999 inclusive.
int32 nanos = 2;
}

View File

@ -0,0 +1,52 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
syntax = "proto3";
package google.protobuf;
option csharp_namespace = "Google.Protobuf.WellKnownTypes";
option go_package = "github.com/golang/protobuf/ptypes/empty";
option java_package = "com.google.protobuf";
option java_outer_classname = "EmptyProto";
option java_multiple_files = true;
option objc_class_prefix = "GPB";
option cc_enable_arenas = true;
// A generic empty message that you can re-use to avoid defining duplicated
// empty messages in your APIs. A typical example is to use it as the request
// or the response type of an API method. For instance:
//
// service Foo {
// rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty);
// }
//
// The JSON representation for `Empty` is empty JSON object `{}`.
message Empty {}

View File

@ -0,0 +1,252 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
syntax = "proto3";
package google.protobuf;
option csharp_namespace = "Google.Protobuf.WellKnownTypes";
option java_package = "com.google.protobuf";
option java_outer_classname = "FieldMaskProto";
option java_multiple_files = true;
option objc_class_prefix = "GPB";
option go_package = "google.golang.org/genproto/protobuf/field_mask;field_mask";
// `FieldMask` represents a set of symbolic field paths, for example:
//
// paths: "f.a"
// paths: "f.b.d"
//
// Here `f` represents a field in some root message, `a` and `b`
// fields in the message found in `f`, and `d` a field found in the
// message in `f.b`.
//
// Field masks are used to specify a subset of fields that should be
// returned by a get operation or modified by an update operation.
// Field masks also have a custom JSON encoding (see below).
//
// # Field Masks in Projections
//
// When used in the context of a projection, a response message or
// sub-message is filtered by the API to only contain those fields as
// specified in the mask. For example, if the mask in the previous
// example is applied to a response message as follows:
//
// f {
// a : 22
// b {
// d : 1
// x : 2
// }
// y : 13
// }
// z: 8
//
// The result will not contain specific values for fields x,y and z
// (their value will be set to the default, and omitted in proto text
// output):
//
//
// f {
// a : 22
// b {
// d : 1
// }
// }
//
// A repeated field is not allowed except at the last position of a
// paths string.
//
// If a FieldMask object is not present in a get operation, the
// operation applies to all fields (as if a FieldMask of all fields
// had been specified).
//
// Note that a field mask does not necessarily apply to the
// top-level response message. In case of a REST get operation, the
// field mask applies directly to the response, but in case of a REST
// list operation, the mask instead applies to each individual message
// in the returned resource list. In case of a REST custom method,
// other definitions may be used. Where the mask applies will be
// clearly documented together with its declaration in the API. In
// any case, the effect on the returned resource/resources is required
// behavior for APIs.
//
// # Field Masks in Update Operations
//
// A field mask in update operations specifies which fields of the
// targeted resource are going to be updated. The API is required
// to only change the values of the fields as specified in the mask
// and leave the others untouched. If a resource is passed in to
// describe the updated values, the API ignores the values of all
// fields not covered by the mask.
//
// If a repeated field is specified for an update operation, the existing
// repeated values in the target resource will be overwritten by the new values.
// Note that a repeated field is only allowed in the last position of a `paths`
// string.
//
// If a sub-message is specified in the last position of the field mask for an
// update operation, then the existing sub-message in the target resource is
// overwritten. Given the target message:
//
// f {
// b {
// d : 1
// x : 2
// }
// c : 1
// }
//
// And an update message:
//
// f {
// b {
// d : 10
// }
// }
//
// then if the field mask is:
//
// paths: "f.b"
//
// then the result will be:
//
// f {
// b {
// d : 10
// }
// c : 1
// }
//
// However, if the update mask was:
//
// paths: "f.b.d"
//
// then the result would be:
//
// f {
// b {
// d : 10
// x : 2
// }
// c : 1
// }
//
// In order to reset a field's value to the default, the field must
// be in the mask and set to the default value in the provided resource.
// Hence, in order to reset all fields of a resource, provide a default
// instance of the resource and set all fields in the mask, or do
// not provide a mask as described below.
//
// If a field mask is not present on update, the operation applies to
// all fields (as if a field mask of all fields has been specified).
// Note that in the presence of schema evolution, this may mean that
// fields the client does not know and has therefore not filled into
// the request will be reset to their default. If this is unwanted
// behavior, a specific service may require a client to always specify
// a field mask, producing an error if not.
//
// As with get operations, the location of the resource which
// describes the updated values in the request message depends on the
// operation kind. In any case, the effect of the field mask is
// required to be honored by the API.
//
// ## Considerations for HTTP REST
//
// The HTTP kind of an update operation which uses a field mask must
// be set to PATCH instead of PUT in order to satisfy HTTP semantics
// (PUT must only be used for full updates).
//
// # JSON Encoding of Field Masks
//
// In JSON, a field mask is encoded as a single string where paths are
// separated by a comma. Fields name in each path are converted
// to/from lower-camel naming conventions.
//
// As an example, consider the following message declarations:
//
// message Profile {
// User user = 1;
// Photo photo = 2;
// }
// message User {
// string display_name = 1;
// string address = 2;
// }
//
// In proto a field mask for `Profile` may look as such:
//
// mask {
// paths: "user.display_name"
// paths: "photo"
// }
//
// In JSON, the same mask is represented as below:
//
// {
// mask: "user.displayName,photo"
// }
//
// # Field Masks and Oneof Fields
//
// Field masks treat fields in oneofs just as regular fields. Consider the
// following message:
//
// message SampleMessage {
// oneof test_oneof {
// string name = 4;
// SubMessage sub_message = 9;
// }
// }
//
// The field mask can be:
//
// mask {
// paths: "name"
// }
//
// Or:
//
// mask {
// paths: "sub_message"
// }
//
// Note that oneof type names ("test_oneof" in this case) cannot be used in
// paths.
//
// ## Field Mask Verification
//
// The implementation of the all the API methods, which have any FieldMask type
// field in the request, should verify the included field paths, and return
// `INVALID_ARGUMENT` error if any path is duplicated or unmappable.
message FieldMask {
// The set of field mask paths.
repeated string paths = 1;
}

View File

@ -0,0 +1,48 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
syntax = "proto3";
package google.protobuf;
option csharp_namespace = "Google.Protobuf.WellKnownTypes";
option java_package = "com.google.protobuf";
option java_outer_classname = "SourceContextProto";
option java_multiple_files = true;
option objc_class_prefix = "GPB";
option go_package = "google.golang.org/genproto/protobuf/source_context;source_context";
// `SourceContext` represents information about the source of a
// protobuf element, like the file in which it is defined.
message SourceContext {
// The path-qualified name of the .proto file that contained the associated
// protobuf element. For example: `"google/protobuf/source_context.proto"`.
string file_name = 1;
}

View File

@ -0,0 +1,96 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
syntax = "proto3";
package google.protobuf;
option csharp_namespace = "Google.Protobuf.WellKnownTypes";
option cc_enable_arenas = true;
option go_package = "github.com/golang/protobuf/ptypes/struct;structpb";
option java_package = "com.google.protobuf";
option java_outer_classname = "StructProto";
option java_multiple_files = true;
option objc_class_prefix = "GPB";
// `Struct` represents a structured data value, consisting of fields
// which map to dynamically typed values. In some languages, `Struct`
// might be supported by a native representation. For example, in
// scripting languages like JS a struct is represented as an
// object. The details of that representation are described together
// with the proto support for the language.
//
// The JSON representation for `Struct` is JSON object.
message Struct {
// Unordered map of dynamically typed values.
map<string, Value> fields = 1;
}
// `Value` represents a dynamically typed value which can be either
// null, a number, a string, a boolean, a recursive struct value, or a
// list of values. A producer of value is expected to set one of that
// variants, absence of any variant indicates an error.
//
// The JSON representation for `Value` is JSON value.
message Value {
// The kind of value.
oneof kind {
// Represents a null value.
NullValue null_value = 1;
// Represents a double value.
double number_value = 2;
// Represents a string value.
string string_value = 3;
// Represents a boolean value.
bool bool_value = 4;
// Represents a structured value.
Struct struct_value = 5;
// Represents a repeated `Value`.
ListValue list_value = 6;
}
}
// `NullValue` is a singleton enumeration to represent the null value for the
// `Value` type union.
//
// The JSON representation for `NullValue` is JSON `null`.
enum NullValue {
// Null value.
NULL_VALUE = 0;
}
// `ListValue` is a wrapper around a repeated field of values.
//
// The JSON representation for `ListValue` is JSON array.
message ListValue {
// Repeated field of dynamically typed values.
repeated Value values = 1;
}

View File

@ -0,0 +1,133 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
syntax = "proto3";
package google.protobuf;
option csharp_namespace = "Google.Protobuf.WellKnownTypes";
option cc_enable_arenas = true;
option go_package = "github.com/golang/protobuf/ptypes/timestamp";
option java_package = "com.google.protobuf";
option java_outer_classname = "TimestampProto";
option java_multiple_files = true;
option objc_class_prefix = "GPB";
// A Timestamp represents a point in time independent of any time zone
// or calendar, represented as seconds and fractions of seconds at
// nanosecond resolution in UTC Epoch time. It is encoded using the
// Proleptic Gregorian Calendar which extends the Gregorian calendar
// backwards to year one. It is encoded assuming all minutes are 60
// seconds long, i.e. leap seconds are "smeared" so that no leap second
// table is needed for interpretation. Range is from
// 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z.
// By restricting to that range, we ensure that we can convert to
// and from RFC 3339 date strings.
// See [https://www.ietf.org/rfc/rfc3339.txt](https://www.ietf.org/rfc/rfc3339.txt).
//
// # Examples
//
// Example 1: Compute Timestamp from POSIX `time()`.
//
// Timestamp timestamp;
// timestamp.set_seconds(time(NULL));
// timestamp.set_nanos(0);
//
// Example 2: Compute Timestamp from POSIX `gettimeofday()`.
//
// struct timeval tv;
// gettimeofday(&tv, NULL);
//
// Timestamp timestamp;
// timestamp.set_seconds(tv.tv_sec);
// timestamp.set_nanos(tv.tv_usec * 1000);
//
// Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`.
//
// FILETIME ft;
// GetSystemTimeAsFileTime(&ft);
// UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
//
// // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z
// // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z.
// Timestamp timestamp;
// timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL));
// timestamp.set_nanos((INT32) ((ticks % 10000000) * 100));
//
// Example 4: Compute Timestamp from Java `System.currentTimeMillis()`.
//
// long millis = System.currentTimeMillis();
//
// Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000)
// .setNanos((int) ((millis % 1000) * 1000000)).build();
//
//
// Example 5: Compute Timestamp from current time in Python.
//
// timestamp = Timestamp()
// timestamp.GetCurrentTime()
//
// # JSON Mapping
//
// In JSON format, the Timestamp type is encoded as a string in the
// [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the
// format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z"
// where {year} is always expressed using four digits while {month}, {day},
// {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional
// seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution),
// are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone
// is required, though only UTC (as indicated by "Z") is presently supported.
//
// For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past
// 01:30 UTC on January 15, 2017.
//
// In JavaScript, one can convert a Date object to this format using the
// standard [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString]
// method. In Python, a standard `datetime.datetime` object can be converted
// to this format using [`strftime`](https://docs.python.org/2/library/time.html#time.strftime)
// with the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one
// can use the Joda Time's [`ISODateTimeFormat.dateTime()`](
// http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime--)
// to obtain a formatter capable of generating timestamps in this format.
//
//
message Timestamp {
// Represents seconds of UTC time since Unix epoch
// 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
// 9999-12-31T23:59:59Z inclusive.
int64 seconds = 1;
// Non-negative fractions of a second at nanosecond resolution. Negative
// second values with fractions must still have non-negative nanos values
// that count forward in time. Must be from 0 to 999,999,999
// inclusive.
int32 nanos = 2;
}

View File

@ -0,0 +1,187 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
syntax = "proto3";
package google.protobuf;
import "google/protobuf/any.proto";
import "google/protobuf/source_context.proto";
option csharp_namespace = "Google.Protobuf.WellKnownTypes";
option cc_enable_arenas = true;
option java_package = "com.google.protobuf";
option java_outer_classname = "TypeProto";
option java_multiple_files = true;
option objc_class_prefix = "GPB";
option go_package = "google.golang.org/genproto/protobuf/ptype;ptype";
// A protocol buffer message type.
message Type {
// The fully qualified message name.
string name = 1;
// The list of fields.
repeated Field fields = 2;
// The list of types appearing in `oneof` definitions in this type.
repeated string oneofs = 3;
// The protocol buffer options.
repeated Option options = 4;
// The source context.
SourceContext source_context = 5;
// The source syntax.
Syntax syntax = 6;
}
// A single field of a message type.
message Field {
// Basic field types.
enum Kind {
// Field type unknown.
TYPE_UNKNOWN = 0;
// Field type double.
TYPE_DOUBLE = 1;
// Field type float.
TYPE_FLOAT = 2;
// Field type int64.
TYPE_INT64 = 3;
// Field type uint64.
TYPE_UINT64 = 4;
// Field type int32.
TYPE_INT32 = 5;
// Field type fixed64.
TYPE_FIXED64 = 6;
// Field type fixed32.
TYPE_FIXED32 = 7;
// Field type bool.
TYPE_BOOL = 8;
// Field type string.
TYPE_STRING = 9;
// Field type group. Proto2 syntax only, and deprecated.
TYPE_GROUP = 10;
// Field type message.
TYPE_MESSAGE = 11;
// Field type bytes.
TYPE_BYTES = 12;
// Field type uint32.
TYPE_UINT32 = 13;
// Field type enum.
TYPE_ENUM = 14;
// Field type sfixed32.
TYPE_SFIXED32 = 15;
// Field type sfixed64.
TYPE_SFIXED64 = 16;
// Field type sint32.
TYPE_SINT32 = 17;
// Field type sint64.
TYPE_SINT64 = 18;
};
// Whether a field is optional, required, or repeated.
enum Cardinality {
// For fields with unknown cardinality.
CARDINALITY_UNKNOWN = 0;
// For optional fields.
CARDINALITY_OPTIONAL = 1;
// For required fields. Proto2 syntax only.
CARDINALITY_REQUIRED = 2;
// For repeated fields.
CARDINALITY_REPEATED = 3;
};
// The field type.
Kind kind = 1;
// The field cardinality.
Cardinality cardinality = 2;
// The field number.
int32 number = 3;
// The field name.
string name = 4;
// The field type URL, without the scheme, for message or enumeration
// types. Example: `"type.googleapis.com/google.protobuf.Timestamp"`.
string type_url = 6;
// The index of the field type in `Type.oneofs`, for message or enumeration
// types. The first type has index 1; zero means the type is not in the list.
int32 oneof_index = 7;
// Whether to use alternative packed wire representation.
bool packed = 8;
// The protocol buffer options.
repeated Option options = 9;
// The field JSON name.
string json_name = 10;
// The string value of the default value of this field. Proto2 syntax only.
string default_value = 11;
}
// Enum type definition.
message Enum {
// Enum type name.
string name = 1;
// Enum value definitions.
repeated EnumValue enumvalue = 2;
// Protocol buffer options.
repeated Option options = 3;
// The source context.
SourceContext source_context = 4;
// The source syntax.
Syntax syntax = 5;
}
// Enum value definition.
message EnumValue {
// Enum value name.
string name = 1;
// Enum value number.
int32 number = 2;
// Protocol buffer options.
repeated Option options = 3;
}
// A protocol buffer option, which can be attached to a message, field,
// enumeration, etc.
message Option {
// The option's name. For protobuf built-in options (options defined in
// descriptor.proto), this is the short name. For example, `"map_entry"`.
// For custom options, it should be the fully-qualified name. For example,
// `"google.api.http"`.
string name = 1;
// The option's value packed in an Any message. If the value is a primitive,
// the corresponding wrapper type defined in google/protobuf/wrappers.proto
// should be used. If the value is an enum, it should be stored as an int32
// value using the google.protobuf.Int32Value type.
Any value = 2;
}
// The syntax in which a protocol buffer element is defined.
enum Syntax {
// Syntax `proto2`.
SYNTAX_PROTO2 = 0;
// Syntax `proto3`.
SYNTAX_PROTO3 = 1;
}

View File

@ -0,0 +1,118 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Wrappers for primitive (non-message) types. These types are useful
// for embedding primitives in the `google.protobuf.Any` type and for places
// where we need to distinguish between the absence of a primitive
// typed field and its default value.
syntax = "proto3";
package google.protobuf;
option csharp_namespace = "Google.Protobuf.WellKnownTypes";
option cc_enable_arenas = true;
option go_package = "github.com/golang/protobuf/ptypes/wrappers";
option java_package = "com.google.protobuf";
option java_outer_classname = "WrappersProto";
option java_multiple_files = true;
option objc_class_prefix = "GPB";
// Wrapper message for `double`.
//
// The JSON representation for `DoubleValue` is JSON number.
message DoubleValue {
// The double value.
double value = 1;
}
// Wrapper message for `float`.
//
// The JSON representation for `FloatValue` is JSON number.
message FloatValue {
// The float value.
float value = 1;
}
// Wrapper message for `int64`.
//
// The JSON representation for `Int64Value` is JSON string.
message Int64Value {
// The int64 value.
int64 value = 1;
}
// Wrapper message for `uint64`.
//
// The JSON representation for `UInt64Value` is JSON string.
message UInt64Value {
// The uint64 value.
uint64 value = 1;
}
// Wrapper message for `int32`.
//
// The JSON representation for `Int32Value` is JSON number.
message Int32Value {
// The int32 value.
int32 value = 1;
}
// Wrapper message for `uint32`.
//
// The JSON representation for `UInt32Value` is JSON number.
message UInt32Value {
// The uint32 value.
uint32 value = 1;
}
// Wrapper message for `bool`.
//
// The JSON representation for `BoolValue` is JSON `true` and `false`.
message BoolValue {
// The bool value.
bool value = 1;
}
// Wrapper message for `string`.
//
// The JSON representation for `StringValue` is JSON string.
message StringValue {
// The string value.
string value = 1;
}
// Wrapper message for `bytes`.
//
// The JSON representation for `BytesValue` is JSON string.
message BytesValue {
// The bytes value.
bytes value = 1;
}

View File

@ -0,0 +1,15 @@
Protocol Buffers - Google's data interchange format
Copyright 2008 Google Inc.
https://developers.google.com/protocol-buffers/
This package contains a precompiled binary version of the protocol buffer
compiler (protoc). This binary is intended for users who want to use Protocol
Buffers in languages other than C++ but do not want to compile protoc
themselves. To install, simply place this binary somewhere in your PATH.
If you intend to use the included well known types then don't forget to
copy the contents of the 'include' directory somewhere as well, for example
into '/usr/local/include/'.
Please refer to our official github site for more installation instructions:
https://github.com/google/protobuf

BIN
bin/protoc-gen-go.exe Normal file

Binary file not shown.

154
core/admin/admin.go Normal file
View File

@ -0,0 +1,154 @@
package admin
import (
"encoding/json"
"fmt"
"net"
"net/http"
"mongo.games.com/goserver/core/logger"
"mongo.games.com/goserver/core/schedule"
"mongo.games.com/goserver/core/utils"
)
// MyAdminApp is the default AdminApp used by admin module.
var MyAdminApp *AdminApp
// AdminIndex is the default http.Handler for admin module.
// it matches url pattern "/".
func AdminIndex(rw http.ResponseWriter, r *http.Request) {
rw.Write([]byte("Welcome to Admin Dashboard\n"))
rw.Write([]byte("There are servral functions:\n"))
rw.Write([]byte(fmt.Sprintf("1. Get runtime profiling data by the pprof, http://%s:%d/prof\n", Config.AdminHttpAddr, Config.AdminHttpPort)))
rw.Write([]byte(fmt.Sprintf("2. Get healthcheck result from http://%s:%d/healthcheck\n", Config.AdminHttpAddr, Config.AdminHttpPort)))
rw.Write([]byte(fmt.Sprintf("3. Get current task infomation from task http://%s:%d/task \n", Config.AdminHttpAddr, Config.AdminHttpPort)))
rw.Write([]byte(fmt.Sprintf("4. To run a task passed a param http://%s:%d/runtask\n", Config.AdminHttpAddr, Config.AdminHttpPort)))
rw.Write([]byte(fmt.Sprintf("5. Get all confige & router infomation http://%s:%d/listconf\n", Config.AdminHttpAddr, Config.AdminHttpPort)))
}
// ListConf is the http.Handler of displaying all configuration values as key/value pair.
// it's registered with url pattern "/listconf" in admin module.
func ListConf(rw http.ResponseWriter, r *http.Request) {
rw.Write([]byte("unimpletement"))
}
// ProfIndex is a http.Handler for showing profile command.
// it's in url pattern "/prof" in admin module.
func ProfIndex(rw http.ResponseWriter, r *http.Request) {
r.ParseForm()
command := r.Form.Get("command")
if command != "" {
utils.ProcessInput(command, rw)
} else {
rw.Write([]byte("request url like '/prof?command=lookup goroutine'\n"))
rw.Write([]byte("the command have below types:\n"))
rw.Write([]byte("1. lookup goroutine\n"))
rw.Write([]byte("2. lookup heap\n"))
rw.Write([]byte("3. lookup threadcreate\n"))
rw.Write([]byte("4. lookup block\n"))
rw.Write([]byte("5. start cpuprof\n"))
rw.Write([]byte("6. stop cpuprof\n"))
rw.Write([]byte("7. get memprof\n"))
rw.Write([]byte("8. gc summary\n"))
rw.Write([]byte("9. logic statistics\n"))
}
}
// Healthcheck is a http.Handler calling health checking and showing the result.
// it's in "/healthcheck" pattern in admin module.
func Healthcheck(rw http.ResponseWriter, req *http.Request) {
defer utils.DumpStackIfPanic("Admin Healthcheck")
for name, h := range utils.AdminCheckList {
if err := h.Check(); err == nil {
fmt.Fprintf(rw, "%s : ok\n", name)
} else {
fmt.Fprintf(rw, "%s : %s\n", name, err.Error())
}
}
}
// TaskStatus is a http.Handler with running task status (task name, status and the last execution).
// it's in "/task" pattern in admin module.
func TaskStatus(rw http.ResponseWriter, req *http.Request) {
tasks := schedule.GetAllTask()
for tname, tk := range tasks {
fmt.Fprintf(rw, "%s:%s:%s", tname, tk.GetStatus(), tk.GetPrev().String())
}
}
type TaskRunResult struct {
Code int
Err string
}
// RunTask is a http.Handler to run a Task from the "query string.
// the request url likes /runtask?taskname=sendmail.
func RunTask(rw http.ResponseWriter, req *http.Request) {
defer req.ParseForm()
taskname := req.Form.Get("taskname")
trr := &TaskRunResult{}
t := schedule.GetTask(taskname)
if t != nil {
err := t.Run()
if err != nil {
trr.Code = 1
trr.Err = err.Error()
} else {
trr.Code = 0
}
} else {
trr.Err = fmt.Sprintf("there's no task which named:%s", taskname)
trr.Code = 2
}
b, _ := json.Marshal(trr)
fmt.Println(string(b[:]))
rw.Write(b)
}
// AdminApp is an http.HandlerFunc map used as AdminApp.
type AdminApp struct {
routers map[string]http.HandlerFunc
}
// Route adds http.HandlerFunc to AdminApp with url pattern.
func (admin *AdminApp) Route(pattern string, f http.HandlerFunc) {
admin.routers[pattern] = f
}
// Start AdminApp http server.
// Its addr is defined in configuration file as adminhttpaddr and adminhttpport.
func (admin *AdminApp) Start(AdminHttpAddr string, AdminHttpPort int) {
for p, f := range admin.routers {
http.Handle(p, f)
}
addr := fmt.Sprintf("%s:%d", AdminHttpAddr, AdminHttpPort)
l, err := net.Listen("tcp", addr)
if err != nil {
logger.Logger.Critical("Admin Listen error: ", err)
return
}
logger.Logger.Infof("Admin Serve: %s", l.Addr())
go func() {
server := &http.Server{}
err = server.Serve(l)
if err != nil {
logger.Logger.Critical("Admin Serve: ", err)
}
}()
}
func init() {
MyAdminApp = &AdminApp{
routers: make(map[string]http.HandlerFunc),
}
//MyAdminApp.Route("/", AdminIndex)
//MyAdminApp.Route("/prof", ProfIndex)
//MyAdminApp.Route("/healthcheck", Healthcheck)
//MyAdminApp.Route("/task", TaskStatus)
//MyAdminApp.Route("/runtask", RunTask)
//MyAdminApp.Route("/listconf", ListConf)
}

33
core/admin/config.go Normal file
View File

@ -0,0 +1,33 @@
package admin
import (
"mongo.games.com/goserver/core"
)
var Config = Configuration{}
type Configuration struct {
SupportAdmin bool
AdminHttpAddr string
AdminHttpPort int
WhiteHttpAddr []string
}
func (c *Configuration) Name() string {
return "admin"
}
func (c *Configuration) Init() error {
if c.SupportAdmin {
MyAdminApp.Start(c.AdminHttpAddr, c.AdminHttpPort)
}
return nil
}
func (c *Configuration) Close() error {
return nil
}
func init() {
core.RegistePackage(&Config)
}

13
core/basic/command.go Normal file
View File

@ -0,0 +1,13 @@
package basic
// Object to process the command.
type Command interface {
Done(*Object) error
}
type CommandWrapper func(*Object) error
func (cw CommandWrapper) Done(o *Object) error {
return cw(o)
}

32
core/basic/command_own.go Normal file
View File

@ -0,0 +1,32 @@
package basic
import "mongo.games.com/goserver/core/container"
type ownCommand struct {
c *Object
}
func (oc *ownCommand) Done(o *Object) error {
defer o.ProcessSeqnum()
// If the object is already being shut down, new owned objects are
// immediately asked to terminate. Note that linger is set to zero.
if o.terminating {
o.termAcks++
SendTerm(oc.c)
return nil
}
// Store the reference to the owned object.
if o.childs == nil {
o.childs = container.NewSynchronizedMap()
}
o.childs.Set(oc.c.Id, oc.c)
return nil
}
func SendOwn(p *Object, c *Object) bool {
return p.SendCommand(&ownCommand{c: c}, true)
}

View File

@ -0,0 +1,21 @@
package basic
var termCmd = &termCommand{}
type termCommand struct {
}
func (tc *termCommand) Done(o *Object) error {
if o == nil {
return nil
}
// Double termination should never happen.
o.processTerm()
return nil
}
func SendTerm(o *Object) bool {
return o.SendCommand(termCmd, false)
}

View File

@ -0,0 +1,25 @@
package basic
var termAckCmd = &termAckCommand{}
type termAckCommand struct {
}
func (tac *termAckCommand) Done(o *Object) error {
if o == nil {
return nil
}
if o.termAcks > 0 {
o.termAcks--
// This may be a last ack we are waiting for before termination...
o.checkTermAcks()
}
return nil
}
func SendTermAck(p *Object) bool {
return p.SendCommand(termAckCmd, false)
}

View File

@ -0,0 +1,33 @@
package basic
type termReqCommand struct {
c *Object
}
func (trc *termReqCommand) Done(o *Object) error {
if o == nil {
return nil
}
// When shutting down we can ignore termination requests from owned
// objects. The termination request was already sent to the object.
if o.terminating {
return nil
}
// If I/O object is well and alive let's ask it to terminate.
if o.childs.IsExist(trc.c.Id) {
o.termAcks++
// Note that this object is the root of the (partial shutdown) thus, its
// value of linger is used, rather than the value stored by the children.
SendTerm(trc.c)
// Remove child
o.childs.Delete(trc.c.Id)
}
return nil
}
func SendTermReq(p *Object, c *Object) bool {
return p.SendCommand(&termReqCommand{c: c}, false)
}

72
core/basic/cond.go Normal file
View File

@ -0,0 +1,72 @@
package basic
import (
"sync/atomic"
"time"
)
type Cond struct {
notify chan struct{}
countor int32
}
func NewCond(waitor int) *Cond {
return &Cond{notify: make(chan struct{}, waitor)}
}
func (c *Cond) Wait() {
atomic.AddInt32(&c.countor, 1)
defer atomic.AddInt32(&c.countor, -1)
select {
case <-c.notify:
}
}
func (c *Cond) WaitForTimeout(dura time.Duration) bool {
atomic.AddInt32(&c.countor, 1)
defer atomic.AddInt32(&c.countor, -1)
select {
case <-c.notify:
case <-time.Tick(dura):
return true
}
return false
}
func (c *Cond) WaitForTick(ticker *time.Ticker) bool {
atomic.AddInt32(&c.countor, 1)
defer atomic.AddInt32(&c.countor, -1)
select {
case <-c.notify:
case <-ticker.C:
return true
}
return false
}
func (c *Cond) Signal() {
select {
case c.notify <- struct{}{}:
default:
return
}
}
func (c *Cond) Drain() {
for {
select {
case <-c.notify:
default:
return
}
}
}
func (c *Cond) Broadcast() {
for atomic.LoadInt32(&c.countor) > 0 {
c.notify <- struct{}{}
}
}

432
core/basic/object.go Normal file
View File

@ -0,0 +1,432 @@
package basic
import (
"container/list"
"sync"
"sync/atomic"
"time"
"fmt"
"mongo.games.com/goserver/core/container"
"mongo.games.com/goserver/core/logger"
"mongo.games.com/goserver/core/utils"
)
const (
DefaultQueueBacklog int = 4
)
var (
// Waitor = utils.NewWaitor()
)
// Base class for need alone goroutine objects
// that easy to start and when to exit the unified management
// Feature.
// establish a tree structure between objects
// asynchronous message queue
type Object struct {
*utils.Waitor
sync.RWMutex
// Identify
Id int
// Name
Name string
// True if termination was already initiated. If so, we can destroy
// the object if there are no more child objects or pending term acks.
terminating bool
// True if termination was already finished.
terminated bool
// Sequence number of the last command sent to this object.
sentSeqnum uint32
// Sequence number of the last command processed by this object.
processedSeqnum uint32
// Number of events we have to get before we can destroy the object.
termAcks int
// List of all objects owned by this object. We are responsible
// for deallocating them before we quit.
childs *container.SynchronizedMap
// Socket owning this object. It's responsible for shutting down
// this object.
owner *Object
// Command queue
que *list.List
// Configuration Options
opt Options
// Currently resides goroutine id. I do not know how get it.
gid int
//
waitActive chan struct{}
//
waitEnlarge chan struct{}
// UserData
UserData interface{}
//
sinker Sinker
//
timer *time.Ticker
//object local storage
ols [OLS_MAX_SLOT]interface{}
//
recvCmdCnt int64
//
sendCmdCnt int64
//
cond *Cond
}
func NewObject(id int, name string, opt Options, sinker Sinker) *Object {
o := &Object{
Id: id,
Name: name,
opt: opt,
sinker: sinker,
waitActive: make(chan struct{}, 1),
waitEnlarge: make(chan struct{}, 1),
childs: container.NewSynchronizedMap(),
cond: NewCond(1),
}
o.init()
go func() {
defer func() {
if err := recover(); err != nil {
logger.Logger.Error(o, "panic, o.ProcessCommand error=", err)
}
}()
o.ProcessCommand()
}()
return o
}
func (o *Object) GetTreeName() string {
name := o.Name
parent := o.owner
for parent != nil {
name = parent.Name + "/" + name
parent = parent.owner
}
return "/" + name
}
func (o *Object) init() {
o.que = list.New()
}
// Active inner goroutine
func (o *Object) Active() {
o.waitActive <- struct{}{}
}
// Launch the supplied object and become its owner.
func (o *Object) LaunchChild(c *Object) {
if c == nil {
return
}
if c.owner != nil {
panic("An object can have only one parent node")
}
c.owner = o
c.Waitor = o.Waitor
c.Active()
c.safeStart()
// Take ownership of the object.
SendOwn(o, c)
}
// thread safe
func (o *Object) GetChildById(id int) *Object {
c := o.childs.Get(id)
if cc, ok := c.(*Object); ok {
return cc
}
return nil
}
// When another owned object wants to send command to this object
// it calls this function to let it know it should not shut down
// before the command is delivered.
func (o *Object) incSeqnum() {
atomic.AddUint32(&(o.sentSeqnum), 1)
}
// Special handler called after a command that requires a seqnum
// was processed. The implementation should catch up with its counter
// of processed commands here.
func (o *Object) ProcessSeqnum() {
// Catch up with counter of processed commands.
o.processedSeqnum++
// We may have catched up and still have pending terms acks.
o.checkTermAcks()
}
// Check whether all the peding term acks were delivered.
// If so, deallocate this object.
func (o *Object) checkTermAcks() {
name := o.GetTreeName()
logger.Logger.Debugf("(%v) object checkTermAcks terminating=%v processedSeqnum=%v sentSeqnum=%v termAcks=%v ", name, o.terminating, o.processedSeqnum, o.sentSeqnum, o.termAcks)
if o.terminating && o.processedSeqnum == o.sentSeqnum && o.termAcks == 0 {
// Sanity check. There should be no active children at this point.
// The root object has nobody to confirm the termination to.
// Other nodes will confirm the termination to the owner.
if o.owner != nil {
logger.Logger.Debugf("(%v)->(%v) Object SendTermAck ", o.Name, o.owner.Name)
SendTermAck(o.owner)
}
// Deallocate the resources.
o.processDestroy()
}
}
// Ask owner object to terminate this object. It may take a while
// while actual termination is started. This function should not be
// called more than once.
func (o *Object) Terminate(s *Object) {
// If termination is already underway, there's no point
// in starting it anew.
if o.terminating {
return
}
name := o.GetTreeName()
logger.Logger.Debugf("(%v) object Terminate ", name)
// As for the root of the ownership tree, there's noone to terminate it,
// so it has to terminate itself.
if o.owner == nil {
o.processTerm()
return
}
// If I am an owned object, I'll ask my owner to terminate me.
SendTermReq(o.owner, o)
}
// Term handler is protocted rather than private so that it can
// be intercepted by the derived class. This is useful to add custom
// steps to the beginning of the termination process.
func (o *Object) processTerm() {
// Double termination should never happen.
if o.terminating {
return
}
// Send termination request to all owned objects.
cnt := 0
childs := o.childs.Items()
for _, c := range childs {
if cc, ok := c.(*Object); ok && cc != nil {
SendTerm(cc)
cnt++
}
}
o.termAcks += cnt
name := o.GetTreeName()
logger.Logger.Debugf("(%v) object processTerm, termAcks=%v", name, o.termAcks)
o.safeStop()
// Start termination process and check whether by chance we cannot
// terminate immediately.
o.terminating = true
o.checkTermAcks()
}
// A place to hook in when phyicallal destruction of the object
// is to be delayed.
func (o *Object) processDestroy() {
name := o.GetTreeName()
logger.Logger.Debugf("(%v) object processDestroy ", name)
o.terminated = true
//clear ols
o.OlsClrValue()
}
func (o *Object) GetPendingCommandCnt() int {
o.RLock()
cnt := o.que.Len()
o.RUnlock()
return cnt
}
// Enqueue command
func (o *Object) SendCommand(c Command, incseq bool) bool {
if incseq {
o.incSeqnum()
}
o.Lock()
o.que.PushBack(c)
o.Unlock()
atomic.AddInt64(&o.sendCmdCnt, 1)
//notify
o.cond.Signal()
return true
}
// Dequeue command and process it.
func (o *Object) ProcessCommand() {
//wait for active
<-o.waitActive
//deamon or no
if o.Waitor != nil {
o.Waitor.Add(o.Name, 1)
defer o.Waitor.Done(o.Name)
}
var tickMode bool
if o.opt.Interval > 0 && o.sinker != nil && o.timer == nil {
o.timer = time.NewTicker(o.opt.Interval)
defer o.timer.Stop()
tickMode = true
}
name := o.GetTreeName()
logger.Logger.Debug("(", name, ") object active!!!")
doneCnt := 0
for !o.terminated {
cnt := o.GetPendingCommandCnt()
if cnt == 0 {
if tickMode {
if o.cond.WaitForTick(o.timer) {
//logger.Logger.Debug("(", name, ") object safeTick 1 ", time.Now())
o.safeTick()
doneCnt = 0
continue
}
} else {
o.cond.Wait()
}
}
o.Lock()
e := o.que.Front()
if e != nil {
o.que.Remove(e)
}
o.Unlock()
if e != nil {
if cmd, ok := e.Value.(Command); ok {
o.safeDone(cmd)
doneCnt++
}
}
if tickMode {
select {
case <-o.timer.C:
//logger.Logger.Debug("(", name, ") object safeTick 2 ", time.Now())
o.safeTick()
doneCnt = 0
default:
}
// 在一个心跳周期内待处理任务过多
// cnt 剩余任务数量(待处理任务)
// MaxDone 允许最大待处理任务数量
// doneCnt 当前心跳周期内已经处理的任务数量
if doneCnt > o.opt.MaxDone || cnt > o.opt.MaxDone {
logger.Logger.Warn("(", name, ") object queue cmd count(", cnt, ") maxdone(", o.opt.MaxDone, ")", " this tick process cnt(", doneCnt, ")")
}
}
}
cnt := o.GetPendingCommandCnt()
logger.Logger.Debug("(", name, ") object ProcessCommand done!!! queue rest cmd count(", cnt, ") ")
}
func (o *Object) safeDone(cmd Command) {
defer utils.DumpStackIfPanic("Object::Command::Done")
if StatsWatchMgr != nil {
watch := StatsWatchMgr.WatchStart(fmt.Sprintf("/object/%v/cmdone", o.Name), 4)
if watch != nil {
defer watch.Stop()
}
}
err := cmd.Done(o)
atomic.AddInt64(&o.recvCmdCnt, 1)
if err != nil {
panic(err)
}
}
func (o *Object) safeStart() {
defer utils.DumpStackIfPanic("Object::OnStart")
if o.sinker != nil {
o.sinker.OnStart()
}
}
func (o *Object) safeTick() {
defer utils.DumpStackIfPanic("Object::OnTick")
if o.sinker != nil {
o.sinker.OnTick()
}
}
func (o *Object) safeStop() {
defer utils.DumpStackIfPanic("Object::OnStop")
if o.sinker != nil {
o.sinker.OnStop()
}
}
func (o *Object) IsTermiated() bool {
return o.terminated
}
func (o *Object) StatsSelf() (stats CmdStats) {
stats.PendingCnt = int64(o.GetPendingCommandCnt())
stats.SendCmdCnt = atomic.LoadInt64(&o.sendCmdCnt)
stats.RecvCmdCnt = atomic.LoadInt64(&o.recvCmdCnt)
return
}
func (o *Object) GetStats() map[string]CmdStats {
if o.childs == nil {
return nil
}
stats := make(map[string]CmdStats)
stats[o.GetTreeName()] = o.StatsSelf()
childs := o.childs.Items()
for _, c := range childs {
if cc, ok := c.(*Object); ok && cc != nil {
stats[cc.GetTreeName()] = cc.StatsSelf()
subStats := cc.GetStats()
if subStats != nil && len(subStats) > 0 {
for k, v := range subStats {
stats[k] = v
}
}
}
}
return stats
}

92
core/basic/object_test.go Normal file
View File

@ -0,0 +1,92 @@
package basic
import (
"fmt"
"runtime"
"testing"
"time"
)
func TestSendCommand(t *testing.T) {
n := 5
opt := Options{
Interval: time.Second,
MaxDone: n,
}
c := make(chan int)
o := NewObject(1, "test1", opt, nil)
o.Active()
for i := 0; i < n*2; i++ {
go func(tag int) {
o.SendCommand(CommandWrapper(func(*Object) error {
c <- tag
return nil
}), true)
}(i)
}
go func() {
i := 0
for {
i++
if i%1000 == 0 {
runtime.Gosched()
}
}
}()
slice := make([]int, 0, n*2)
for i := 0; i < n*2; i++ {
tag := <-c
slice = append(slice, tag)
}
if len(slice) != n*2 {
t.Fatal("Command be droped")
}
fmt.Println("TestSendCommand", slice)
}
func TestSendCommandLoop(t *testing.T) {
n := 5
m := n * 2
opt := Options{
Interval: time.Second,
MaxDone: n,
}
c := make(chan int)
o := NewObject(1, "test1", opt, nil)
o.Active()
for i := 0; i < n; i++ {
go func(tag int) {
o.SendCommand(CommandWrapper(func(oo *Object) error {
for j := 0; j < m; j++ {
func(tag2 int) {
oo.SendCommand(CommandWrapper(func(*Object) error {
c <- tag*1000 + tag2
return nil
}), true)
}(j)
}
return nil
}), true)
}(i)
}
go func() {
i := 0
for {
i++
if i%1000 == 0 {
runtime.Gosched()
}
}
}()
slice := make([]int, 0, n*m)
for i := 0; i < n*m; i++ {
tag := <-c
slice = append(slice, tag)
}
if len(slice) != n*m {
t.Fatal("Command be droped")
}
fmt.Println("TestSendCommandLoop", slice, len(slice))
}

View File

@ -0,0 +1,93 @@
package basic
import (
"math"
"sync"
"mongo.games.com/goserver/core/container"
)
// Be similar to (Windows, Thread Local Storage)
const OLS_MAX_SLOT uint = 64
const OLS_INVALID_SLOT = math.MaxUint32
type OlsSlotCleanHandler func(interface{})
var objSlotFlag uint64
var objSlotLock sync.Mutex
var objSlotCleanHandler [OLS_MAX_SLOT]OlsSlotCleanHandler
var objSlotHolder = container.NewSynchronizedMap()
func OlsAlloc() uint {
objSlotLock.Lock()
for i := uint(0); i < 64; i++ {
if ((1 << i) & objSlotFlag) == 0 {
objSlotFlag |= (1 << i)
objSlotLock.Unlock()
return i
}
}
objSlotLock.Unlock()
return OLS_INVALID_SLOT
}
func OlsFree(slot uint) {
objSlotLock.Lock()
defer objSlotLock.Unlock()
if slot < OLS_MAX_SLOT {
handler := objSlotCleanHandler[slot]
flag := objSlotFlag & (1 << slot)
if handler != nil && flag != 0 {
objSlotFlag ^= (1 << slot)
objSlotHolder.Foreach(func(k, v interface{}) {
if o, ok := k.(*Object); ok && o != nil {
v := o.ols[slot]
if v != nil {
o.ols[slot] = nil
handler(v)
}
}
})
}
}
}
func OlsInstallSlotCleanHandler(slot uint, handler OlsSlotCleanHandler) {
if slot < OLS_MAX_SLOT {
objSlotCleanHandler[slot] = handler
}
}
func (o *Object) OlsGetValue(slot uint) interface{} {
if slot < OLS_MAX_SLOT {
return o.ols[slot]
}
return nil
}
func (o *Object) OlsSetValue(slot uint, val interface{}) {
if slot < OLS_MAX_SLOT {
old := o.ols[slot]
o.ols[slot] = val
if old != nil {
handler := objSlotCleanHandler[slot]
if handler != nil {
handler(old)
}
}
objSlotHolder.Set(o, struct{}{})
}
}
func (o *Object) OlsClrValue() {
for i := uint(0); i < OLS_MAX_SLOT; i++ {
v := o.ols[i]
if v != nil {
handler := objSlotCleanHandler[i]
if handler != nil {
handler(v)
}
}
}
}

View File

@ -0,0 +1,29 @@
package basic
var StatsWatchMgr IStatsWatchMgr
type ObjectMonitor struct {
}
func (om *ObjectMonitor) OnStart(o *Object) {
}
func (om *ObjectMonitor) OnTick(o *Object) {
}
func (om *ObjectMonitor) OnStop(o *Object) {
}
type IStatsWatchMgr interface {
WatchStart(name string, elementype int) IStatsWatch
}
type IStatsWatch interface {
Stop()
}
type CmdStats struct {
PendingCnt int64
SendCmdCnt int64
RecvCmdCnt int64
}

19
core/basic/options.go Normal file
View File

@ -0,0 +1,19 @@
package basic
import (
"time"
)
const (
QueueType_List int = iota
QueueType_Chan
)
type Options struct {
// HeartBeat interval
Interval time.Duration
// The maximum number of processing each heartbeat
MaxDone int
//
QueueBacklog int
}

7
core/basic/sinker.go Normal file
View File

@ -0,0 +1,7 @@
package basic
type Sinker interface {
OnStart()
OnTick()
OnStop()
}

39
core/broker/broker.go Normal file
View File

@ -0,0 +1,39 @@
// Package broker is an interface used for asynchronous messaging
package broker
// Broker is an interface used for asynchronous messaging.
type Broker interface {
Init(...Option) error
Options() Options
Address() string
Connect() error
Disconnect() error
Publish(topic string, m *Message, opts ...PublishOption) error
Subscribe(topic string, h Handler, opts ...SubscribeOption) (Subscriber, error)
String() string
}
// Handler is used to process messages via a subscription of a topic.
// The handler is passed a publication interface which contains the
// message and optional Ack method to acknowledge receipt of the message.
type Handler func(Event) error
type Message struct {
Header map[string]string
Body []byte
}
// Event is given to a subscription handler for processing
type Event interface {
Topic() string
Message() *Message
Ack() error
Error() error
}
// Subscriber is a convenience return type for the Subscribe method
type Subscriber interface {
Options() SubscribeOptions
Topic() string
Unsubscribe() error
}

117
core/broker/options.go Normal file
View File

@ -0,0 +1,117 @@
package broker
import (
"context"
"crypto/tls"
)
type Options struct {
Addrs []string
Secure bool
// Handler executed when error happens in broker mesage
// processing
ErrorHandler Handler
TLSConfig *tls.Config
// Other options for implementations of the interface
// can be stored in a context
Context context.Context
}
type PublishOptions struct {
// Other options for implementations of the interface
// can be stored in a context
Context context.Context
}
type SubscribeOptions struct {
// AutoAck defaults to true. When a handler returns
// with a nil error the message is acked.
AutoAck bool
// Subscribers with the same queue name
// will create a shared subscription where each
// receives a subset of messages.
Queue string
// Other options for implementations of the interface
// can be stored in a context
Context context.Context
}
type Option func(*Options)
type PublishOption func(*PublishOptions)
// PublishContext set context
func PublishContext(ctx context.Context) PublishOption {
return func(o *PublishOptions) {
o.Context = ctx
}
}
type SubscribeOption func(*SubscribeOptions)
func NewSubscribeOptions(opts ...SubscribeOption) SubscribeOptions {
opt := SubscribeOptions{
AutoAck: true,
}
for _, o := range opts {
o(&opt)
}
return opt
}
// Addrs sets the host addresses to be used by the broker
func Addrs(addrs ...string) Option {
return func(o *Options) {
o.Addrs = addrs
}
}
// DisableAutoAck will disable auto acking of messages
// after they have been handled.
func DisableAutoAck() SubscribeOption {
return func(o *SubscribeOptions) {
o.AutoAck = false
}
}
// ErrorHandler will catch all broker errors that cant be handled
// in normal way, for example Codec errors
func ErrorHandler(h Handler) Option {
return func(o *Options) {
o.ErrorHandler = h
}
}
// Queue sets the name of the queue to share messages on
func Queue(name string) SubscribeOption {
return func(o *SubscribeOptions) {
o.Queue = name
}
}
// Secure communication with the broker
func Secure(b bool) Option {
return func(o *Options) {
o.Secure = b
}
}
// Specify TLS Config
func TLSConfig(t *tls.Config) Option {
return func(o *Options) {
o.TLSConfig = t
}
}
// SubscribeContext set context
func SubscribeContext(ctx context.Context) SubscribeOption {
return func(o *SubscribeOptions) {
o.Context = ctx
}
}

View File

@ -0,0 +1,12 @@
package rabbitmq
type ExternalAuthentication struct {
}
func (auth *ExternalAuthentication) Mechanism() string {
return "EXTERNAL"
}
func (auth *ExternalAuthentication) Response() string {
return ""
}

View File

@ -0,0 +1,143 @@
package rabbitmq
//
// All credit to Mondo
//
import (
"errors"
"github.com/google/uuid"
"github.com/streadway/amqp"
)
type rabbitMQChannel struct {
uuid string
connection *amqp.Connection
channel *amqp.Channel
}
func newRabbitChannel(conn *amqp.Connection, prefetchCount int, prefetchGlobal bool) (*rabbitMQChannel, error) {
id, err := uuid.NewRandom()
if err != nil {
return nil, err
}
rabbitCh := &rabbitMQChannel{
uuid: id.String(),
connection: conn,
}
if err := rabbitCh.Connect(prefetchCount, prefetchGlobal); err != nil {
return nil, err
}
return rabbitCh, nil
}
func (r *rabbitMQChannel) Connect(prefetchCount int, prefetchGlobal bool) error {
var err error
r.channel, err = r.connection.Channel()
if err != nil {
return err
}
err = r.channel.Qos(prefetchCount, 0, prefetchGlobal)
if err != nil {
return err
}
return nil
}
func (r *rabbitMQChannel) Close() error {
if r.channel == nil {
return errors.New("Channel is nil")
}
return r.channel.Close()
}
func (r *rabbitMQChannel) Publish(exchange, key string, message amqp.Publishing) error {
if r.channel == nil {
return errors.New("Channel is nil")
}
return r.channel.Publish(exchange, key, false, false, message)
}
func (r *rabbitMQChannel) DeclareExchange(exchange string) error {
return r.channel.ExchangeDeclare(
exchange, // name
"topic", // kind
false, // durable
false, // autoDelete
false, // internal
false, // noWait
nil, // args
)
}
func (r *rabbitMQChannel) DeclareDurableExchange(exchange string) error {
return r.channel.ExchangeDeclare(
exchange, // name
"topic", // kind
true, // durable
false, // autoDelete
false, // internal
false, // noWait
nil, // args
)
}
func (r *rabbitMQChannel) DeclareQueue(queue string, args amqp.Table) error {
_, err := r.channel.QueueDeclare(
queue, // name
false, // durable
true, // autoDelete
false, // exclusive
false, // noWait
args, // args
)
return err
}
func (r *rabbitMQChannel) DeclareDurableQueue(queue string, args amqp.Table) error {
_, err := r.channel.QueueDeclare(
queue, // name
true, // durable
false, // autoDelete
false, // exclusive
false, // noWait
args, // args
)
return err
}
func (r *rabbitMQChannel) DeclareReplyQueue(queue string) error {
_, err := r.channel.QueueDeclare(
queue, // name
false, // durable
true, // autoDelete
true, // exclusive
false, // noWait
nil, // args
)
return err
}
func (r *rabbitMQChannel) ConsumeQueue(queue string, autoAck bool) (<-chan amqp.Delivery, error) {
return r.channel.Consume(
queue, // queue
r.uuid, // consumer
autoAck, // autoAck
false, // exclusive
false, // nolocal
false, // nowait
nil, // args
)
}
func (r *rabbitMQChannel) BindQueue(queue, key, exchange string, args amqp.Table) error {
return r.channel.QueueBind(
queue, // name
key, // key
exchange, // exchange
false, // noWait
args, // args
)
}

View File

@ -0,0 +1,252 @@
package rabbitmq
//
// All credit to Mondo
//
import (
"crypto/tls"
"regexp"
"strings"
"sync"
"time"
"github.com/streadway/amqp"
)
var (
DefaultExchange = Exchange{
Name: "idealeak",
}
DefaultRabbitURL = "amqp://guest:guest@127.0.0.1:5672"
DefaultPrefetchCount = 0
DefaultPrefetchGlobal = false
DefaultRequeueOnError = false
// The amqp library does not seem to set these when using amqp.DialConfig
// (even though it says so in the comments) so we set them manually to make
// sure to not brake any existing functionality
defaultHeartbeat = 10 * time.Second
defaultLocale = "en_US"
defaultAmqpConfig = amqp.Config{
Heartbeat: defaultHeartbeat,
Locale: defaultLocale,
}
dial = amqp.Dial
dialTLS = amqp.DialTLS
dialConfig = amqp.DialConfig
)
type rabbitMQConn struct {
Connection *amqp.Connection
Channel *rabbitMQChannel
ExchangeChannel *rabbitMQChannel
exchange Exchange
url string
prefetchCount int
prefetchGlobal bool
sync.Mutex
connected bool
close chan bool // 关闭信号
waitConnection chan struct{} // 建立连接中
}
// Exchange is the rabbitmq exchange
type Exchange struct {
// Name of the exchange
Name string
// Whether its persistent
Durable bool
}
func newRabbitMQConn(ex Exchange, urls []string, prefetchCount int, prefetchGlobal bool) *rabbitMQConn {
var url string
if len(urls) > 0 && regexp.MustCompile("^amqp(s)?://.*").MatchString(urls[0]) {
url = urls[0]
} else {
url = DefaultRabbitURL
}
ret := &rabbitMQConn{
exchange: ex,
url: url,
prefetchCount: prefetchCount,
prefetchGlobal: prefetchGlobal,
close: make(chan bool),
waitConnection: make(chan struct{}),
}
// its bad case of nil == waitConnection, so close it at start
close(ret.waitConnection)
return ret
}
func (r *rabbitMQConn) connect(secure bool, config *amqp.Config) error {
// try connect
if err := r.tryConnect(secure, config); err != nil {
return err
}
// connected
r.Lock()
r.connected = true
r.Unlock()
// create reconnect loop
go r.reconnect(secure, config)
return nil
}
func (r *rabbitMQConn) reconnect(secure bool, config *amqp.Config) {
// skip first connect
var connect bool
for {
if connect {
// try reconnect
if err := r.tryConnect(secure, config); err != nil {
time.Sleep(1 * time.Second)
continue
}
// connected
r.Lock()
r.connected = true
r.Unlock()
//unblock resubscribe cycle - close channel
//at this point channel is created and unclosed - close it without any additional checks
close(r.waitConnection)
}
connect = true
notifyClose := make(chan *amqp.Error)
r.Connection.NotifyClose(notifyClose)
// block until closed
select {
case <-notifyClose:
// block all resubscribe attempt - they are useless because there is no connection to rabbitmq
// create channel 'waitConnection' (at this point channel is nil or closed, create it without unnecessary checks)
r.Lock()
r.connected = false
r.waitConnection = make(chan struct{})
r.Unlock()
case <-r.close:
return
}
}
}
func (r *rabbitMQConn) Connect(secure bool, config *amqp.Config) error {
r.Lock()
// already connected
if r.connected {
r.Unlock()
return nil
}
// check it was closed
select {
case <-r.close:
r.close = make(chan bool)
default:
// no op
// new conn
}
r.Unlock()
return r.connect(secure, config)
}
func (r *rabbitMQConn) Close() error {
r.Lock()
defer r.Unlock()
select {
case <-r.close:
return nil
default:
close(r.close)
r.connected = false
}
return r.Connection.Close()
}
func (r *rabbitMQConn) tryConnect(secure bool, config *amqp.Config) error {
var err error
if config == nil {
config = &defaultAmqpConfig
}
url := r.url
if secure || config.TLSClientConfig != nil || strings.HasPrefix(r.url, "amqps://") {
if config.TLSClientConfig == nil {
config.TLSClientConfig = &tls.Config{
InsecureSkipVerify: true,
}
}
url = strings.Replace(r.url, "amqp://", "amqps://", 1)
}
r.Connection, err = dialConfig(url, *config)
if err != nil {
return err
}
if r.Channel, err = newRabbitChannel(r.Connection, r.prefetchCount, r.prefetchGlobal); err != nil {
return err
}
if r.exchange.Durable {
r.Channel.DeclareDurableExchange(r.exchange.Name)
} else {
r.Channel.DeclareExchange(r.exchange.Name)
}
r.ExchangeChannel, err = newRabbitChannel(r.Connection, r.prefetchCount, r.prefetchGlobal)
return err
}
func (r *rabbitMQConn) Consume(queue, key string, headers amqp.Table, qArgs amqp.Table, autoAck, durableQueue bool) (*rabbitMQChannel, <-chan amqp.Delivery, error) {
consumerChannel, err := newRabbitChannel(r.Connection, r.prefetchCount, r.prefetchGlobal)
if err != nil {
return nil, nil, err
}
if durableQueue {
err = consumerChannel.DeclareDurableQueue(queue, qArgs)
} else {
err = consumerChannel.DeclareQueue(queue, qArgs)
}
if err != nil {
return nil, nil, err
}
deliveries, err := consumerChannel.ConsumeQueue(queue, autoAck)
if err != nil {
return nil, nil, err
}
err = consumerChannel.BindQueue(queue, key, r.exchange.Name, headers)
if err != nil {
return nil, nil, err
}
return consumerChannel, deliveries, nil
}
func (r *rabbitMQConn) Publish(exchange, key string, msg amqp.Publishing) error {
return r.ExchangeChannel.Publish(exchange, key, msg)
}

View File

@ -0,0 +1,106 @@
package rabbitmq
import (
"crypto/tls"
"errors"
"testing"
"github.com/streadway/amqp"
)
func TestNewRabbitMQConnURL(t *testing.T) {
testcases := []struct {
title string
urls []string
want string
}{
{"Multiple URLs", []string{"amqp://example.com/one", "amqp://example.com/two"}, "amqp://example.com/one"},
{"Insecure URL", []string{"amqp://example.com"}, "amqp://example.com"},
{"Secure URL", []string{"amqps://example.com"}, "amqps://example.com"},
{"Invalid URL", []string{"http://example.com"}, DefaultRabbitURL},
{"No URLs", []string{}, DefaultRabbitURL},
}
for _, test := range testcases {
conn := newRabbitMQConn(Exchange{Name: "exchange"}, test.urls, 0, false)
if have, want := conn.url, test.want; have != want {
t.Errorf("%s: invalid url, want %q, have %q", test.title, want, have)
}
}
}
func TestTryToConnectTLS(t *testing.T) {
var (
dialCount, dialTLSCount int
err = errors.New("stop connect here")
)
dialConfig = func(_ string, c amqp.Config) (*amqp.Connection, error) {
if c.TLSClientConfig != nil {
dialTLSCount++
return nil, err
}
dialCount++
return nil, err
}
testcases := []struct {
title string
url string
secure bool
amqpConfig *amqp.Config
wantTLS bool
}{
{"unsecure url, secure false, no tls config", "amqp://example.com", false, nil, false},
{"secure url, secure false, no tls config", "amqps://example.com", false, nil, true},
{"unsecure url, secure true, no tls config", "amqp://example.com", true, nil, true},
{"unsecure url, secure false, tls config", "amqp://example.com", false, &amqp.Config{TLSClientConfig: &tls.Config{}}, true},
}
for _, test := range testcases {
dialCount, dialTLSCount = 0, 0
conn := newRabbitMQConn(Exchange{Name: "exchange"}, []string{test.url}, 0, false)
conn.tryConnect(test.secure, test.amqpConfig)
have := dialCount
if test.wantTLS {
have = dialTLSCount
}
if have != 1 {
t.Errorf("%s: used wrong dialer, Dial called %d times, DialTLS called %d times", test.title, dialCount, dialTLSCount)
}
}
}
func TestNewRabbitMQPrefetch(t *testing.T) {
testcases := []struct {
title string
urls []string
prefetchCount int
prefetchGlobal bool
}{
{"Multiple URLs", []string{"amqp://example.com/one", "amqp://example.com/two"}, 1, true},
{"Insecure URL", []string{"amqp://example.com"}, 1, true},
{"Secure URL", []string{"amqps://example.com"}, 1, true},
{"Invalid URL", []string{"http://example.com"}, 1, true},
{"No URLs", []string{}, 1, true},
}
for _, test := range testcases {
conn := newRabbitMQConn(Exchange{Name: "exchange"}, test.urls, test.prefetchCount, test.prefetchGlobal)
if have, want := conn.prefetchCount, test.prefetchCount; have != want {
t.Errorf("%s: invalid prefetch count, want %d, have %d", test.title, want, have)
}
if have, want := conn.prefetchGlobal, test.prefetchGlobal; have != want {
t.Errorf("%s: invalid prefetch global setting, want %t, have %t", test.title, want, have)
}
}
}

View File

@ -0,0 +1,37 @@
package rabbitmq
import (
"context"
"mongo.games.com/goserver/core/broker"
)
// setSubscribeOption returns a function to setup a context with given value
func setSubscribeOption(k, v interface{}) broker.SubscribeOption {
return func(o *broker.SubscribeOptions) {
if o.Context == nil {
o.Context = context.Background()
}
o.Context = context.WithValue(o.Context, k, v)
}
}
// setBrokerOption returns a function to setup a context with given value
func setBrokerOption(k, v interface{}) broker.Option {
return func(o *broker.Options) {
if o.Context == nil {
o.Context = context.Background()
}
o.Context = context.WithValue(o.Context, k, v)
}
}
// setPublishOption returns a function to setup a context with given value
func setPublishOption(k, v interface{}) broker.PublishOption {
return func(o *broker.PublishOptions) {
if o.Context == nil {
o.Context = context.Background()
}
o.Context = context.WithValue(o.Context, k, v)
}
}

View File

@ -0,0 +1,87 @@
package rabbitmq
import (
"context"
"mongo.games.com/goserver/core/broker"
)
type durableQueueKey struct{}
type headersKey struct{}
type queueArgumentsKey struct{}
type prefetchCountKey struct{}
type prefetchGlobalKey struct{}
type exchangeKey struct{}
type requeueOnErrorKey struct{}
type deliveryMode struct{}
type priorityKey struct{}
type externalAuth struct{}
type durableExchange struct{}
// DurableQueue creates a durable queue when subscribing.
func DurableQueue() broker.SubscribeOption {
return setSubscribeOption(durableQueueKey{}, true)
}
// DurableExchange is an option to set the Exchange to be durable
func DurableExchange() broker.Option {
return setBrokerOption(durableExchange{}, true)
}
// Headers adds headers used by the headers exchange
func Headers(h map[string]interface{}) broker.SubscribeOption {
return setSubscribeOption(headersKey{}, h)
}
// QueueArguments sets arguments for queue creation
func QueueArguments(h map[string]interface{}) broker.SubscribeOption {
return setSubscribeOption(queueArgumentsKey{}, h)
}
// RequeueOnError calls Nack(muliple:false, requeue:true) on amqp delivery when handler returns error
func RequeueOnError() broker.SubscribeOption {
return setSubscribeOption(requeueOnErrorKey{}, true)
}
// ExchangeName is an option to set the ExchangeName
func ExchangeName(e string) broker.Option {
return setBrokerOption(exchangeKey{}, e)
}
// PrefetchCount ...
func PrefetchCount(c int) broker.Option {
return setBrokerOption(prefetchCountKey{}, c)
}
// PrefetchGlobal creates a durable queue when subscribing.
func PrefetchGlobal() broker.Option {
return setBrokerOption(prefetchGlobalKey{}, true)
}
// DeliveryMode sets a delivery mode for publishing
func DeliveryMode(value uint8) broker.PublishOption {
return setPublishOption(deliveryMode{}, value)
}
// Priority sets a priority level for publishing
func Priority(value uint8) broker.PublishOption {
return setPublishOption(priorityKey{}, value)
}
func ExternalAuth() broker.Option {
return setBrokerOption(externalAuth{}, ExternalAuthentication{})
}
type subscribeContextKey struct{}
// SubscribeContext set the context for broker.SubscribeOption
func SubscribeContext(ctx context.Context) broker.SubscribeOption {
return setSubscribeOption(subscribeContextKey{}, ctx)
}
type ackSuccessKey struct{}
// AckOnSuccess will automatically acknowledge messages when no error is returned
func AckOnSuccess() broker.SubscribeOption {
return setSubscribeOption(ackSuccessKey{}, true)
}

View File

@ -0,0 +1,335 @@
// Package rabbitmq provides a RabbitMQ broker
package rabbitmq
import (
"context"
"errors"
"sync"
"time"
"github.com/streadway/amqp"
"mongo.games.com/goserver/core/broker"
)
type rbroker struct {
conn *rabbitMQConn
addrs []string
opts broker.Options
prefetchCount int
prefetchGlobal bool
mtx sync.Mutex
wg sync.WaitGroup
}
type subscriber struct {
mtx sync.Mutex
mayRun bool
opts broker.SubscribeOptions
topic string
ch *rabbitMQChannel
durableQueue bool
queueArgs map[string]interface{}
r *rbroker
fn func(msg amqp.Delivery)
headers map[string]interface{}
}
type publication struct {
d amqp.Delivery
m *broker.Message
t string
err error
}
func (p *publication) Ack() error {
return p.d.Ack(false)
}
func (p *publication) Error() error {
return p.err
}
func (p *publication) Topic() string {
return p.t
}
func (p *publication) Message() *broker.Message {
return p.m
}
func (s *subscriber) Options() broker.SubscribeOptions {
return s.opts
}
func (s *subscriber) Topic() string {
return s.topic
}
func (s *subscriber) Unsubscribe() error {
s.mtx.Lock()
defer s.mtx.Unlock()
s.mayRun = false
if s.ch != nil {
return s.ch.Close()
}
return nil
}
func (s *subscriber) resubscribe() {
minResubscribeDelay := 100 * time.Millisecond
maxResubscribeDelay := 30 * time.Second
expFactor := time.Duration(2)
reSubscribeDelay := minResubscribeDelay
//loop until unsubscribe
for {
s.mtx.Lock()
mayRun := s.mayRun
s.mtx.Unlock()
if !mayRun {
// we are unsubscribed, showdown routine
return
}
select {
//check shutdown case
case <-s.r.conn.close:
//yep, its shutdown case
return
//wait until we reconect to rabbit
case <-s.r.conn.waitConnection:
}
// it may crash (panic) in case of Consume without connection, so recheck it
s.r.mtx.Lock()
if !s.r.conn.connected {
s.r.mtx.Unlock()
continue
}
ch, sub, err := s.r.conn.Consume(
s.opts.Queue,
s.topic,
s.headers,
s.queueArgs,
s.opts.AutoAck,
s.durableQueue,
)
s.r.mtx.Unlock()
switch err {
case nil:
reSubscribeDelay = minResubscribeDelay
s.mtx.Lock()
s.ch = ch
s.mtx.Unlock()
default:
if reSubscribeDelay > maxResubscribeDelay {
reSubscribeDelay = maxResubscribeDelay
}
time.Sleep(reSubscribeDelay)
reSubscribeDelay *= expFactor
continue
}
for d := range sub {
s.r.wg.Add(1)
s.fn(d)
s.r.wg.Done()
}
}
}
func (r *rbroker) Publish(topic string, msg *broker.Message, opts ...broker.PublishOption) error {
m := amqp.Publishing{
Body: msg.Body,
Headers: amqp.Table{},
}
options := broker.PublishOptions{}
for _, o := range opts {
o(&options)
}
if options.Context != nil {
if value, ok := options.Context.Value(deliveryMode{}).(uint8); ok {
m.DeliveryMode = value
}
if value, ok := options.Context.Value(priorityKey{}).(uint8); ok {
m.Priority = value
}
}
for k, v := range msg.Header {
m.Headers[k] = v
}
if r.conn == nil {
return errors.New("connection is nil")
}
return r.conn.Publish(r.conn.exchange.Name, topic, m)
}
func (r *rbroker) Subscribe(topic string, handler broker.Handler, opts ...broker.SubscribeOption) (broker.Subscriber, error) {
var ackSuccess bool
if r.conn == nil {
return nil, errors.New("not connected")
}
opt := broker.SubscribeOptions{
AutoAck: true,
}
for _, o := range opts {
o(&opt)
}
// Make sure context is setup
if opt.Context == nil {
opt.Context = context.Background()
}
ctx := opt.Context
if subscribeContext, ok := ctx.Value(subscribeContextKey{}).(context.Context); ok && subscribeContext != nil {
ctx = subscribeContext
}
var requeueOnError bool
requeueOnError, _ = ctx.Value(requeueOnErrorKey{}).(bool)
var durableQueue bool
durableQueue, _ = ctx.Value(durableQueueKey{}).(bool)
var qArgs map[string]interface{}
if qa, ok := ctx.Value(queueArgumentsKey{}).(map[string]interface{}); ok {
qArgs = qa
}
var headers map[string]interface{}
if h, ok := ctx.Value(headersKey{}).(map[string]interface{}); ok {
headers = h
}
if bval, ok := ctx.Value(ackSuccessKey{}).(bool); ok && bval {
opt.AutoAck = false
ackSuccess = true
}
fn := func(msg amqp.Delivery) {
header := make(map[string]string)
for k, v := range msg.Headers {
header[k], _ = v.(string)
}
m := &broker.Message{
Header: header,
Body: msg.Body,
}
p := &publication{d: msg, m: m, t: msg.RoutingKey}
p.err = handler(p)
if p.err == nil && ackSuccess && !opt.AutoAck {
msg.Ack(false)
} else if p.err != nil && !opt.AutoAck {
msg.Nack(false, requeueOnError)
}
}
sret := &subscriber{topic: topic, opts: opt, mayRun: true, r: r,
durableQueue: durableQueue, fn: fn, headers: headers, queueArgs: qArgs}
go sret.resubscribe()
return sret, nil
}
func (r *rbroker) Options() broker.Options {
return r.opts
}
func (r *rbroker) String() string {
return "rabbitmq"
}
func (r *rbroker) Address() string {
if len(r.addrs) > 0 {
return r.addrs[0]
}
return ""
}
func (r *rbroker) Init(opts ...broker.Option) error {
for _, o := range opts {
o(&r.opts)
}
r.addrs = r.opts.Addrs
return nil
}
func (r *rbroker) Connect() error {
if r.conn == nil {
r.conn = newRabbitMQConn(r.getExchange(), r.opts.Addrs, r.getPrefetchCount(), r.getPrefetchGlobal())
}
conf := defaultAmqpConfig
if auth, ok := r.opts.Context.Value(externalAuth{}).(ExternalAuthentication); ok {
conf.SASL = []amqp.Authentication{&auth}
}
conf.TLSClientConfig = r.opts.TLSConfig
return r.conn.Connect(r.opts.Secure, &conf)
}
func (r *rbroker) Disconnect() error {
if r.conn == nil {
return errors.New("connection is nil")
}
ret := r.conn.Close()
r.wg.Wait() // wait all goroutines
return ret
}
func NewBroker(opts ...broker.Option) broker.Broker {
options := broker.Options{
Context: context.Background(),
}
for _, o := range opts {
o(&options)
}
return &rbroker{
addrs: options.Addrs,
opts: options,
}
}
func (r *rbroker) getExchange() Exchange {
ex := DefaultExchange
if e, ok := r.opts.Context.Value(exchangeKey{}).(string); ok {
ex.Name = e
}
if d, ok := r.opts.Context.Value(durableExchange{}).(bool); ok {
ex.Durable = d
}
return ex
}
func (r *rbroker) getPrefetchCount() int {
if e, ok := r.opts.Context.Value(prefetchCountKey{}).(int); ok {
return e
}
return DefaultPrefetchCount
}
func (r *rbroker) getPrefetchGlobal() bool {
if e, ok := r.opts.Context.Value(prefetchGlobalKey{}).(bool); ok {
return e
}
return DefaultPrefetchGlobal
}

View File

@ -0,0 +1,37 @@
package rabbitmq_test
import (
"fmt"
"os"
"testing"
"mongo.games.com/goserver/core/broker"
"mongo.games.com/goserver/core/broker/rabbitmq"
)
func MyHandler(e broker.Event) error {
fmt.Println(e.Topic(), ":", e.Message())
return nil
}
func TestDurable(t *testing.T) {
if tr := os.Getenv("TRAVIS"); len(tr) > 0 {
t.Skip()
}
rabbitmq.DefaultRabbitURL = "amqp://win88:123456@192.168.1.230:5672/win88"
b := rabbitmq.NewBroker()
b.Init()
if err := b.Connect(); err != nil {
t.Logf("cant conect to broker, skip: %v", err)
t.Skip()
}
b.Subscribe("test", MyHandler, broker.Queue("queue.default"),
broker.DisableAutoAck(),
rabbitmq.DurableQueue())
for i := 0; i < 100; i++ {
b.Publish("test", &broker.Message{Body: []byte("hello")})
}
}

5
core/build.go Normal file
View File

@ -0,0 +1,5 @@
package core
func BuildTime() string {
return "" //buildTime()
}

18
core/build_darwin.go Normal file
View File

@ -0,0 +1,18 @@
package core
/*
const char* build_time(void)
{
static const char* psz_build_time = "["__DATE__ " " __TIME__ "]";
return psz_build_time;
}
*/
import "C"
var (
_linux_buildTime = C.GoString(C.build_time())
)
func buildTime() string {
return _linux_buildTime
}

18
core/build_linux.go Normal file
View File

@ -0,0 +1,18 @@
package core
/*
const char* build_time(void)
{
static const char* psz_build_time = "["__DATE__ " " __TIME__ "]";
return psz_build_time;
}
*/
import "C"
var (
_linux_buildTime = C.GoString(C.build_time())
)
func buildTime() string {
return _linux_buildTime
}

10
core/build_windows.go Normal file
View File

@ -0,0 +1,10 @@
package core
import (
"fmt"
"time"
)
func buildTime() string {
return fmt.Sprintf("[%s]", time.Now().String())
}

34
core/buildall.bat Normal file
View File

@ -0,0 +1,34 @@
go build
cd admin
go build
cd ../basic
go build
cd ../builtin/action
go build
cd ../filter
go build
cd ../protocol
go build
cd ../../cmdline
go build
cd ../logger
go build
cd ../module
go build
cd ../netlib
go build
cd ../profile
go build
cd ../schedule
go build
cd ../signal
go build
cd ../task
go build
cd ../timer
go build
cd ../transact
go build
cd ../utils
go build
pause

View File

@ -0,0 +1,106 @@
package action
import (
"bytes"
"errors"
"strconv"
"mongo.games.com/goserver/core/builtin/protocol"
"mongo.games.com/goserver/core/netlib"
)
var (
SessionAttributeBigBuf = &PacketSlicesHandler{}
)
type PacketSlicesPacketFactory struct {
}
type PacketSlicesHandler struct {
}
func (this *PacketSlicesPacketFactory) CreatePacket() interface{} {
pack := &protocol.SSPacketSlices{}
return pack
}
func (this *PacketSlicesHandler) Process(s *netlib.Session, packetid int, data interface{}) error {
if packetslices, ok := data.(*protocol.SSPacketSlices); ok {
seqNo := int(packetslices.GetSeqNo())
if seqNo < 1 {
return errors.New("PacketSlicesHandler unexpect packet seq:" + strconv.Itoa(seqNo))
}
totalSize := int(packetslices.GetTotalSize())
if totalSize > s.GetSessionConfig().MaxPacket {
return errors.New("PacketSlicesHandler exceed MaxPacket size:" + strconv.Itoa(s.GetSessionConfig().MaxPacket) + " size=" + strconv.Itoa(totalSize))
}
attr := s.GetAttribute(SessionAttributeBigBuf)
if seqNo == 1 {
if attr == nil {
attr = bytes.NewBuffer(make([]byte, 0, packetslices.GetTotalSize()))
s.SetAttribute(SessionAttributeBigBuf, attr)
}
}
if seqNo > 1 {
if attr == nil {
return errors.New("PacketSlicesHandler Incorrect packet seq, expect seq=1")
}
} else if attr == nil {
return errors.New("PacketSlicesHandler get bytesbuf failed")
}
buf := attr.(*bytes.Buffer)
if seqNo == 1 {
buf.Reset()
}
if buf.Len() != int(packetslices.GetOffset()) {
return errors.New("PacketSlicesHandler get next packet offset error")
}
buf.Write(packetslices.GetPacketData())
if buf.Len() == totalSize {
packetid, pck, err := netlib.UnmarshalPacket(buf.Bytes())
if err != nil {
return err
}
h := netlib.GetHandler(packetid)
if h != nil {
h.Process(s, packetid, pck)
}
}
}
return nil
}
func init() {
netlib.RegisterHandler(int(protocol.CoreBuiltinPacketID_PACKET_SS_SLICES), &PacketSlicesHandler{})
netlib.RegisterFactory(int(protocol.CoreBuiltinPacketID_PACKET_SS_SLICES), &PacketSlicesPacketFactory{})
netlib.DefaultBuiltinProtocolEncoder.PacketCutor = func(data []byte) (packid int, packs []interface{}) {
var (
offset = 0
sendSize = 0
seqNo = 1
totalSize = len(data)
restSize = len(data)
)
packid = int(protocol.CoreBuiltinPacketID_PACKET_SS_SLICES)
for restSize > 0 {
sendSize = restSize
if sendSize > netlib.MaxPacketSize-128 {
sendSize = netlib.MaxPacketSize - 128
}
pack := &protocol.SSPacketSlices{
SeqNo: int32(seqNo),
TotalSize: int32(totalSize),
Offset: int32(offset),
PacketData: data[offset : offset+sendSize],
}
seqNo++
restSize -= sendSize
offset += sendSize
packs = append(packs, pack)
}
return
}
}

View File

@ -0,0 +1,45 @@
package action
import (
"errors"
"strconv"
"google.golang.org/protobuf/proto"
"mongo.games.com/goserver/core/builtin/protocol"
"mongo.games.com/goserver/core/netlib"
"mongo.games.com/goserver/core/transact"
)
type TxCtrlCmdPacketFactory struct {
}
type TxCtrlCmdHandler struct {
}
func (this *TxCtrlCmdPacketFactory) CreatePacket() interface{} {
pack := &protocol.TransactCtrlCmd{}
return pack
}
func (this *TxCtrlCmdHandler) Process(session *netlib.Session, packetid int, data interface{}) error {
//logger.Logger.Trace("TxCtrlCmdHandler.Process")
if txcmd, ok := data.(*protocol.TransactCtrlCmd); ok {
if !transact.ProcessTransCmd(transact.TransNodeID(txcmd.GetTId()), transact.TransCmd(txcmd.GetCmd())) {
return errors.New("TxCtrlCmdHandler error, tid=" + strconv.FormatInt(txcmd.GetTId(), 16) + " cmd=" + strconv.Itoa(int(txcmd.GetCmd())))
}
}
return nil
}
func init() {
netlib.RegisterHandler(int(protocol.CoreBuiltinPacketID_PACKET_SS_TX_CMD), &TxCtrlCmdHandler{})
netlib.RegisterFactory(int(protocol.CoreBuiltinPacketID_PACKET_SS_TX_CMD), &TxCtrlCmdPacketFactory{})
}
func ConstructTxCmdPacket(tnp *transact.TransNodeParam, cmd transact.TransCmd) proto.Message {
packet := &protocol.TransactCtrlCmd{
TId: int64(tnp.TId),
Cmd: int32(cmd),
}
return packet
}

View File

@ -0,0 +1,55 @@
package action
import (
"errors"
"strconv"
"google.golang.org/protobuf/proto"
"mongo.games.com/goserver/core/builtin/protocol"
"mongo.games.com/goserver/core/logger"
"mongo.games.com/goserver/core/netlib"
"mongo.games.com/goserver/core/transact"
)
type TxResultPacketFactory struct {
}
type TxResultHandler struct {
}
func (this *TxResultPacketFactory) CreatePacket() interface{} {
pack := &protocol.TransactResult{}
return pack
}
func (this *TxResultHandler) Process(session *netlib.Session, packetid int, data interface{}) error {
//logger.Logger.Trace("TxResultHandler.Process")
if tr, ok := data.(*protocol.TransactResult); ok {
if !transact.ProcessTransResult(transact.TransNodeID(tr.GetMyTId()), transact.TransNodeID(tr.GetChildTId()), int(tr.GetRetCode()), tr.GetCustomData()) {
return errors.New("TxResultHandler error, tid=" + strconv.FormatInt(tr.GetMyTId(), 16))
}
}
return nil
}
func init() {
netlib.RegisterHandler(int(protocol.CoreBuiltinPacketID_PACKET_SS_TX_RESULT), &TxResultHandler{})
netlib.RegisterFactory(int(protocol.CoreBuiltinPacketID_PACKET_SS_TX_RESULT), &TxResultPacketFactory{})
}
func ContructTxResultPacket(parent, me *transact.TransNodeParam, tr *transact.TransResult) proto.Message {
packet := &protocol.TransactResult{
MyTId: int64(parent.TId),
ChildTId: int64(me.TId),
RetCode: int32(tr.RetCode),
}
if tr.RetFiels != nil {
b, err := netlib.MarshalPacketNoPackId(tr.RetFiels)
if err != nil {
logger.Logger.Warn("ContructTxResultPacket Marshal UserData error:", err)
} else {
packet.CustomData = b
}
}
return packet
}

View File

@ -0,0 +1,110 @@
package action
import (
"errors"
"strconv"
"time"
"google.golang.org/protobuf/proto"
"mongo.games.com/goserver/core/builtin/protocol"
"mongo.games.com/goserver/core/logger"
"mongo.games.com/goserver/core/netlib"
"mongo.games.com/goserver/core/transact"
)
type TxStartPacketFactory struct {
}
type TxStartHandler struct {
}
func (this *TxStartPacketFactory) CreatePacket() interface{} {
pack := &protocol.TransactStart{}
return pack
}
func (this *TxStartHandler) Process(session *netlib.Session, packetid int, data interface{}) error {
//logger.Logger.Trace("TxStartHandler.Process")
if ts, ok := data.(*protocol.TransactStart); ok {
netptnp := ts.GetParenTNP()
if netptnp == nil {
return nil
}
netmtnp := ts.GetMyTNP()
if netmtnp == nil {
return nil
}
ptnp := &transact.TransNodeParam{
TId: transact.TransNodeID(netptnp.GetTransNodeID()),
Tt: transact.TransType(netptnp.GetTransType()),
Ot: transact.TransOwnerType(netptnp.GetOwnerType()),
Tct: transact.TransactCommitPolicy(netptnp.GetTransCommitType()),
Oid: int(netptnp.GetOwnerID()),
SkeletonID: int(netptnp.GetSkeletonID()),
LevelNo: int(netptnp.GetLevelNo()),
AreaID: int(netptnp.GetAreaID()),
TimeOut: time.Duration(netptnp.GetTimeOut()),
ExpiresTs: netptnp.GetExpiresTs(),
}
mtnp := &transact.TransNodeParam{
TId: transact.TransNodeID(netmtnp.GetTransNodeID()),
Tt: transact.TransType(netmtnp.GetTransType()),
Ot: transact.TransOwnerType(netmtnp.GetOwnerType()),
Tct: transact.TransactCommitPolicy(netmtnp.GetTransCommitType()),
Oid: int(netmtnp.GetOwnerID()),
SkeletonID: int(netmtnp.GetSkeletonID()),
LevelNo: int(netmtnp.GetLevelNo()),
AreaID: int(netmtnp.GetAreaID()),
TimeOut: time.Duration(netmtnp.GetTimeOut()),
ExpiresTs: netmtnp.GetExpiresTs(),
}
if !transact.ProcessTransStart(ptnp, mtnp, ts.GetCustomData(), mtnp.TimeOut) {
return errors.New("TxStartHandler error, tid=" + strconv.FormatInt(netmtnp.GetTransNodeID(), 16))
}
}
return nil
}
func init() {
netlib.RegisterHandler(int(protocol.CoreBuiltinPacketID_PACKET_SS_TX_START), &TxStartHandler{})
netlib.RegisterFactory(int(protocol.CoreBuiltinPacketID_PACKET_SS_TX_START), &TxStartPacketFactory{})
}
func ContructTxStartPacket(parent, me *transact.TransNodeParam, ud interface{}) proto.Message {
packet := &protocol.TransactStart{
MyTNP: &protocol.TransactParam{
TransNodeID: int64(me.TId),
TransType: int32(me.Tt),
OwnerType: int32(me.Ot),
TransCommitType: int32(me.Tct),
OwnerID: int32(me.Oid),
SkeletonID: int32(me.SkeletonID),
LevelNo: int32(me.LevelNo),
AreaID: int32(me.AreaID),
TimeOut: int64(me.TimeOut),
},
ParenTNP: &protocol.TransactParam{
TransNodeID: int64(parent.TId),
TransType: int32(parent.Tt),
OwnerType: int32(parent.Ot),
TransCommitType: int32(parent.Tct),
OwnerID: int32(parent.Oid),
SkeletonID: int32(parent.SkeletonID),
LevelNo: int32(parent.LevelNo),
AreaID: int32(parent.AreaID),
TimeOut: int64(parent.TimeOut),
},
}
if ud != nil {
b, err := netlib.MarshalPacketNoPackId(ud)
if err != nil {
logger.Logger.Warn("ContructTxStartPacket Marshal UserData error:", err)
} else {
packet.CustomData = b
}
}
return packet
}

View File

@ -0,0 +1,103 @@
package filter
import (
"crypto/md5"
"encoding/hex"
"fmt"
"time"
"mongo.games.com/goserver/core/builtin/protocol"
"mongo.games.com/goserver/core/logger"
"mongo.games.com/goserver/core/netlib"
)
var (
AuthenticationFilterName = "session-filter-auth"
SessionAttributeAuth = &AuthenticationFilter{}
)
type AuthenticationHandler func(s *netlib.Session, bSuc bool)
type AuthenticationFilter struct {
SessionAuthHandler AuthenticationHandler
}
func (af *AuthenticationFilter) GetName() string {
return AuthenticationFilterName
}
func (af *AuthenticationFilter) GetInterestOps() uint {
return 1<<netlib.InterestOps_Opened | 1<<netlib.InterestOps_Received
}
func (af *AuthenticationFilter) OnSessionOpened(s *netlib.Session) bool {
if s.GetSessionConfig().IsClient {
timestamp := time.Now().Unix()
h := md5.New()
sc := s.GetSessionConfig()
h.Write([]byte(fmt.Sprintf("%v;%v", timestamp, sc.AuthKey)))
authPack := &protocol.SSPacketAuth{
Timestamp: timestamp,
AuthKey: hex.EncodeToString(h.Sum(nil)),
}
s.Send(int(protocol.CoreBuiltinPacketID_PACKET_SS_AUTH), authPack)
}
return true
}
func (af *AuthenticationFilter) OnSessionClosed(s *netlib.Session) bool {
return true
}
func (af *AuthenticationFilter) OnSessionIdle(s *netlib.Session) bool {
return true
}
func (af *AuthenticationFilter) OnPacketReceived(s *netlib.Session, packetid int, logicNo uint32, packet interface{}) bool {
if !s.GetSessionConfig().IsClient {
if !s.Auth {
if auth, ok := packet.(*protocol.SSPacketAuth); ok {
h := md5.New()
rawText := fmt.Sprintf("%v;%v", auth.GetTimestamp(), s.GetSessionConfig().AuthKey)
logger.Logger.Tracef("AuthenticationFilter rawtext=%v IsInnerLink(%v)", rawText, s.GetSessionConfig().IsInnerLink)
h.Write([]byte(rawText))
expectKey := hex.EncodeToString(h.Sum(nil))
if expectKey != auth.GetAuthKey() {
if af.SessionAuthHandler != nil {
af.SessionAuthHandler(s, false)
}
s.Close()
logger.Logger.Tracef("AuthenticationFilter AuthKey error[expect:%v get:%v]", expectKey, auth.GetAuthKey())
return false
}
s.Auth = true
if af.SessionAuthHandler != nil {
af.SessionAuthHandler(s, true)
}
//ack 回一个
authAck := &protocol.SSPacketAuthAck{Msg: "ok"}
s.Send(int(protocol.CoreBuiltinPacketID_PACKET_SS_AUTH_ACK), authAck, false)
return false
} else {
s.Close()
logger.Logger.Warn("AuthenticationFilter packet not expect")
return false
}
}
}
return true
}
func (af *AuthenticationFilter) OnPacketSent(s *netlib.Session, packetid int, logicNo uint32, data []byte) bool {
return true
}
func init() {
netlib.RegisterFactory(int(protocol.CoreBuiltinPacketID_PACKET_SS_AUTH), netlib.PacketFactoryWrapper(func() interface{} {
return &protocol.SSPacketAuth{}
}))
netlib.RegisteSessionFilterCreator(AuthenticationFilterName, func() netlib.SessionFilter {
return &AuthenticationFilter{}
})
}

View File

@ -0,0 +1,102 @@
package filter
import (
"container/list"
"net"
"sync"
"mongo.games.com/goserver/core/netlib"
)
var (
BlackListFilterName = "session-filter-blacklist"
)
type BlackListFilter struct {
lock sync.RWMutex // locker
blacklist *list.List
}
func (blf *BlackListFilter) GetName() string {
return BlackListFilterName
}
func (blf *BlackListFilter) GetInterestOps() uint {
return 1<<netlib.InterestOps_Opened | 1<<netlib.InterestOps_Received | 1<<netlib.InterestOps_Sent
}
func (blf *BlackListFilter) OnSessionOpened(s *netlib.Session) bool {
if blf.isBlock(s) {
blf.blockSession(s)
return false
}
return true
}
func (blf *BlackListFilter) OnSessionClosed(s *netlib.Session) bool {
return true
}
func (blf *BlackListFilter) OnSessionIdle(s *netlib.Session) bool {
return true
}
func (blf *BlackListFilter) OnPacketReceived(s *netlib.Session, packetid int, logicNo uint32, packet interface{}) bool {
if blf.isBlock(s) {
blf.blockSession(s)
return false
}
return true
}
func (blf *BlackListFilter) OnPacketSent(s *netlib.Session, packetid int, logicNo uint32, data []byte) bool {
if blf.isBlock(s) {
blf.blockSession(s)
return false
}
return true
}
func (blf *BlackListFilter) isBlock(s *netlib.Session) bool {
host, _, err := net.SplitHostPort(s.RemoteAddr())
if err != nil {
return true
}
ip := net.ParseIP(host)
blf.lock.RLock()
defer blf.lock.RUnlock()
for e := blf.blacklist.Front(); e != nil; e = e.Next() {
if e.Value.(*net.IPNet).Contains(ip) {
return true
}
}
return false
}
func (blf *BlackListFilter) blockSession(s *netlib.Session) {
s.Close()
}
func (blf *BlackListFilter) Block(ipnet *net.IPNet) {
blf.lock.Lock()
defer blf.lock.Unlock()
blf.blacklist.PushBack(ipnet)
}
func (blf *BlackListFilter) UnBlock(ipnet *net.IPNet) {
blf.lock.Lock()
defer blf.lock.Unlock()
for e := blf.blacklist.Front(); e != nil; e = e.Next() {
if e.Value.(*net.IPNet).String() == ipnet.String() {
blf.blacklist.Remove(e)
return
}
}
}
func init() {
netlib.RegisteSessionFilterCreator(BlackListFilterName, func() netlib.SessionFilter {
return &BlackListFilter{blacklist: list.New()}
})
}

View File

@ -0,0 +1,77 @@
package filter
import (
"net"
"time"
"mongo.games.com/goserver/core/container"
"mongo.games.com/goserver/core/netlib"
)
var (
DefaultAllowedInterval = 500 //ms
ConnectionThrottleFilterName = "session-filter-connectionthrottle"
)
type ConnectionThrottleFilter struct {
clients *container.SynchronizedMap //need synchronize
AllowedInterval int //ms
}
func (ctf *ConnectionThrottleFilter) GetName() string {
return ConnectionThrottleFilterName
}
func (ctf *ConnectionThrottleFilter) GetInterestOps() uint {
return 1 << netlib.InterestOps_Opened
}
func (ctf *ConnectionThrottleFilter) OnSessionOpened(s *netlib.Session) bool {
if !ctf.isConnectionOk(s) {
s.Close()
return false
}
return true
}
func (ctf *ConnectionThrottleFilter) OnSessionClosed(s *netlib.Session) bool {
return true
}
func (ctf *ConnectionThrottleFilter) OnSessionIdle(s *netlib.Session) bool {
return true
}
func (ctf *ConnectionThrottleFilter) OnPacketReceived(s *netlib.Session, packetid int, logicNo uint32, packet interface{}) bool {
return true
}
func (ctf *ConnectionThrottleFilter) OnPacketSent(s *netlib.Session, packetid int, logicNo uint32, data []byte) bool {
return true
}
func (ctf *ConnectionThrottleFilter) isConnectionOk(s *netlib.Session) bool {
host, _, err := net.SplitHostPort(s.RemoteAddr())
if err != nil {
return false
}
tNow := time.Now()
value := ctf.clients.Get(host)
if value != nil {
tLast := value.(time.Time)
if tNow.Sub(tLast) < time.Duration(ctf.AllowedInterval)*time.Millisecond {
ctf.clients.Set(host, tNow)
return false
}
}
ctf.clients.Set(host, tNow)
return true
}
func init() {
netlib.RegisteSessionFilterCreator(ConnectionThrottleFilterName, func() netlib.SessionFilter {
return &ConnectionThrottleFilter{clients: container.NewSynchronizedMap(), AllowedInterval: DefaultAllowedInterval}
})
}

View File

@ -0,0 +1,61 @@
package filter
import (
"mongo.games.com/goserver/core/builtin/protocol"
"mongo.games.com/goserver/core/netlib"
)
var (
KeepAliveFilterName = "session-filter-keepalive"
)
type KeepAliveFilter struct {
}
func (kf *KeepAliveFilter) GetName() string {
return KeepAliveFilterName
}
func (kf *KeepAliveFilter) GetInterestOps() uint {
return 1 << netlib.InterestOps_Idle
}
func (kf *KeepAliveFilter) OnSessionOpened(s *netlib.Session) bool {
return true
}
func (kf *KeepAliveFilter) OnSessionClosed(s *netlib.Session) bool {
return true
}
func (kf *KeepAliveFilter) OnSessionIdle(s *netlib.Session) bool {
p := &protocol.SSPacketKeepAlive{Flag: 0}
s.Send(int(protocol.CoreBuiltinPacketID_PACKET_SS_KEEPALIVE), p)
return true
}
func (kf *KeepAliveFilter) OnPacketReceived(s *netlib.Session, packetid int, logicNo uint32, packet interface{}) bool {
return true
}
func (kf *KeepAliveFilter) OnPacketSent(s *netlib.Session, packetid int, logicNo uint32, data []byte) bool {
return true
}
func init() {
netlib.RegisterFactory(int(protocol.CoreBuiltinPacketID_PACKET_SS_KEEPALIVE), netlib.PacketFactoryWrapper(func() interface{} {
return &protocol.SSPacketKeepAlive{}
}))
netlib.RegisteSessionFilterCreator(KeepAliveFilterName, func() netlib.SessionFilter {
return &KeepAliveFilter{}
})
netlib.RegisterHandler(int(protocol.CoreBuiltinPacketID_PACKET_SS_KEEPALIVE), netlib.HandlerWrapper(func(s *netlib.Session, packetid int, data interface{}) error {
if p, ok := data.(*protocol.SSPacketKeepAlive); ok {
if p.GetFlag() == 0 {
p.Flag = 1
s.Send(int(protocol.CoreBuiltinPacketID_PACKET_SS_KEEPALIVE), p)
}
}
return nil
}))
}

View File

@ -0,0 +1,43 @@
package filter
import (
"golang.org/x/time/rate"
"mongo.games.com/goserver/core/netlib"
)
var (
LimiterFilterName = "session-filter-limiter"
SessionAttributeLimiter = &LimiterFilter{}
)
type LimiterFilter struct {
netlib.BasicSessionFilter
}
func (lf *LimiterFilter) GetName() string {
return LimiterFilterName
}
func (lf *LimiterFilter) GetInterestOps() uint {
return 1 << netlib.InterestOps_Received
}
func (lf *LimiterFilter) OnPacketReceived(s *netlib.Session, packetid int, logicNo uint32, packet interface{}) bool {
attr := s.GetAttribute(SessionAttributeLimiter)
if attr != nil {
if pool, ok := attr.(map[int]*rate.Limiter); ok && pool != nil {
if limiter, exist := pool[packetid]; exist && limiter != nil {
if !limiter.Allow() {
return false
}
}
}
}
return true
}
func init() {
netlib.RegisteSessionFilterCreator(LimiterFilterName, func() netlib.SessionFilter {
return &LimiterFilter{}
})
}

View File

@ -0,0 +1,94 @@
// sessionfiltertrace
package filter
import (
//"reflect"
"sync"
"time"
//"mongo.games.com/goserver/core/logger"
"mongo.games.com/goserver/core/netlib"
)
var (
SessionFilterTraceName = "session-filter-trace"
)
type SessionFilterTrace struct {
sync.Mutex
recvCntPerSec int
maxRecvPerSec int
recvTime time.Time
sendCntPerSec int
maxSendPerSec int
sendTime time.Time
dumpTime time.Time
}
func (sft SessionFilterTrace) GetName() string {
return SessionFilterTraceName
}
func (sft *SessionFilterTrace) GetInterestOps() uint {
return 1<<netlib.InterestOps_Max - 1
}
func (sft *SessionFilterTrace) OnSessionOpened(s *netlib.Session) bool {
//logger.Logger.Tracef("SessionFilterTrace.OnSessionOpened sid=%v", s.Id)
return true
}
func (sft *SessionFilterTrace) OnSessionClosed(s *netlib.Session) bool {
//logger.Logger.Tracef("SessionFilterTrace.OnSessionClosed sid=%v", s.Id)
return true
}
func (sft *SessionFilterTrace) OnSessionIdle(s *netlib.Session) bool {
//logger.Logger.Tracef("SessionFilterTrace.OnSessionIdle sid=%v", s.Id)
return true
}
func (sft *SessionFilterTrace) OnPacketReceived(s *netlib.Session, packetid int, logicNo uint32, packet interface{}) bool {
//logger.Logger.Tracef("SessionFilterTrace.OnPacketReceived sid=%v packetid=%v logicNo:%v packet=%v", s.Id, packetid, logicNo, reflect.TypeOf(packet))
sft.Lock()
sft.recvCntPerSec++
if time.Now().Sub(sft.recvTime) > time.Second {
if sft.recvCntPerSec > sft.maxRecvPerSec {
sft.maxRecvPerSec = sft.recvCntPerSec
sft.recvCntPerSec = 0
sft.recvTime = time.Now()
}
}
sft.dump()
sft.Unlock()
return true
}
func (sft *SessionFilterTrace) OnPacketSent(s *netlib.Session, packetid int, logicNo uint32, data []byte) bool {
//logger.Logger.Tracef("SessionFilterTrace.OnPacketSent sid=%v packetid:%v logicNo:%v size=%d", s.Id, packetid, logicNo, len(data))
sft.Lock()
sft.sendCntPerSec++
if time.Now().Sub(sft.sendTime) > time.Second {
if sft.sendCntPerSec > sft.maxSendPerSec {
sft.maxSendPerSec = sft.sendCntPerSec
sft.sendCntPerSec = 0
sft.sendTime = time.Now()
}
}
sft.dump()
sft.Unlock()
return true
}
func (sft *SessionFilterTrace) dump() {
if time.Now().Sub(sft.dumpTime) >= time.Minute*5 {
//logger.Logger.Info("Session per five minuts: recvCntPerSec=", sft.recvCntPerSec, " sendCntPerSec=", sft.sendCntPerSec)
sft.dumpTime = time.Now()
}
}
func init() {
netlib.RegisteSessionFilterCreator(SessionFilterTraceName, func() netlib.SessionFilter {
tNow := time.Now()
return &SessionFilterTrace{dumpTime: tNow, recvTime: tNow, sendTime: tNow}
})
}

13
core/builtin/gen_go.bat Normal file
View File

@ -0,0 +1,13 @@
@echo off
set work_path=%cd%
set proto_path=%cd%\protocol
set protoc3=%cd%\..\..\bin\protoc-3.5.1-win32\bin\protoc.exe
set protoc-gen-go-plugin-path="%cd%\..\..\bin\protoc-gen-go.exe"
cd %proto_path%
for %%b in (,*.proto) do (
echo %%b
%protoc3% --plugin=protoc-gen-go=%protoc-gen-go-plugin-path% --go_out=. %%b
)
cd ..
pause

View File

@ -0,0 +1,170 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.25.0-devel
// protoc v3.5.1
// source: corepacketid.proto
package protocol
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type CoreBuiltinPacketID int32
const (
CoreBuiltinPacketID_PACKET_COREBUILTIN_UNKNOW CoreBuiltinPacketID = 0
CoreBuiltinPacketID_PACKET_SS_TX_START CoreBuiltinPacketID = -1000
CoreBuiltinPacketID_PACKET_SS_TX_CMD CoreBuiltinPacketID = -1001
CoreBuiltinPacketID_PACKET_SS_TX_RESULT CoreBuiltinPacketID = -1002
CoreBuiltinPacketID_PACKET_SS_SLICES CoreBuiltinPacketID = -1003
CoreBuiltinPacketID_PACKET_SS_AUTH CoreBuiltinPacketID = -1004
CoreBuiltinPacketID_PACKET_SS_KEEPALIVE CoreBuiltinPacketID = -1005
CoreBuiltinPacketID_PACKET_SS_AUTH_ACK CoreBuiltinPacketID = -1006
CoreBuiltinPacketID_PACKET_SS_RPC_REQ CoreBuiltinPacketID = -1007
CoreBuiltinPacketID_PACKET_SS_RPC_RESP CoreBuiltinPacketID = -1008
)
// Enum value maps for CoreBuiltinPacketID.
var (
CoreBuiltinPacketID_name = map[int32]string{
0: "PACKET_COREBUILTIN_UNKNOW",
-1000: "PACKET_SS_TX_START",
-1001: "PACKET_SS_TX_CMD",
-1002: "PACKET_SS_TX_RESULT",
-1003: "PACKET_SS_SLICES",
-1004: "PACKET_SS_AUTH",
-1005: "PACKET_SS_KEEPALIVE",
-1006: "PACKET_SS_AUTH_ACK",
-1007: "PACKET_SS_RPC_REQ",
-1008: "PACKET_SS_RPC_RESP",
}
CoreBuiltinPacketID_value = map[string]int32{
"PACKET_COREBUILTIN_UNKNOW": 0,
"PACKET_SS_TX_START": -1000,
"PACKET_SS_TX_CMD": -1001,
"PACKET_SS_TX_RESULT": -1002,
"PACKET_SS_SLICES": -1003,
"PACKET_SS_AUTH": -1004,
"PACKET_SS_KEEPALIVE": -1005,
"PACKET_SS_AUTH_ACK": -1006,
"PACKET_SS_RPC_REQ": -1007,
"PACKET_SS_RPC_RESP": -1008,
}
)
func (x CoreBuiltinPacketID) Enum() *CoreBuiltinPacketID {
p := new(CoreBuiltinPacketID)
*p = x
return p
}
func (x CoreBuiltinPacketID) String() string {
return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
}
func (CoreBuiltinPacketID) Descriptor() protoreflect.EnumDescriptor {
return file_corepacketid_proto_enumTypes[0].Descriptor()
}
func (CoreBuiltinPacketID) Type() protoreflect.EnumType {
return &file_corepacketid_proto_enumTypes[0]
}
func (x CoreBuiltinPacketID) Number() protoreflect.EnumNumber {
return protoreflect.EnumNumber(x)
}
// Deprecated: Use CoreBuiltinPacketID.Descriptor instead.
func (CoreBuiltinPacketID) EnumDescriptor() ([]byte, []int) {
return file_corepacketid_proto_rawDescGZIP(), []int{0}
}
var File_corepacketid_proto protoreflect.FileDescriptor
var file_corepacketid_proto_rawDesc = []byte{
0x0a, 0x12, 0x63, 0x6f, 0x72, 0x65, 0x70, 0x61, 0x63, 0x6b, 0x65, 0x74, 0x69, 0x64, 0x2e, 0x70,
0x72, 0x6f, 0x74, 0x6f, 0x12, 0x08, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2a, 0xd6,
0x02, 0x0a, 0x13, 0x43, 0x6f, 0x72, 0x65, 0x42, 0x75, 0x69, 0x6c, 0x74, 0x69, 0x6e, 0x50, 0x61,
0x63, 0x6b, 0x65, 0x74, 0x49, 0x44, 0x12, 0x1d, 0x0a, 0x19, 0x50, 0x41, 0x43, 0x4b, 0x45, 0x54,
0x5f, 0x43, 0x4f, 0x52, 0x45, 0x42, 0x55, 0x49, 0x4c, 0x54, 0x49, 0x4e, 0x5f, 0x55, 0x4e, 0x4b,
0x4e, 0x4f, 0x57, 0x10, 0x00, 0x12, 0x1f, 0x0a, 0x12, 0x50, 0x41, 0x43, 0x4b, 0x45, 0x54, 0x5f,
0x53, 0x53, 0x5f, 0x54, 0x58, 0x5f, 0x53, 0x54, 0x41, 0x52, 0x54, 0x10, 0x98, 0xf8, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x12, 0x1d, 0x0a, 0x10, 0x50, 0x41, 0x43, 0x4b, 0x45, 0x54,
0x5f, 0x53, 0x53, 0x5f, 0x54, 0x58, 0x5f, 0x43, 0x4d, 0x44, 0x10, 0x97, 0xf8, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0x01, 0x12, 0x20, 0x0a, 0x13, 0x50, 0x41, 0x43, 0x4b, 0x45, 0x54, 0x5f,
0x53, 0x53, 0x5f, 0x54, 0x58, 0x5f, 0x52, 0x45, 0x53, 0x55, 0x4c, 0x54, 0x10, 0x96, 0xf8, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x12, 0x1d, 0x0a, 0x10, 0x50, 0x41, 0x43, 0x4b, 0x45,
0x54, 0x5f, 0x53, 0x53, 0x5f, 0x53, 0x4c, 0x49, 0x43, 0x45, 0x53, 0x10, 0x95, 0xf8, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x12, 0x1b, 0x0a, 0x0e, 0x50, 0x41, 0x43, 0x4b, 0x45, 0x54,
0x5f, 0x53, 0x53, 0x5f, 0x41, 0x55, 0x54, 0x48, 0x10, 0x94, 0xf8, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0x01, 0x12, 0x20, 0x0a, 0x13, 0x50, 0x41, 0x43, 0x4b, 0x45, 0x54, 0x5f, 0x53, 0x53,
0x5f, 0x4b, 0x45, 0x45, 0x50, 0x41, 0x4c, 0x49, 0x56, 0x45, 0x10, 0x93, 0xf8, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0x01, 0x12, 0x1f, 0x0a, 0x12, 0x50, 0x41, 0x43, 0x4b, 0x45, 0x54, 0x5f,
0x53, 0x53, 0x5f, 0x41, 0x55, 0x54, 0x48, 0x5f, 0x41, 0x43, 0x4b, 0x10, 0x92, 0xf8, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x12, 0x1e, 0x0a, 0x11, 0x50, 0x41, 0x43, 0x4b, 0x45, 0x54,
0x5f, 0x53, 0x53, 0x5f, 0x52, 0x50, 0x43, 0x5f, 0x52, 0x45, 0x51, 0x10, 0x91, 0xf8, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x12, 0x1f, 0x0a, 0x12, 0x50, 0x41, 0x43, 0x4b, 0x45, 0x54,
0x5f, 0x53, 0x53, 0x5f, 0x52, 0x50, 0x43, 0x5f, 0x52, 0x45, 0x53, 0x50, 0x10, 0x90, 0xf8, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x42, 0x0c, 0x5a, 0x0a, 0x2e, 0x3b, 0x70, 0x72, 0x6f,
0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
file_corepacketid_proto_rawDescOnce sync.Once
file_corepacketid_proto_rawDescData = file_corepacketid_proto_rawDesc
)
func file_corepacketid_proto_rawDescGZIP() []byte {
file_corepacketid_proto_rawDescOnce.Do(func() {
file_corepacketid_proto_rawDescData = protoimpl.X.CompressGZIP(file_corepacketid_proto_rawDescData)
})
return file_corepacketid_proto_rawDescData
}
var file_corepacketid_proto_enumTypes = make([]protoimpl.EnumInfo, 1)
var file_corepacketid_proto_goTypes = []interface{}{
(CoreBuiltinPacketID)(0), // 0: protocol.CoreBuiltinPacketID
}
var file_corepacketid_proto_depIdxs = []int32{
0, // [0:0] is the sub-list for method output_type
0, // [0:0] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_corepacketid_proto_init() }
func file_corepacketid_proto_init() {
if File_corepacketid_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_corepacketid_proto_rawDesc,
NumEnums: 1,
NumMessages: 0,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_corepacketid_proto_goTypes,
DependencyIndexes: file_corepacketid_proto_depIdxs,
EnumInfos: file_corepacketid_proto_enumTypes,
}.Build()
File_corepacketid_proto = out.File
file_corepacketid_proto_rawDesc = nil
file_corepacketid_proto_goTypes = nil
file_corepacketid_proto_depIdxs = nil
}

View File

@ -0,0 +1,16 @@
syntax = "proto3";
package protocol;
option go_package = ".;protocol";
enum CoreBuiltinPacketID {
PACKET_COREBUILTIN_UNKNOW = 0;
PACKET_SS_TX_START = -1000;
PACKET_SS_TX_CMD = -1001;
PACKET_SS_TX_RESULT = -1002;
PACKET_SS_SLICES = -1003;
PACKET_SS_AUTH = -1004;
PACKET_SS_KEEPALIVE = -1005;
PACKET_SS_AUTH_ACK = -1006;
PACKET_SS_RPC_REQ = -1007;
PACKET_SS_RPC_RESP = -1008;
}

View File

@ -0,0 +1,253 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.25.0-devel
// protoc v3.5.1
// source: goserver_rpc.proto
package protocol
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type RpcRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
ServiceMethod string `protobuf:"bytes,1,opt,name=ServiceMethod,proto3" json:"ServiceMethod,omitempty"`
Seq uint64 `protobuf:"varint,2,opt,name=Seq,proto3" json:"Seq,omitempty"`
Args []byte `protobuf:"bytes,3,opt,name=Args,proto3" json:"Args,omitempty"`
}
func (x *RpcRequest) Reset() {
*x = RpcRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_goserver_rpc_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *RpcRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*RpcRequest) ProtoMessage() {}
func (x *RpcRequest) ProtoReflect() protoreflect.Message {
mi := &file_goserver_rpc_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use RpcRequest.ProtoReflect.Descriptor instead.
func (*RpcRequest) Descriptor() ([]byte, []int) {
return file_goserver_rpc_proto_rawDescGZIP(), []int{0}
}
func (x *RpcRequest) GetServiceMethod() string {
if x != nil {
return x.ServiceMethod
}
return ""
}
func (x *RpcRequest) GetSeq() uint64 {
if x != nil {
return x.Seq
}
return 0
}
func (x *RpcRequest) GetArgs() []byte {
if x != nil {
return x.Args
}
return nil
}
type RpcResponse struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
ServiceMethod string `protobuf:"bytes,1,opt,name=ServiceMethod,proto3" json:"ServiceMethod,omitempty"`
Seq uint64 `protobuf:"varint,2,opt,name=Seq,proto3" json:"Seq,omitempty"`
Error string `protobuf:"bytes,3,opt,name=Error,proto3" json:"Error,omitempty"`
Reply []byte `protobuf:"bytes,4,opt,name=Reply,proto3" json:"Reply,omitempty"`
}
func (x *RpcResponse) Reset() {
*x = RpcResponse{}
if protoimpl.UnsafeEnabled {
mi := &file_goserver_rpc_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *RpcResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*RpcResponse) ProtoMessage() {}
func (x *RpcResponse) ProtoReflect() protoreflect.Message {
mi := &file_goserver_rpc_proto_msgTypes[1]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use RpcResponse.ProtoReflect.Descriptor instead.
func (*RpcResponse) Descriptor() ([]byte, []int) {
return file_goserver_rpc_proto_rawDescGZIP(), []int{1}
}
func (x *RpcResponse) GetServiceMethod() string {
if x != nil {
return x.ServiceMethod
}
return ""
}
func (x *RpcResponse) GetSeq() uint64 {
if x != nil {
return x.Seq
}
return 0
}
func (x *RpcResponse) GetError() string {
if x != nil {
return x.Error
}
return ""
}
func (x *RpcResponse) GetReply() []byte {
if x != nil {
return x.Reply
}
return nil
}
var File_goserver_rpc_proto protoreflect.FileDescriptor
var file_goserver_rpc_proto_rawDesc = []byte{
0x0a, 0x12, 0x67, 0x6f, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x5f, 0x72, 0x70, 0x63, 0x2e, 0x70,
0x72, 0x6f, 0x74, 0x6f, 0x12, 0x08, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x22, 0x58,
0x0a, 0x0a, 0x52, 0x70, 0x63, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x24, 0x0a, 0x0d,
0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x4d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x18, 0x01, 0x20,
0x01, 0x28, 0x09, 0x52, 0x0d, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x4d, 0x65, 0x74, 0x68,
0x6f, 0x64, 0x12, 0x10, 0x0a, 0x03, 0x53, 0x65, 0x71, 0x18, 0x02, 0x20, 0x01, 0x28, 0x04, 0x52,
0x03, 0x53, 0x65, 0x71, 0x12, 0x12, 0x0a, 0x04, 0x41, 0x72, 0x67, 0x73, 0x18, 0x03, 0x20, 0x01,
0x28, 0x0c, 0x52, 0x04, 0x41, 0x72, 0x67, 0x73, 0x22, 0x71, 0x0a, 0x0b, 0x52, 0x70, 0x63, 0x52,
0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x24, 0x0a, 0x0d, 0x53, 0x65, 0x72, 0x76, 0x69,
0x63, 0x65, 0x4d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0d,
0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x4d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x12, 0x10, 0x0a,
0x03, 0x53, 0x65, 0x71, 0x18, 0x02, 0x20, 0x01, 0x28, 0x04, 0x52, 0x03, 0x53, 0x65, 0x71, 0x12,
0x14, 0x0a, 0x05, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05,
0x45, 0x72, 0x72, 0x6f, 0x72, 0x12, 0x14, 0x0a, 0x05, 0x52, 0x65, 0x70, 0x6c, 0x79, 0x18, 0x04,
0x20, 0x01, 0x28, 0x0c, 0x52, 0x05, 0x52, 0x65, 0x70, 0x6c, 0x79, 0x42, 0x0c, 0x5a, 0x0a, 0x2e,
0x3b, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f,
0x33,
}
var (
file_goserver_rpc_proto_rawDescOnce sync.Once
file_goserver_rpc_proto_rawDescData = file_goserver_rpc_proto_rawDesc
)
func file_goserver_rpc_proto_rawDescGZIP() []byte {
file_goserver_rpc_proto_rawDescOnce.Do(func() {
file_goserver_rpc_proto_rawDescData = protoimpl.X.CompressGZIP(file_goserver_rpc_proto_rawDescData)
})
return file_goserver_rpc_proto_rawDescData
}
var file_goserver_rpc_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_goserver_rpc_proto_goTypes = []interface{}{
(*RpcRequest)(nil), // 0: protocol.RpcRequest
(*RpcResponse)(nil), // 1: protocol.RpcResponse
}
var file_goserver_rpc_proto_depIdxs = []int32{
0, // [0:0] is the sub-list for method output_type
0, // [0:0] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_goserver_rpc_proto_init() }
func file_goserver_rpc_proto_init() {
if File_goserver_rpc_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_goserver_rpc_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*RpcRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_goserver_rpc_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*RpcResponse); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_goserver_rpc_proto_rawDesc,
NumEnums: 0,
NumMessages: 2,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_goserver_rpc_proto_goTypes,
DependencyIndexes: file_goserver_rpc_proto_depIdxs,
MessageInfos: file_goserver_rpc_proto_msgTypes,
}.Build()
File_goserver_rpc_proto = out.File
file_goserver_rpc_proto_rawDesc = nil
file_goserver_rpc_proto_goTypes = nil
file_goserver_rpc_proto_depIdxs = nil
}

View File

@ -0,0 +1,16 @@
syntax = "proto3";
package protocol;
option go_package = ".;protocol";
message RpcRequest {
string ServiceMethod = 1;
uint64 Seq = 2;
bytes Args = 3;
}
message RpcResponse {
string ServiceMethod = 1;
uint64 Seq = 2;
string Error = 3;
bytes Reply = 4;
}

View File

@ -0,0 +1,142 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.25.0-devel
// protoc v3.5.1
// source: keepalive.proto
package protocol
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type SSPacketKeepAlive struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Flag int32 `protobuf:"varint,1,opt,name=Flag,proto3" json:"Flag,omitempty"`
}
func (x *SSPacketKeepAlive) Reset() {
*x = SSPacketKeepAlive{}
if protoimpl.UnsafeEnabled {
mi := &file_keepalive_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *SSPacketKeepAlive) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*SSPacketKeepAlive) ProtoMessage() {}
func (x *SSPacketKeepAlive) ProtoReflect() protoreflect.Message {
mi := &file_keepalive_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use SSPacketKeepAlive.ProtoReflect.Descriptor instead.
func (*SSPacketKeepAlive) Descriptor() ([]byte, []int) {
return file_keepalive_proto_rawDescGZIP(), []int{0}
}
func (x *SSPacketKeepAlive) GetFlag() int32 {
if x != nil {
return x.Flag
}
return 0
}
var File_keepalive_proto protoreflect.FileDescriptor
var file_keepalive_proto_rawDesc = []byte{
0x0a, 0x0f, 0x6b, 0x65, 0x65, 0x70, 0x61, 0x6c, 0x69, 0x76, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74,
0x6f, 0x12, 0x08, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x22, 0x27, 0x0a, 0x11, 0x53,
0x53, 0x50, 0x61, 0x63, 0x6b, 0x65, 0x74, 0x4b, 0x65, 0x65, 0x70, 0x41, 0x6c, 0x69, 0x76, 0x65,
0x12, 0x12, 0x0a, 0x04, 0x46, 0x6c, 0x61, 0x67, 0x18, 0x01, 0x20, 0x01, 0x28, 0x05, 0x52, 0x04,
0x46, 0x6c, 0x61, 0x67, 0x42, 0x0c, 0x5a, 0x0a, 0x2e, 0x3b, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63,
0x6f, 0x6c, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
file_keepalive_proto_rawDescOnce sync.Once
file_keepalive_proto_rawDescData = file_keepalive_proto_rawDesc
)
func file_keepalive_proto_rawDescGZIP() []byte {
file_keepalive_proto_rawDescOnce.Do(func() {
file_keepalive_proto_rawDescData = protoimpl.X.CompressGZIP(file_keepalive_proto_rawDescData)
})
return file_keepalive_proto_rawDescData
}
var file_keepalive_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
var file_keepalive_proto_goTypes = []interface{}{
(*SSPacketKeepAlive)(nil), // 0: protocol.SSPacketKeepAlive
}
var file_keepalive_proto_depIdxs = []int32{
0, // [0:0] is the sub-list for method output_type
0, // [0:0] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_keepalive_proto_init() }
func file_keepalive_proto_init() {
if File_keepalive_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_keepalive_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*SSPacketKeepAlive); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_keepalive_proto_rawDesc,
NumEnums: 0,
NumMessages: 1,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_keepalive_proto_goTypes,
DependencyIndexes: file_keepalive_proto_depIdxs,
MessageInfos: file_keepalive_proto_msgTypes,
}.Build()
File_keepalive_proto = out.File
file_keepalive_proto_rawDesc = nil
file_keepalive_proto_goTypes = nil
file_keepalive_proto_depIdxs = nil
}

View File

@ -0,0 +1,7 @@
syntax = "proto3";
package protocol;
option go_package = ".;protocol";
message SSPacketKeepAlive {
int32 Flag = 1;
}

View File

@ -0,0 +1,214 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.25.0-devel
// protoc v3.5.1
// source: sessionauth.proto
package protocol
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type SSPacketAuth struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
AuthKey string `protobuf:"bytes,1,opt,name=AuthKey,proto3" json:"AuthKey,omitempty"`
Timestamp int64 `protobuf:"varint,2,opt,name=Timestamp,proto3" json:"Timestamp,omitempty"`
}
func (x *SSPacketAuth) Reset() {
*x = SSPacketAuth{}
if protoimpl.UnsafeEnabled {
mi := &file_sessionauth_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *SSPacketAuth) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*SSPacketAuth) ProtoMessage() {}
func (x *SSPacketAuth) ProtoReflect() protoreflect.Message {
mi := &file_sessionauth_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use SSPacketAuth.ProtoReflect.Descriptor instead.
func (*SSPacketAuth) Descriptor() ([]byte, []int) {
return file_sessionauth_proto_rawDescGZIP(), []int{0}
}
func (x *SSPacketAuth) GetAuthKey() string {
if x != nil {
return x.AuthKey
}
return ""
}
func (x *SSPacketAuth) GetTimestamp() int64 {
if x != nil {
return x.Timestamp
}
return 0
}
type SSPacketAuthAck struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Msg string `protobuf:"bytes,1,opt,name=Msg,proto3" json:"Msg,omitempty"`
}
func (x *SSPacketAuthAck) Reset() {
*x = SSPacketAuthAck{}
if protoimpl.UnsafeEnabled {
mi := &file_sessionauth_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *SSPacketAuthAck) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*SSPacketAuthAck) ProtoMessage() {}
func (x *SSPacketAuthAck) ProtoReflect() protoreflect.Message {
mi := &file_sessionauth_proto_msgTypes[1]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use SSPacketAuthAck.ProtoReflect.Descriptor instead.
func (*SSPacketAuthAck) Descriptor() ([]byte, []int) {
return file_sessionauth_proto_rawDescGZIP(), []int{1}
}
func (x *SSPacketAuthAck) GetMsg() string {
if x != nil {
return x.Msg
}
return ""
}
var File_sessionauth_proto protoreflect.FileDescriptor
var file_sessionauth_proto_rawDesc = []byte{
0x0a, 0x11, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x61, 0x75, 0x74, 0x68, 0x2e, 0x70, 0x72,
0x6f, 0x74, 0x6f, 0x12, 0x08, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x22, 0x46, 0x0a,
0x0c, 0x53, 0x53, 0x50, 0x61, 0x63, 0x6b, 0x65, 0x74, 0x41, 0x75, 0x74, 0x68, 0x12, 0x18, 0x0a,
0x07, 0x41, 0x75, 0x74, 0x68, 0x4b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07,
0x41, 0x75, 0x74, 0x68, 0x4b, 0x65, 0x79, 0x12, 0x1c, 0x0a, 0x09, 0x54, 0x69, 0x6d, 0x65, 0x73,
0x74, 0x61, 0x6d, 0x70, 0x18, 0x02, 0x20, 0x01, 0x28, 0x03, 0x52, 0x09, 0x54, 0x69, 0x6d, 0x65,
0x73, 0x74, 0x61, 0x6d, 0x70, 0x22, 0x23, 0x0a, 0x0f, 0x53, 0x53, 0x50, 0x61, 0x63, 0x6b, 0x65,
0x74, 0x41, 0x75, 0x74, 0x68, 0x41, 0x63, 0x6b, 0x12, 0x10, 0x0a, 0x03, 0x4d, 0x73, 0x67, 0x18,
0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x4d, 0x73, 0x67, 0x42, 0x0c, 0x5a, 0x0a, 0x2e, 0x3b,
0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
file_sessionauth_proto_rawDescOnce sync.Once
file_sessionauth_proto_rawDescData = file_sessionauth_proto_rawDesc
)
func file_sessionauth_proto_rawDescGZIP() []byte {
file_sessionauth_proto_rawDescOnce.Do(func() {
file_sessionauth_proto_rawDescData = protoimpl.X.CompressGZIP(file_sessionauth_proto_rawDescData)
})
return file_sessionauth_proto_rawDescData
}
var file_sessionauth_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_sessionauth_proto_goTypes = []interface{}{
(*SSPacketAuth)(nil), // 0: protocol.SSPacketAuth
(*SSPacketAuthAck)(nil), // 1: protocol.SSPacketAuthAck
}
var file_sessionauth_proto_depIdxs = []int32{
0, // [0:0] is the sub-list for method output_type
0, // [0:0] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_sessionauth_proto_init() }
func file_sessionauth_proto_init() {
if File_sessionauth_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_sessionauth_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*SSPacketAuth); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_sessionauth_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*SSPacketAuthAck); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_sessionauth_proto_rawDesc,
NumEnums: 0,
NumMessages: 2,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_sessionauth_proto_goTypes,
DependencyIndexes: file_sessionauth_proto_depIdxs,
MessageInfos: file_sessionauth_proto_msgTypes,
}.Build()
File_sessionauth_proto = out.File
file_sessionauth_proto_rawDesc = nil
file_sessionauth_proto_goTypes = nil
file_sessionauth_proto_depIdxs = nil
}

View File

@ -0,0 +1,12 @@
syntax = "proto3";
package protocol;
option go_package = ".;protocol";
message SSPacketAuth {
string AuthKey = 1;
int64 Timestamp = 2;
}
message SSPacketAuthAck {
string Msg = 1;
}

View File

@ -0,0 +1,171 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.25.0-devel
// protoc v3.5.1
// source: slices.proto
package protocol
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type SSPacketSlices struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
SeqNo int32 `protobuf:"varint,1,opt,name=SeqNo,proto3" json:"SeqNo,omitempty"`
TotalSize int32 `protobuf:"varint,2,opt,name=TotalSize,proto3" json:"TotalSize,omitempty"`
Offset int32 `protobuf:"varint,3,opt,name=Offset,proto3" json:"Offset,omitempty"`
PacketData []byte `protobuf:"bytes,4,opt,name=PacketData,proto3" json:"PacketData,omitempty"`
}
func (x *SSPacketSlices) Reset() {
*x = SSPacketSlices{}
if protoimpl.UnsafeEnabled {
mi := &file_slices_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *SSPacketSlices) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*SSPacketSlices) ProtoMessage() {}
func (x *SSPacketSlices) ProtoReflect() protoreflect.Message {
mi := &file_slices_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use SSPacketSlices.ProtoReflect.Descriptor instead.
func (*SSPacketSlices) Descriptor() ([]byte, []int) {
return file_slices_proto_rawDescGZIP(), []int{0}
}
func (x *SSPacketSlices) GetSeqNo() int32 {
if x != nil {
return x.SeqNo
}
return 0
}
func (x *SSPacketSlices) GetTotalSize() int32 {
if x != nil {
return x.TotalSize
}
return 0
}
func (x *SSPacketSlices) GetOffset() int32 {
if x != nil {
return x.Offset
}
return 0
}
func (x *SSPacketSlices) GetPacketData() []byte {
if x != nil {
return x.PacketData
}
return nil
}
var File_slices_proto protoreflect.FileDescriptor
var file_slices_proto_rawDesc = []byte{
0x0a, 0x0c, 0x73, 0x6c, 0x69, 0x63, 0x65, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x08,
0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x22, 0x7c, 0x0a, 0x0e, 0x53, 0x53, 0x50, 0x61,
0x63, 0x6b, 0x65, 0x74, 0x53, 0x6c, 0x69, 0x63, 0x65, 0x73, 0x12, 0x14, 0x0a, 0x05, 0x53, 0x65,
0x71, 0x4e, 0x6f, 0x18, 0x01, 0x20, 0x01, 0x28, 0x05, 0x52, 0x05, 0x53, 0x65, 0x71, 0x4e, 0x6f,
0x12, 0x1c, 0x0a, 0x09, 0x54, 0x6f, 0x74, 0x61, 0x6c, 0x53, 0x69, 0x7a, 0x65, 0x18, 0x02, 0x20,
0x01, 0x28, 0x05, 0x52, 0x09, 0x54, 0x6f, 0x74, 0x61, 0x6c, 0x53, 0x69, 0x7a, 0x65, 0x12, 0x16,
0x0a, 0x06, 0x4f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x05, 0x52, 0x06,
0x4f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x12, 0x1e, 0x0a, 0x0a, 0x50, 0x61, 0x63, 0x6b, 0x65, 0x74,
0x44, 0x61, 0x74, 0x61, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0a, 0x50, 0x61, 0x63, 0x6b,
0x65, 0x74, 0x44, 0x61, 0x74, 0x61, 0x42, 0x0c, 0x5a, 0x0a, 0x2e, 0x3b, 0x70, 0x72, 0x6f, 0x74,
0x6f, 0x63, 0x6f, 0x6c, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
file_slices_proto_rawDescOnce sync.Once
file_slices_proto_rawDescData = file_slices_proto_rawDesc
)
func file_slices_proto_rawDescGZIP() []byte {
file_slices_proto_rawDescOnce.Do(func() {
file_slices_proto_rawDescData = protoimpl.X.CompressGZIP(file_slices_proto_rawDescData)
})
return file_slices_proto_rawDescData
}
var file_slices_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
var file_slices_proto_goTypes = []interface{}{
(*SSPacketSlices)(nil), // 0: protocol.SSPacketSlices
}
var file_slices_proto_depIdxs = []int32{
0, // [0:0] is the sub-list for method output_type
0, // [0:0] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_slices_proto_init() }
func file_slices_proto_init() {
if File_slices_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_slices_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*SSPacketSlices); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_slices_proto_rawDesc,
NumEnums: 0,
NumMessages: 1,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_slices_proto_goTypes,
DependencyIndexes: file_slices_proto_depIdxs,
MessageInfos: file_slices_proto_msgTypes,
}.Build()
File_slices_proto = out.File
file_slices_proto_rawDesc = nil
file_slices_proto_goTypes = nil
file_slices_proto_depIdxs = nil
}

View File

@ -0,0 +1,10 @@
syntax = "proto3";
package protocol;
option go_package = ".;protocol";
message SSPacketSlices {
int32 SeqNo = 1;
int32 TotalSize = 2;
int32 Offset = 3;
bytes PacketData = 4;
}

View File

@ -0,0 +1,482 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.25.0-devel
// protoc v3.5.1
// source: transact.proto
package protocol
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type TransactStart struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
MyTNP *TransactParam `protobuf:"bytes,1,opt,name=MyTNP,proto3" json:"MyTNP,omitempty"`
ParenTNP *TransactParam `protobuf:"bytes,2,opt,name=ParenTNP,proto3" json:"ParenTNP,omitempty"`
CustomData []byte `protobuf:"bytes,3,opt,name=CustomData,proto3" json:"CustomData,omitempty"`
}
func (x *TransactStart) Reset() {
*x = TransactStart{}
if protoimpl.UnsafeEnabled {
mi := &file_transact_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *TransactStart) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*TransactStart) ProtoMessage() {}
func (x *TransactStart) ProtoReflect() protoreflect.Message {
mi := &file_transact_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use TransactStart.ProtoReflect.Descriptor instead.
func (*TransactStart) Descriptor() ([]byte, []int) {
return file_transact_proto_rawDescGZIP(), []int{0}
}
func (x *TransactStart) GetMyTNP() *TransactParam {
if x != nil {
return x.MyTNP
}
return nil
}
func (x *TransactStart) GetParenTNP() *TransactParam {
if x != nil {
return x.ParenTNP
}
return nil
}
func (x *TransactStart) GetCustomData() []byte {
if x != nil {
return x.CustomData
}
return nil
}
type TransactCtrlCmd struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
TId int64 `protobuf:"varint,1,opt,name=TId,proto3" json:"TId,omitempty"`
Cmd int32 `protobuf:"varint,2,opt,name=Cmd,proto3" json:"Cmd,omitempty"`
}
func (x *TransactCtrlCmd) Reset() {
*x = TransactCtrlCmd{}
if protoimpl.UnsafeEnabled {
mi := &file_transact_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *TransactCtrlCmd) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*TransactCtrlCmd) ProtoMessage() {}
func (x *TransactCtrlCmd) ProtoReflect() protoreflect.Message {
mi := &file_transact_proto_msgTypes[1]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use TransactCtrlCmd.ProtoReflect.Descriptor instead.
func (*TransactCtrlCmd) Descriptor() ([]byte, []int) {
return file_transact_proto_rawDescGZIP(), []int{1}
}
func (x *TransactCtrlCmd) GetTId() int64 {
if x != nil {
return x.TId
}
return 0
}
func (x *TransactCtrlCmd) GetCmd() int32 {
if x != nil {
return x.Cmd
}
return 0
}
type TransactResult struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
MyTId int64 `protobuf:"varint,1,opt,name=MyTId,proto3" json:"MyTId,omitempty"`
ChildTId int64 `protobuf:"varint,2,opt,name=ChildTId,proto3" json:"ChildTId,omitempty"`
RetCode int32 `protobuf:"varint,3,opt,name=RetCode,proto3" json:"RetCode,omitempty"`
CustomData []byte `protobuf:"bytes,4,opt,name=CustomData,proto3" json:"CustomData,omitempty"`
}
func (x *TransactResult) Reset() {
*x = TransactResult{}
if protoimpl.UnsafeEnabled {
mi := &file_transact_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *TransactResult) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*TransactResult) ProtoMessage() {}
func (x *TransactResult) ProtoReflect() protoreflect.Message {
mi := &file_transact_proto_msgTypes[2]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use TransactResult.ProtoReflect.Descriptor instead.
func (*TransactResult) Descriptor() ([]byte, []int) {
return file_transact_proto_rawDescGZIP(), []int{2}
}
func (x *TransactResult) GetMyTId() int64 {
if x != nil {
return x.MyTId
}
return 0
}
func (x *TransactResult) GetChildTId() int64 {
if x != nil {
return x.ChildTId
}
return 0
}
func (x *TransactResult) GetRetCode() int32 {
if x != nil {
return x.RetCode
}
return 0
}
func (x *TransactResult) GetCustomData() []byte {
if x != nil {
return x.CustomData
}
return nil
}
type TransactParam struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
TransNodeID int64 `protobuf:"varint,1,opt,name=TransNodeID,proto3" json:"TransNodeID,omitempty"`
TransType int32 `protobuf:"varint,2,opt,name=TransType,proto3" json:"TransType,omitempty"`
OwnerType int32 `protobuf:"varint,3,opt,name=OwnerType,proto3" json:"OwnerType,omitempty"`
OwnerID int32 `protobuf:"varint,4,opt,name=OwnerID,proto3" json:"OwnerID,omitempty"`
SkeletonID int32 `protobuf:"varint,5,opt,name=SkeletonID,proto3" json:"SkeletonID,omitempty"`
LevelNo int32 `protobuf:"varint,6,opt,name=LevelNo,proto3" json:"LevelNo,omitempty"`
AreaID int32 `protobuf:"varint,7,opt,name=AreaID,proto3" json:"AreaID,omitempty"`
TimeOut int64 `protobuf:"varint,8,opt,name=TimeOut,proto3" json:"TimeOut,omitempty"`
TransCommitType int32 `protobuf:"varint,9,opt,name=TransCommitType,proto3" json:"TransCommitType,omitempty"`
ExpiresTs int64 `protobuf:"varint,10,opt,name=ExpiresTs,proto3" json:"ExpiresTs,omitempty"`
}
func (x *TransactParam) Reset() {
*x = TransactParam{}
if protoimpl.UnsafeEnabled {
mi := &file_transact_proto_msgTypes[3]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *TransactParam) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*TransactParam) ProtoMessage() {}
func (x *TransactParam) ProtoReflect() protoreflect.Message {
mi := &file_transact_proto_msgTypes[3]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use TransactParam.ProtoReflect.Descriptor instead.
func (*TransactParam) Descriptor() ([]byte, []int) {
return file_transact_proto_rawDescGZIP(), []int{3}
}
func (x *TransactParam) GetTransNodeID() int64 {
if x != nil {
return x.TransNodeID
}
return 0
}
func (x *TransactParam) GetTransType() int32 {
if x != nil {
return x.TransType
}
return 0
}
func (x *TransactParam) GetOwnerType() int32 {
if x != nil {
return x.OwnerType
}
return 0
}
func (x *TransactParam) GetOwnerID() int32 {
if x != nil {
return x.OwnerID
}
return 0
}
func (x *TransactParam) GetSkeletonID() int32 {
if x != nil {
return x.SkeletonID
}
return 0
}
func (x *TransactParam) GetLevelNo() int32 {
if x != nil {
return x.LevelNo
}
return 0
}
func (x *TransactParam) GetAreaID() int32 {
if x != nil {
return x.AreaID
}
return 0
}
func (x *TransactParam) GetTimeOut() int64 {
if x != nil {
return x.TimeOut
}
return 0
}
func (x *TransactParam) GetTransCommitType() int32 {
if x != nil {
return x.TransCommitType
}
return 0
}
func (x *TransactParam) GetExpiresTs() int64 {
if x != nil {
return x.ExpiresTs
}
return 0
}
var File_transact_proto protoreflect.FileDescriptor
var file_transact_proto_rawDesc = []byte{
0x0a, 0x0e, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f,
0x12, 0x08, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x22, 0x93, 0x01, 0x0a, 0x0d, 0x54,
0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x53, 0x74, 0x61, 0x72, 0x74, 0x12, 0x2d, 0x0a, 0x05,
0x4d, 0x79, 0x54, 0x4e, 0x50, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, 0x2e, 0x70, 0x72,
0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x50,
0x61, 0x72, 0x61, 0x6d, 0x52, 0x05, 0x4d, 0x79, 0x54, 0x4e, 0x50, 0x12, 0x33, 0x0a, 0x08, 0x50,
0x61, 0x72, 0x65, 0x6e, 0x54, 0x4e, 0x50, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, 0x2e,
0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63,
0x74, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x52, 0x08, 0x50, 0x61, 0x72, 0x65, 0x6e, 0x54, 0x4e, 0x50,
0x12, 0x1e, 0x0a, 0x0a, 0x43, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x44, 0x61, 0x74, 0x61, 0x18, 0x03,
0x20, 0x01, 0x28, 0x0c, 0x52, 0x0a, 0x43, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x44, 0x61, 0x74, 0x61,
0x22, 0x35, 0x0a, 0x0f, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x43, 0x74, 0x72, 0x6c,
0x43, 0x6d, 0x64, 0x12, 0x10, 0x0a, 0x03, 0x54, 0x49, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03,
0x52, 0x03, 0x54, 0x49, 0x64, 0x12, 0x10, 0x0a, 0x03, 0x43, 0x6d, 0x64, 0x18, 0x02, 0x20, 0x01,
0x28, 0x05, 0x52, 0x03, 0x43, 0x6d, 0x64, 0x22, 0x7c, 0x0a, 0x0e, 0x54, 0x72, 0x61, 0x6e, 0x73,
0x61, 0x63, 0x74, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x12, 0x14, 0x0a, 0x05, 0x4d, 0x79, 0x54,
0x49, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x05, 0x4d, 0x79, 0x54, 0x49, 0x64, 0x12,
0x1a, 0x0a, 0x08, 0x43, 0x68, 0x69, 0x6c, 0x64, 0x54, 0x49, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28,
0x03, 0x52, 0x08, 0x43, 0x68, 0x69, 0x6c, 0x64, 0x54, 0x49, 0x64, 0x12, 0x18, 0x0a, 0x07, 0x52,
0x65, 0x74, 0x43, 0x6f, 0x64, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x05, 0x52, 0x07, 0x52, 0x65,
0x74, 0x43, 0x6f, 0x64, 0x65, 0x12, 0x1e, 0x0a, 0x0a, 0x43, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x44,
0x61, 0x74, 0x61, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0a, 0x43, 0x75, 0x73, 0x74, 0x6f,
0x6d, 0x44, 0x61, 0x74, 0x61, 0x22, 0xbb, 0x02, 0x0a, 0x0d, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61,
0x63, 0x74, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x12, 0x20, 0x0a, 0x0b, 0x54, 0x72, 0x61, 0x6e, 0x73,
0x4e, 0x6f, 0x64, 0x65, 0x49, 0x44, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0b, 0x54, 0x72,
0x61, 0x6e, 0x73, 0x4e, 0x6f, 0x64, 0x65, 0x49, 0x44, 0x12, 0x1c, 0x0a, 0x09, 0x54, 0x72, 0x61,
0x6e, 0x73, 0x54, 0x79, 0x70, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x05, 0x52, 0x09, 0x54, 0x72,
0x61, 0x6e, 0x73, 0x54, 0x79, 0x70, 0x65, 0x12, 0x1c, 0x0a, 0x09, 0x4f, 0x77, 0x6e, 0x65, 0x72,
0x54, 0x79, 0x70, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x05, 0x52, 0x09, 0x4f, 0x77, 0x6e, 0x65,
0x72, 0x54, 0x79, 0x70, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x4f, 0x77, 0x6e, 0x65, 0x72, 0x49, 0x44,
0x18, 0x04, 0x20, 0x01, 0x28, 0x05, 0x52, 0x07, 0x4f, 0x77, 0x6e, 0x65, 0x72, 0x49, 0x44, 0x12,
0x1e, 0x0a, 0x0a, 0x53, 0x6b, 0x65, 0x6c, 0x65, 0x74, 0x6f, 0x6e, 0x49, 0x44, 0x18, 0x05, 0x20,
0x01, 0x28, 0x05, 0x52, 0x0a, 0x53, 0x6b, 0x65, 0x6c, 0x65, 0x74, 0x6f, 0x6e, 0x49, 0x44, 0x12,
0x18, 0x0a, 0x07, 0x4c, 0x65, 0x76, 0x65, 0x6c, 0x4e, 0x6f, 0x18, 0x06, 0x20, 0x01, 0x28, 0x05,
0x52, 0x07, 0x4c, 0x65, 0x76, 0x65, 0x6c, 0x4e, 0x6f, 0x12, 0x16, 0x0a, 0x06, 0x41, 0x72, 0x65,
0x61, 0x49, 0x44, 0x18, 0x07, 0x20, 0x01, 0x28, 0x05, 0x52, 0x06, 0x41, 0x72, 0x65, 0x61, 0x49,
0x44, 0x12, 0x18, 0x0a, 0x07, 0x54, 0x69, 0x6d, 0x65, 0x4f, 0x75, 0x74, 0x18, 0x08, 0x20, 0x01,
0x28, 0x03, 0x52, 0x07, 0x54, 0x69, 0x6d, 0x65, 0x4f, 0x75, 0x74, 0x12, 0x28, 0x0a, 0x0f, 0x54,
0x72, 0x61, 0x6e, 0x73, 0x43, 0x6f, 0x6d, 0x6d, 0x69, 0x74, 0x54, 0x79, 0x70, 0x65, 0x18, 0x09,
0x20, 0x01, 0x28, 0x05, 0x52, 0x0f, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x43, 0x6f, 0x6d, 0x6d, 0x69,
0x74, 0x54, 0x79, 0x70, 0x65, 0x12, 0x1c, 0x0a, 0x09, 0x45, 0x78, 0x70, 0x69, 0x72, 0x65, 0x73,
0x54, 0x73, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x03, 0x52, 0x09, 0x45, 0x78, 0x70, 0x69, 0x72, 0x65,
0x73, 0x54, 0x73, 0x42, 0x0c, 0x5a, 0x0a, 0x2e, 0x3b, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f,
0x6c, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
file_transact_proto_rawDescOnce sync.Once
file_transact_proto_rawDescData = file_transact_proto_rawDesc
)
func file_transact_proto_rawDescGZIP() []byte {
file_transact_proto_rawDescOnce.Do(func() {
file_transact_proto_rawDescData = protoimpl.X.CompressGZIP(file_transact_proto_rawDescData)
})
return file_transact_proto_rawDescData
}
var file_transact_proto_msgTypes = make([]protoimpl.MessageInfo, 4)
var file_transact_proto_goTypes = []interface{}{
(*TransactStart)(nil), // 0: protocol.TransactStart
(*TransactCtrlCmd)(nil), // 1: protocol.TransactCtrlCmd
(*TransactResult)(nil), // 2: protocol.TransactResult
(*TransactParam)(nil), // 3: protocol.TransactParam
}
var file_transact_proto_depIdxs = []int32{
3, // 0: protocol.TransactStart.MyTNP:type_name -> protocol.TransactParam
3, // 1: protocol.TransactStart.ParenTNP:type_name -> protocol.TransactParam
2, // [2:2] is the sub-list for method output_type
2, // [2:2] is the sub-list for method input_type
2, // [2:2] is the sub-list for extension type_name
2, // [2:2] is the sub-list for extension extendee
0, // [0:2] is the sub-list for field type_name
}
func init() { file_transact_proto_init() }
func file_transact_proto_init() {
if File_transact_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_transact_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*TransactStart); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_transact_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*TransactCtrlCmd); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_transact_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*TransactResult); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_transact_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*TransactParam); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_transact_proto_rawDesc,
NumEnums: 0,
NumMessages: 4,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_transact_proto_goTypes,
DependencyIndexes: file_transact_proto_depIdxs,
MessageInfos: file_transact_proto_msgTypes,
}.Build()
File_transact_proto = out.File
file_transact_proto_rawDesc = nil
file_transact_proto_goTypes = nil
file_transact_proto_depIdxs = nil
}

View File

@ -0,0 +1,34 @@
syntax = "proto3";
package protocol;
option go_package = ".;protocol";
message TransactStart {
TransactParam MyTNP = 1;
TransactParam ParenTNP = 2;
bytes CustomData = 3;
}
message TransactCtrlCmd {
int64 TId = 1;
int32 Cmd = 2;
}
message TransactResult {
int64 MyTId = 1;
int64 ChildTId = 2;
int32 RetCode = 3;
bytes CustomData = 4;
}
message TransactParam {
int64 TransNodeID = 1;
int32 TransType = 2;
int32 OwnerType = 3;
int32 OwnerID = 4;
int32 SkeletonID = 5;
int32 LevelNo = 6;
int32 AreaID = 7;
int64 TimeOut = 8;
int32 TransCommitType = 9;
int64 ExpiresTs = 10;
}

121
core/cmdline/cmdline.go Normal file
View File

@ -0,0 +1,121 @@
package cmdline
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
"time"
"mongo.games.com/goserver/core/module"
)
var cmdpool = make(map[string]cmdExecuter)
type cmdGoroutineWapper struct {
}
type CmdArg struct {
Flag string
SimplifyFlag string
Required bool
}
type CmdArgParser struct {
cmeKV map[string]string
}
type cmdExecuter interface {
Execute(args []string)
ShowUsage()
}
func NewCmdArgParser(args []string) *CmdArgParser {
parser := &CmdArgParser{
cmeKV: make(map[string]string),
}
for _, arg := range args {
kv := strings.Split(arg, "=")
if len(kv) == 2 {
k := kv[0]
v := kv[1]
parser.cmeKV[k] = v
}
}
return parser
}
func RegisteCmd(cmdName string, executer cmdExecuter) {
cmdpool[strings.ToLower(cmdName)] = executer
}
func (cw *cmdGoroutineWapper) Start() {
if Config.SupportCmdLine {
go func() {
var (
reader = bufio.NewReader(os.Stdin)
cmdLine []byte
isPrefix bool
err error
)
for {
cmdLine, isPrefix, err = reader.ReadLine()
if err == nil && isPrefix == false {
params := strings.Split(string(cmdLine), " ")
if len(params) >= 1 {
cmdName := strings.ToLower(params[0])
if cmdExecute, exist := cmdpool[cmdName]; exist {
PostCmd(module.AppModule.Object, cmdExecute, params[1:])
}
}
}
time.Sleep(time.Second)
}
}()
}
}
func (this *CmdArgParser) ExtraIntArg(arg *CmdArg, val *int) {
if v, exist := this.cmeKV[arg.SimplifyFlag]; !exist {
if v, exist := this.cmeKV[arg.Flag]; !exist && arg.Required {
fmt.Println(arg.Flag, "must be give")
return
} else {
*val, _ = strconv.Atoi(v)
}
} else {
*val, _ = strconv.Atoi(v)
}
}
func (this *CmdArgParser) ExtraInt64Arg(arg *CmdArg, val *int64) {
if v, exist := this.cmeKV[arg.SimplifyFlag]; !exist {
if v, exist := this.cmeKV[arg.Flag]; !exist && arg.Required {
fmt.Println(arg.Flag, "must be give")
return
} else {
*val, _ = strconv.ParseInt(v, 10, 64)
}
} else {
*val, _ = strconv.ParseInt(v, 10, 64)
}
}
func (this *CmdArgParser) ExtraStringArg(arg *CmdArg, val *string) {
if v, exist := this.cmeKV[arg.SimplifyFlag]; !exist {
if v, exist := this.cmeKV[arg.Flag]; !exist && arg.Required {
fmt.Println(arg.Flag, "must be give")
return
} else {
*val = v
}
} else {
*val = v
}
}
func init() {
//module.RegistePreloadModule(&cmdGoroutineWapper{}, 0)
}

View File

@ -0,0 +1,22 @@
package cmdline
import (
"fmt"
"mongo.games.com/goserver/core/module"
)
type exitExecuter struct {
}
func (this exitExecuter) Execute(args []string) {
module.Stop()
}
func (this exitExecuter) ShowUsage() {
fmt.Println("usage: exit")
}
func init() {
RegisteCmd("exit", &exitExecuter{})
}

View File

@ -0,0 +1,35 @@
package cmdline
import (
"fmt"
)
type helpExecuter struct {
}
func (this helpExecuter) Execute(args []string) {
if len(args) > 0 {
if cmde, exist := cmdpool[args[0]]; exist {
cmde.ShowUsage()
}
} else {
this.ShowUsage()
fmt.Println("The commands are:")
for k, _ := range cmdpool {
if k != "help" {
fmt.Println("\t", k)
}
}
fmt.Println("Use \"help [command]\" for more information about a command.")
}
}
func (this helpExecuter) ShowUsage() {
fmt.Println("Help is a help command like window or linux shell's command")
fmt.Println("Usage:")
fmt.Println("\t", "help command")
}
func init() {
RegisteCmd("help", &helpExecuter{})
}

View File

@ -0,0 +1,20 @@
package cmdline
import (
"mongo.games.com/goserver/core/basic"
)
type cmdlineCommand struct {
exec cmdExecuter
args []string
}
func (cmd *cmdlineCommand) Done(o *basic.Object) error {
defer o.ProcessSeqnum()
cmd.exec.Execute(cmd.args)
return nil
}
func PostCmd(p *basic.Object, exec cmdExecuter, args []string) bool {
return p.SendCommand(&cmdlineCommand{exec: exec, args: args}, true)
}

27
core/cmdline/config.go Normal file
View File

@ -0,0 +1,27 @@
package cmdline
import (
"mongo.games.com/goserver/core"
)
var Config = Configuration{}
type Configuration struct {
SupportCmdLine bool
}
func (c *Configuration) Name() string {
return "cmdline"
}
func (c *Configuration) Init() error {
return nil
}
func (c *Configuration) Close() error {
return nil
}
func init() {
core.RegistePackage(&Config)
}

32
core/config.go Normal file
View File

@ -0,0 +1,32 @@
package core
import (
"runtime"
)
var Config = Configuration{}
type Configuration struct {
MaxProcs int
Debug bool
}
func (c *Configuration) Name() string {
return "core"
}
func (c *Configuration) Init() error {
if c.MaxProcs <= 0 {
c.MaxProcs = 1
}
runtime.GOMAXPROCS(c.MaxProcs)
return nil
}
func (c *Configuration) Close() error {
return nil
}
func init() {
RegistePackage(&Config)
}

1
core/container/doc.go Normal file
View File

@ -0,0 +1 @@
package container

View File

@ -0,0 +1,12 @@
// queue
package queue
import (
"time"
)
type Queue interface {
Len() int
Enqueue(interface{}, time.Duration) bool
Dequeue(time.Duration) (interface{}, bool)
}

View File

@ -0,0 +1,51 @@
// queue
package queue
import "time"
type queueC struct {
c chan interface{}
}
func NewQueueC(backlog int) Queue {
return &queueC{
c: make(chan interface{}, backlog),
}
}
func (q *queueC) Enqueue(i interface{}, timeout time.Duration) bool {
if timeout > 0 {
timer := time.NewTimer(timeout)
select {
case q.c <- i:
case <-timer.C:
return false
}
} else {
q.c <- i
}
return true
}
func (q *queueC) Dequeue(timeout time.Duration) (i interface{}, ok bool) {
if timeout > 0 {
timer := time.NewTimer(timeout)
select {
case i, ok = <-q.c:
return i, ok
case <-timer.C:
return nil, false
}
} else {
select {
case i, ok = <-q.c:
return i, ok
}
}
return nil, false
}
func (q *queueC) Len() int {
return len(q.c)
}

View File

@ -0,0 +1,50 @@
package queue
import (
"container/list"
"sync"
"time"
)
type queueS struct {
fifo *list.List
lock *sync.RWMutex
}
func NewQueueS() Queue {
q := &queueS{
fifo: list.New(),
lock: new(sync.RWMutex),
}
return q
}
func (q *queueS) Enqueue(i interface{}, timeout time.Duration) bool {
q.lock.Lock()
q.fifo.PushBack(i)
q.lock.Unlock()
return true
}
func (q *queueS) Dequeue(timeout time.Duration) (interface{}, bool) {
if q.fifo.Len() == 0 {
return nil, false
}
q.lock.Lock()
e := q.fifo.Front()
if e != nil {
q.fifo.Remove(e)
q.lock.Unlock()
return e.Value, true
}
q.lock.Unlock()
return nil, false
}
func (q *queueS) Len() int {
q.lock.RLock()
l := q.fifo.Len()
q.lock.RUnlock()
return l
}

View File

@ -0,0 +1,85 @@
// queue_test
package queue
import (
"testing"
"time"
)
func TestSyncQueneEnqueue(t *testing.T) {
const CNT int = 10
q := NewQueueS()
for i := 0; i < CNT; i++ {
q.Enqueue(i, 0)
}
if q.Len() != CNT {
t.Error("sync queue Enqueue error")
}
}
func TestSyncQueneDequeue(t *testing.T) {
const CNT int = 10
q := NewQueueS()
for i := 0; i < CNT; i++ {
q.Enqueue(i, 0)
}
var (
b bool = true
d interface{}
cnt int
)
for b {
d, b = q.Dequeue(0)
if b {
cnt++
t.Log("Dequeue data:", d)
}
}
if cnt != CNT {
t.Error("sync queue Dequeue error")
}
}
func BenchmarkSyncQueneEnqueue(b *testing.B) {
q := NewQueueS()
b.StartTimer()
for i := 0; i < b.N; i++ {
q.Enqueue(i, 0)
}
b.StopTimer()
}
func BenchmarkSyncQueneDequeue(b *testing.B) {
q := NewQueueS()
for i := 0; i < b.N; i++ {
q.Enqueue(i, 0)
}
b.StartTimer()
for i := 0; i < b.N; i++ {
q.Dequeue(0)
}
b.StopTimer()
}
func BenchmarkChanQueneEnqueue(b *testing.B) {
q := NewQueueC(b.N)
b.StartTimer()
for i := 0; i < b.N; i++ {
q.Enqueue(i, time.Millisecond)
}
b.StopTimer()
}
func BenchmarkChanQueneDequeue(b *testing.B) {
q := NewQueueC(b.N)
for i := 0; i < b.N; i++ {
q.Enqueue(i, 0)
}
b.StartTimer()
for i := 0; i < b.N; i++ {
q.Dequeue(0)
}
b.StopTimer()
}

View File

@ -0,0 +1,87 @@
// recycler
package recycler
import (
"container/list"
"time"
)
var RecyclerBacklogDefault int = 5
type element struct {
when time.Time
data interface{}
}
type Recycler struct {
get chan interface{}
give chan interface{}
ocf func() interface{}
que *list.List
timeout *time.Timer
makecnt int
name string
running bool
}
func NewRecycler(backlog int, ocf func() interface{}, name string) *Recycler {
r := &Recycler{
get: make(chan interface{}, backlog),
give: make(chan interface{}, backlog),
ocf: ocf,
que: list.New(),
timeout: time.NewTimer(time.Minute),
name: name,
running: true,
}
go r.run()
return r
}
func (this *Recycler) run() {
RecyclerMgr.registe(this)
defer RecyclerMgr.unregiste(this)
for this.running {
if this.que.Len() == 0 {
this.que.PushFront(element{when: time.Now(), data: this.ocf()})
this.makecnt++
}
this.timeout.Reset(time.Minute)
e := this.que.Front()
select {
case d := <-this.give:
this.timeout.Stop()
this.que.PushFront(element{when: time.Now(), data: d})
case this.get <- e.Value.(element).data:
this.timeout.Stop()
this.que.Remove(e)
case <-this.timeout.C:
e := this.que.Front()
for e != nil {
n := e.Next()
if time.Since(e.Value.(element).when) > time.Minute {
this.que.Remove(e)
e.Value = nil
this.makecnt--
}
e = n
}
}
}
}
func (this *Recycler) Get() interface{} {
i := <-this.get
return i
}
func (this *Recycler) Give(i interface{}) {
this.give <- i
}
func (this *Recycler) Close() {
this.running = false
}

View File

@ -0,0 +1,28 @@
package recycler
import (
"bytes"
)
const (
BytebufRecyclerBacklog int = 128
)
var BytebufRecycler = NewRecycler(
BytebufRecyclerBacklog,
func() interface{} {
return bytes.NewBuffer(nil)
},
"bytebuf_recycler",
)
func AllocBytebuf() *bytes.Buffer {
b := BytebufRecycler.Get()
buf := b.(*bytes.Buffer)
buf.Reset()
return buf
}
func FreeBytebuf(buf *bytes.Buffer) {
BytebufRecycler.Give(buf)
}

View File

@ -0,0 +1,45 @@
package recycler
import (
"fmt"
"io"
"sync"
)
var RecyclerMgr = &recyclerMgr{
recyclers: make(map[interface{}]*Recycler),
lock: new(sync.Mutex),
}
type recyclerMgr struct {
recyclers map[interface{}]*Recycler
lock *sync.Mutex
}
func (this *recyclerMgr) registe(r *Recycler) {
this.lock.Lock()
this.recyclers[r] = r
this.lock.Unlock()
}
func (this *recyclerMgr) unregiste(r *Recycler) {
this.lock.Lock()
delete(this.recyclers, r)
this.lock.Unlock()
}
func (this *recyclerMgr) CloseAll() {
this.lock.Lock()
defer this.lock.Unlock()
for _, r := range this.recyclers {
r.Close()
}
}
func (this *recyclerMgr) Dump(w io.Writer) {
this.lock.Lock()
for _, r := range this.recyclers {
w.Write([]byte(fmt.Sprintf("(%s) alloc object (%d)", r.name, r.makecnt)))
}
this.lock.Unlock()
}

View File

@ -0,0 +1,30 @@
// recycler_test
package recycler
import (
"runtime"
"testing"
)
func makeBuffer() interface{} {
buf := make([]byte, 0, 1024)
return buf
}
var MyRecycler = NewRecycler(RecyclerBacklogDefault, makeBuffer, "test")
func TestGet(t *testing.T) {
MyRecycler.Get()
}
func TestGive(t *testing.T) {
MyRecycler.Give(nil)
}
func BenchmarkGet(b *testing.B) {
b.StartTimer()
for i := 0; i < b.N; i++ {
MyRecycler.Get()
}
b.StopTimer()
}

View File

@ -0,0 +1,29 @@
package recycler
import (
"time"
)
const (
NewTimerDefaultDuration time.Duration = time.Minute
TimerRecyclerBacklog int = 128
)
var TimerRecycler = NewRecycler(
TimerRecyclerBacklog,
func() interface{} {
return time.NewTimer(NewTimerDefaultDuration)
},
"timer_recycler",
)
func GetTimer(timeout time.Duration) *time.Timer {
t := TimerRecycler.Get()
timer := t.(*time.Timer)
timer.Reset(timeout)
return timer
}
func GiveTimer(t *time.Timer) {
TimerRecycler.Give(t)
}

View File

@ -0,0 +1,703 @@
// Package skiplist implements skip list based maps and sets.
//
// Skip lists are a data structure that can be used in place of
// balanced trees. Skip lists use probabilistic balancing rather than
// strictly enforced balancing and as a result the algorithms for
// insertion and deletion in skip lists are much simpler and
// significantly faster than equivalent algorithms for balanced trees.
//
// Skip lists were first described in Pugh, William (June 1990). "Skip
// lists: a probabilistic alternative to balanced
// trees". Communications of the ACM 33 (6): 668676
package skiplist
import (
"math/rand"
)
// p is the fraction of nodes with level i pointers that also have
// level i+1 pointers. p equal to 1/4 is a good value from the point
// of view of speed and space requirements. If variability of running
// times is a concern, 1/2 is a better value for p.
const p = 0.25
const DefaultMaxLevel = 32
// A node is a container for key-value pairs that are stored in a skip
// list.
type node struct {
forward []*node
span []int
backward *node
key, value interface{}
}
// next returns the next node in the skip list containing n.
func (n *node) next() *node {
if len(n.forward) == 0 {
return nil
}
return n.forward[0]
}
// previous returns the previous node in the skip list containing n.
func (n *node) previous() *node {
return n.backward
}
// hasNext returns true if n has a next node.
func (n *node) hasNext() bool {
return n.next() != nil
}
// hasPrevious returns true if n has a previous node.
func (n *node) hasPrevious() bool {
return n.previous() != nil
}
// A SkipList is a map-like data structure that maintains an ordered
// collection of key-value pairs. Insertion, lookup, and deletion are
// all O(log n) operations. A SkipList can efficiently store up to
// 2^MaxLevel items.
//
// To iterate over a skip list (where s is a
// *SkipList):
//
// for i := s.Iterator(); i.Next(); {
// // do something with i.Key() and i.Value()
// }
type SkipList struct {
lessThan func(l, r interface{}) bool
header *node
footer *node
length int
// MaxLevel determines how many items the SkipList can store
// efficiently (2^MaxLevel).
//
// It is safe to increase MaxLevel to accomodate more
// elements. If you decrease MaxLevel and the skip list
// already contains nodes on higer levels, the effective
// MaxLevel will be the greater of the new MaxLevel and the
// level of the highest node.
//
// A SkipList with MaxLevel equal to 0 is equivalent to a
// standard linked list and will not have any of the nice
// properties of skip lists (probably not what you want).
MaxLevel int
}
// Len returns the length of s.
func (s *SkipList) Len() int {
return s.length
}
// Iterator is an interface that you can use to iterate through the
// skip list (in its entirety or fragments). For an use example, see
// the documentation of SkipList.
//
// Key and Value return the key and the value of the current node.
type Iterator interface {
// Next returns true if the iterator contains subsequent elements
// and advances its state to the next element if that is possible.
Next() (ok bool)
// Previous returns true if the iterator contains previous elements
// and rewinds its state to the previous element if that is possible.
Previous() (ok bool)
// Key returns the current key.
Key() interface{}
// Value returns the current value.
Value() interface{}
// Seek reduces iterative seek costs for searching forward into the Skip List
// by remarking the range of keys over which it has scanned before. If the
// requested key occurs prior to the point, the Skip List will start searching
// as a safeguard. It returns true if the key is within the known range of
// the list.
Seek(key interface{}) (ok bool)
// Close this iterator to reap resources associated with it. While not
// strictly required, it will provide extra hints for the garbage collector.
Close()
}
type iter struct {
current *node
key interface{}
list *SkipList
value interface{}
}
func (i iter) Key() interface{} {
return i.key
}
func (i iter) Value() interface{} {
return i.value
}
func (i *iter) Next() bool {
if !i.current.hasNext() {
return false
}
i.current = i.current.next()
i.key = i.current.key
i.value = i.current.value
return true
}
func (i *iter) Previous() bool {
if !i.current.hasPrevious() {
return false
}
i.current = i.current.previous()
i.key = i.current.key
i.value = i.current.value
return true
}
func (i *iter) Seek(key interface{}) (ok bool) {
current := i.current
list := i.list
// If the existing iterator outside of the known key range, we should set the
// position back to the beginning of the list.
if current == nil {
current = list.header
}
// If the target key occurs before the current key, we cannot take advantage
// of the heretofore spent traversal cost to find it; resetting back to the
// beginning is the safest choice.
if current.key != nil && list.lessThan(key, current.key) {
current = list.header
}
// We should back up to the so that we can seek to our present value if that
// is requested for whatever reason.
if current.backward == nil {
current = list.header
} else {
current = current.backward
}
current = list.getPath(current, nil, nil, key)
if current == nil {
return
}
i.current = current
i.key = current.key
i.value = current.value
return true
}
func (i *iter) Close() {
i.key = nil
i.value = nil
i.current = nil
i.list = nil
}
type rangeIterator struct {
iter
upperLimit interface{}
lowerLimit interface{}
}
func (i *rangeIterator) Next() bool {
if !i.current.hasNext() {
return false
}
next := i.current.next()
if !i.list.lessThan(next.key, i.upperLimit) {
return false
}
i.current = i.current.next()
i.key = i.current.key
i.value = i.current.value
return true
}
func (i *rangeIterator) Previous() bool {
if !i.current.hasPrevious() {
return false
}
previous := i.current.previous()
if i.list.lessThan(previous.key, i.lowerLimit) {
return false
}
i.current = i.current.previous()
i.key = i.current.key
i.value = i.current.value
return true
}
func (i *rangeIterator) Seek(key interface{}) (ok bool) {
if i.list.lessThan(key, i.lowerLimit) {
return
} else if !i.list.lessThan(key, i.upperLimit) {
return
}
return i.iter.Seek(key)
}
func (i *rangeIterator) Close() {
i.iter.Close()
i.upperLimit = nil
i.lowerLimit = nil
}
// Iterator returns an Iterator that will go through all elements s.
func (s *SkipList) Iterator() Iterator {
return &iter{
current: s.header,
list: s,
}
}
// Seek returns a bidirectional iterator starting with the first element whose
// key is greater or equal to key; otherwise, a nil iterator is returned.
func (s *SkipList) Seek(key interface{}) Iterator {
current := s.getPath(s.header, nil, nil, key)
if current == nil {
return nil
}
return &iter{
current: current,
key: current.key,
list: s,
value: current.value,
}
}
// SeekToFirst returns a bidirectional iterator starting from the first element
// in the list if the list is populated; otherwise, a nil iterator is returned.
func (s *SkipList) SeekToFirst() Iterator {
if s.length == 0 {
return nil
}
current := s.header.next()
return &iter{
current: current,
key: current.key,
list: s,
value: current.value,
}
}
// SeekToLast returns a bidirectional iterator starting from the last element
// in the list if the list is populated; otherwise, a nil iterator is returned.
func (s *SkipList) SeekToLast() Iterator {
current := s.footer
if current == nil {
return nil
}
return &iter{
current: current,
key: current.key,
list: s,
value: current.value,
}
}
// Range returns an iterator that will go through all the
// elements of the skip list that are greater or equal than from, but
// less than to.
func (s *SkipList) Range(from, to interface{}) Iterator {
start := s.getPath(s.header, nil, nil, from)
return &rangeIterator{
iter: iter{
current: &node{
forward: []*node{start},
backward: start,
},
list: s,
},
upperLimit: to,
lowerLimit: from,
}
}
func (s *SkipList) level() int {
return len(s.header.forward) - 1
}
func maxInt(x, y int) int {
if x > y {
return x
}
return y
}
func (s *SkipList) effectiveMaxLevel() int {
return maxInt(s.level(), s.MaxLevel)
}
// Returns a new random level.
func (s SkipList) randomLevel() (n int) {
for n = 0; n < s.effectiveMaxLevel() && rand.Float64() < p; n++ {
}
return
}
// Get returns the value associated with key from s (nil if the key is
// not present in s). The second return value is true when the key is
// present.
func (s *SkipList) Get(key interface{}) (value interface{}, ok bool) {
candidate := s.getPath(s.header, nil, nil, key)
if candidate == nil || candidate.key != key {
return nil, false
}
return candidate.value, true
}
// GetGreaterOrEqual finds the node whose key is greater than or equal
// to min. It returns its value, its actual key, and whether such a
// node is present in the skip list.
func (s *SkipList) GetGreaterOrEqual(min interface{}) (actualKey, value interface{}, ok bool) {
candidate := s.getPath(s.header, nil, nil, min)
if candidate != nil {
return candidate.key, candidate.value, true
}
return nil, nil, false
}
// getPath populates update with nodes that constitute the path to the
// node that may contain key. The candidate node will be returned. If
// update is nil, it will be left alone (the candidate node will still
// be returned). If update is not nil, but it doesn't have enough
// slots for all the nodes in the path, getPath will panic.
func (s *SkipList) getPath(current *node, update []*node, rank []int, key interface{}) *node {
depth := len(current.forward) - 1
for i := depth; i >= 0; i-- {
if rank != nil {
if i != depth {
rank[i] = rank[i+1]
}
}
for current.forward[i] != nil && s.lessThan(current.forward[i].key, key) {
if rank != nil {
rank[i] += current.span[i]
}
current = current.forward[i]
}
if update != nil {
update[i] = current
}
}
return current.next()
}
// Sets set the value associated with key in s.
func (s *SkipList) Set(key, value interface{}) {
if key == nil {
panic("goskiplist: nil keys are not supported")
}
// s.level starts from 0, so we need to allocate one.
update := make([]*node, s.level()+1, s.effectiveMaxLevel()+1)
rank := make([]int, s.level()+1, s.effectiveMaxLevel()+1)
candidate := s.getPath(s.header, update, rank, key)
if candidate != nil && candidate.key == key {
candidate.value = value
return
}
newLevel := s.randomLevel()
if currentLevel := s.level(); newLevel > currentLevel {
// there are no pointers for the higher levels in
// update. Header should be there. Also add higher
// level links to the header.
for i := currentLevel + 1; i <= newLevel; i++ {
update = append(update, s.header)
rank = append(rank, 0)
s.header.forward = append(s.header.forward, nil)
s.header.span = append(s.header.span, s.length)
}
}
newNode := &node{
forward: make([]*node, newLevel+1, s.effectiveMaxLevel()+1),
span: make([]int, newLevel+1, s.effectiveMaxLevel()+1),
key: key,
value: value,
}
if previous := update[0]; previous.key != nil {
newNode.backward = previous
}
for i := 0; i <= newLevel; i++ {
newNode.forward[i] = update[i].forward[i]
update[i].forward[i] = newNode
newNode.span[i] = update[i].span[i] - (rank[0] - rank[i])
update[i].span[i] = (rank[0] - rank[i]) + 1
}
for i := newLevel + 1; i <= s.level(); i++ {
update[i].span[i]++
}
s.length++
if newNode.forward[0] != nil {
if newNode.forward[0].backward != newNode {
newNode.forward[0].backward = newNode
}
}
if s.footer == nil || s.lessThan(s.footer.key, key) {
s.footer = newNode
}
}
// Delete removes the node with the given key.
//
// It returns the old value and whether the node was present.
func (s *SkipList) Delete(key interface{}) (value interface{}, ok bool) {
if key == nil {
panic("goskiplist: nil keys are not supported")
}
update := make([]*node, s.level()+1, s.effectiveMaxLevel())
candidate := s.getPath(s.header, update, nil, key)
if candidate == nil || candidate.key != key {
return nil, false
}
previous := candidate.backward
if s.footer == candidate {
s.footer = previous
}
next := candidate.next()
if next != nil {
next.backward = previous
}
for i := 0; i <= s.level(); i++ {
if update[i].forward[i] == candidate {
update[i].span[i] += candidate.span[i] - 1
update[i].forward[i] = candidate.forward[i]
} else {
update[i].span[i]--
}
}
for s.level() > 0 && s.header.forward[s.level()] == nil {
s.header.forward = s.header.forward[:s.level()]
}
s.length--
return candidate.value, true
}
// Find the rank for an element by both score and key.
//
// Returns 0 when the element cannot be found, rank otherwise.
//
// Note that the rank is 1-based due to the span of s.header to the
// first element.
//
func (s *SkipList) GetRank(key interface{}) int {
var rank int
depth := len(s.header.forward) - 1
current := s.header
for i := depth; i >= 0; i-- {
for current.forward[i] != nil && s.lessThan(current.forward[i].key, key) {
rank += current.span[i]
current = current.forward[i]
}
}
if current != nil {
current = current.next()
}
if current != nil && current.key == key {
return rank + 1
}
return 0
}
// Finds an element by its rank. The rank argument needs to be 1-based.
func (s *SkipList) GetElementByRank(rank int) (interface{}, bool) {
var traversed int
depth := len(s.header.forward) - 1
current := s.header
for i := depth; i >= 0; i-- {
for current.forward[i] != nil && (traversed+current.span[i] <= rank) {
traversed += current.span[i]
current = current.forward[i]
}
if traversed == rank {
return current.value, true
}
}
return nil, false
}
// NewCustomMap returns a new SkipList that will use lessThan as the
// comparison function. lessThan should define a linear order on keys
// you intend to use with the SkipList.
func NewCustomMap(lessThan func(l, r interface{}) bool) *SkipList {
return &SkipList{
lessThan: lessThan,
header: &node{
forward: []*node{nil},
span: []int{0},
},
MaxLevel: DefaultMaxLevel,
}
}
// Ordered is an interface which can be linearly ordered by the
// LessThan method, whereby this instance is deemed to be less than
// other. Additionally, Ordered instances should behave properly when
// compared using == and !=.
type Ordered interface {
LessThan(other Ordered) bool
}
// New returns a new SkipList.
//
// Its keys must implement the Ordered interface.
func New() *SkipList {
comparator := func(left, right interface{}) bool {
return left.(Ordered).LessThan(right.(Ordered))
}
return NewCustomMap(comparator)
}
// NewIntKey returns a SkipList that accepts int keys.
func NewIntMap() *SkipList {
return NewCustomMap(func(l, r interface{}) bool {
return l.(int) < r.(int)
})
}
// NewStringMap returns a SkipList that accepts string keys.
func NewStringMap() *SkipList {
return NewCustomMap(func(l, r interface{}) bool {
return l.(string) < r.(string)
})
}
// Set is an ordered set data structure.
//
// Its elements must implement the Ordered interface. It uses a
// SkipList for storage, and it gives you similar performance
// guarantees.
//
// To iterate over a set (where s is a *Set):
//
// for i := s.Iterator(); i.Next(); {
// // do something with i.Key().
// // i.Value() will be nil.
// }
type Set struct {
skiplist SkipList
}
// NewSet returns a new Set.
func NewSet() *Set {
comparator := func(left, right interface{}) bool {
return left.(Ordered).LessThan(right.(Ordered))
}
return NewCustomSet(comparator)
}
// NewCustomSet returns a new Set that will use lessThan as the
// comparison function. lessThan should define a linear order on
// elements you intend to use with the Set.
func NewCustomSet(lessThan func(l, r interface{}) bool) *Set {
return &Set{skiplist: SkipList{
lessThan: lessThan,
header: &node{
forward: []*node{nil},
span: []int{0},
},
MaxLevel: DefaultMaxLevel,
}}
}
// NewIntSet returns a new Set that accepts int elements.
func NewIntSet() *Set {
return NewCustomSet(func(l, r interface{}) bool {
return l.(int) < r.(int)
})
}
// NewStringSet returns a new Set that accepts string elements.
func NewStringSet() *Set {
return NewCustomSet(func(l, r interface{}) bool {
return l.(string) < r.(string)
})
}
// Add adds key to s.
func (s *Set) Add(key interface{}) {
s.skiplist.Set(key, nil)
}
// Remove tries to remove key from the set. It returns true if key was
// present.
func (s *Set) Remove(key interface{}) (ok bool) {
_, ok = s.skiplist.Delete(key)
return ok
}
// Len returns the length of the set.
func (s *Set) Len() int {
return s.skiplist.Len()
}
// Contains returns true if key is present in s.
func (s *Set) Contains(key interface{}) bool {
_, ok := s.skiplist.Get(key)
return ok
}
func (s *Set) Iterator() Iterator {
return s.skiplist.Iterator()
}
// Range returns an iterator that will go through all the elements of
// the set that are greater or equal than from, but less than to.
func (s *Set) Range(from, to interface{}) Iterator {
return s.skiplist.Range(from, to)
}
// SetMaxLevel sets MaxLevel in the underlying skip list.
func (s *Set) SetMaxLevel(newMaxLevel int) {
s.skiplist.MaxLevel = newMaxLevel
}
// GetMaxLevel returns MaxLevel fo the underlying skip list.
func (s *Set) GetMaxLevel() int {
return s.skiplist.MaxLevel
}

View File

@ -0,0 +1,950 @@
// Copyright 2012 Google Inc. All rights reserved.
// Author: Ric Szopa (Ryszard) <ryszard.szopa@gmail.com>
// Package skiplist implements skip list based maps and sets.
//
// Skip lists are a data structure that can be used in place of
// balanced trees. Skip lists use probabilistic balancing rather than
// strictly enforced balancing and as a result the algorithms for
// insertion and deletion in skip lists are much simpler and
// significantly faster than equivalent algorithms for balanced trees.
//
// Skip lists were first described in Pugh, William (June 1990). "Skip
// lists: a probabilistic alternative to balanced
// trees". Communications of the ACM 33 (6): 668676
package skiplist
import (
"fmt"
"math/rand"
"sort"
"testing"
)
func (s *SkipList) printRepr() {
fmt.Printf("header:\n")
for i, link := range s.header.forward {
if link != nil {
fmt.Printf("\t%d: -> %v\n", i, link.key)
} else {
fmt.Printf("\t%d: -> END\n", i)
}
}
for node := s.header.next(); node != nil; node = node.next() {
fmt.Printf("%v: %v (level %d)\n", node.key, node.value, len(node.forward))
for i, link := range node.forward {
if link != nil {
fmt.Printf("\t%d: -> %v\n", i, link.key)
} else {
fmt.Printf("\t%d: -> END\n", i)
}
}
}
fmt.Println()
}
func TestInitialization(t *testing.T) {
s := NewCustomMap(func(l, r interface{}) bool {
return l.(int) < r.(int)
})
if !s.lessThan(1, 2) {
t.Errorf("Less than doesn't work correctly.")
}
}
func TestEmptyNodeNext(t *testing.T) {
n := new(node)
if next := n.next(); next != nil {
t.Errorf("Next() should be nil for an empty node.")
}
if n.hasNext() {
t.Errorf("hasNext() should be false for an empty node.")
}
}
func TestEmptyNodePrev(t *testing.T) {
n := new(node)
if previous := n.previous(); previous != nil {
t.Errorf("Previous() should be nil for an empty node.")
}
if n.hasPrevious() {
t.Errorf("hasPrevious() should be false for an empty node.")
}
}
func TestNodeHasNext(t *testing.T) {
s := NewIntMap()
s.Set(0, 0)
node := s.header.next()
if node.key != 0 {
t.Fatalf("We got the wrong node: %v.", node)
}
if node.hasNext() {
t.Errorf("%v should be the last node.", node)
}
}
func TestNodeHasPrev(t *testing.T) {
s := NewIntMap()
s.Set(0, 0)
node := s.header.previous()
if node != nil {
t.Fatalf("Expected no previous entry, got %v.", node)
}
}
func (s *SkipList) check(t *testing.T, key, wanted int) {
if got, _ := s.Get(key); got != wanted {
t.Errorf("For key %v wanted value %v, got %v.", key, wanted, got)
}
}
func TestGet(t *testing.T) {
s := NewIntMap()
s.Set(0, 0)
if value, present := s.Get(0); !(value == 0 && present) {
t.Errorf("%v, %v instead of %v, %v", value, present, 0, true)
}
if value, present := s.Get(100); value != nil || present {
t.Errorf("%v, %v instead of %v, %v", value, present, nil, false)
}
}
func TestGetGreaterOrEqual(t *testing.T) {
s := NewIntMap()
if _, value, present := s.GetGreaterOrEqual(5); !(value == nil && !present) {
t.Errorf("s.GetGreaterOrEqual(5) should have returned nil and false for an empty map, not %v and %v.", value, present)
}
s.Set(0, 0)
if _, value, present := s.GetGreaterOrEqual(5); !(value == nil && !present) {
t.Errorf("s.GetGreaterOrEqual(5) should have returned nil and false for an empty map, not %v and %v.", value, present)
}
s.Set(10, 10)
if key, value, present := s.GetGreaterOrEqual(5); !(value == 10 && key == 10 && present) {
t.Errorf("s.GetGreaterOrEqual(5) should have returned 10 and true, not %v and %v.", value, present)
}
}
func TestSet(t *testing.T) {
s := NewIntMap()
if l := s.Len(); l != 0 {
t.Errorf("Len is not 0, it is %v", l)
}
s.Set(0, 0)
s.Set(1, 1)
if l := s.Len(); l != 2 {
t.Errorf("Len is not 2, it is %v", l)
}
s.check(t, 0, 0)
if t.Failed() {
t.Errorf("header.Next() after s.Set(0, 0) and s.Set(1, 1): %v.", s.header.next())
}
s.check(t, 1, 1)
}
func TestChange(t *testing.T) {
s := NewIntMap()
s.Set(0, 0)
s.Set(1, 1)
s.Set(2, 2)
s.Set(0, 7)
if value, _ := s.Get(0); value != 7 {
t.Errorf("Value should be 7, not %d", value)
}
s.Set(1, 8)
if value, _ := s.Get(1); value != 8 {
t.Errorf("Value should be 8, not %d", value)
}
}
func TestDelete(t *testing.T) {
s := NewIntMap()
for i := 0; i < 10; i++ {
s.Set(i, i)
}
for i := 0; i < 10; i += 2 {
s.Delete(i)
}
for i := 0; i < 10; i += 2 {
if _, present := s.Get(i); present {
t.Errorf("%d should not be present in s", i)
}
}
if v, present := s.Delete(10000); v != nil || present {
t.Errorf("Deleting a non-existent key should return nil, false, and not %v, %v.", v, present)
}
if t.Failed() {
s.printRepr()
}
}
func TestLen(t *testing.T) {
s := NewIntMap()
for i := 0; i < 10; i++ {
s.Set(i, i)
}
if length := s.Len(); length != 10 {
t.Errorf("Length should be equal to 10, not %v.", length)
s.printRepr()
}
for i := 0; i < 5; i++ {
s.Delete(i)
}
if length := s.Len(); length != 5 {
t.Errorf("Length should be equal to 5, not %v.", length)
}
s.Delete(10000)
if length := s.Len(); length != 5 {
t.Errorf("Length should be equal to 5, not %v.", length)
}
}
func TestIteration(t *testing.T) {
s := NewIntMap()
for i := 0; i < 20; i++ {
s.Set(i, i)
}
seen := 0
var lastKey int
i := s.Iterator()
defer i.Close()
for i.Next() {
seen++
lastKey = i.Key().(int)
if i.Key() != i.Value() {
t.Errorf("Wrong value for key %v: %v.", i.Key(), i.Value())
}
}
if seen != s.Len() {
t.Errorf("Not all the items in s where iterated through (seen %d, should have seen %d). Last one seen was %d.", seen, s.Len(), lastKey)
}
for i.Previous() {
if i.Key() != i.Value() {
t.Errorf("Wrong value for key %v: %v.", i.Key(), i.Value())
}
if i.Key().(int) >= lastKey {
t.Errorf("Expected key to descend but ascended from %v to %v.", lastKey, i.Key())
}
lastKey = i.Key().(int)
}
if lastKey != 0 {
t.Errorf("Expected to count back to zero, but stopped at key %v.", lastKey)
}
}
func TestRangeIteration(t *testing.T) {
s := NewIntMap()
for i := 0; i < 20; i++ {
s.Set(i, i)
}
max, min := 0, 100000
var lastKey, seen int
i := s.Range(5, 10)
defer i.Close()
for i.Next() {
seen++
lastKey = i.Key().(int)
if lastKey > max {
max = lastKey
}
if lastKey < min {
min = lastKey
}
if i.Key() != i.Value() {
t.Errorf("Wrong value for key %v: %v.", i.Key(), i.Value())
}
}
if seen != 5 {
t.Errorf("The number of items yielded is incorrect (should be 5, was %v)", seen)
}
if min != 5 {
t.Errorf("The smallest element should have been 5, not %v", min)
}
if max != 9 {
t.Errorf("The largest element should have been 9, not %v", max)
}
if i.Seek(4) {
t.Error("Allowed to seek to invalid range.")
}
if !i.Seek(5) {
t.Error("Could not seek to an allowed range.")
}
if i.Key().(int) != 5 || i.Value().(int) != 5 {
t.Errorf("Expected 5 for key and 5 for value, got %d and %d", i.Key(), i.Value())
}
if !i.Seek(7) {
t.Error("Could not seek to an allowed range.")
}
if i.Key().(int) != 7 || i.Value().(int) != 7 {
t.Errorf("Expected 7 for key and 7 for value, got %d and %d", i.Key(), i.Value())
}
if i.Seek(10) {
t.Error("Allowed to seek to invalid range.")
}
i.Seek(9)
seen = 0
min = 100000
max = -1
for i.Previous() {
seen++
lastKey = i.Key().(int)
if lastKey > max {
max = lastKey
}
if lastKey < min {
min = lastKey
}
if i.Key() != i.Value() {
t.Errorf("Wrong value for key %v: %v.", i.Key(), i.Value())
}
}
if seen != 4 {
t.Errorf("The number of items yielded is incorrect (should be 5, was %v)", seen)
}
if min != 5 {
t.Errorf("The smallest element should have been 5, not %v", min)
}
if max != 8 {
t.Errorf("The largest element should have been 9, not %v", max)
}
}
func TestSomeMore(t *testing.T) {
s := NewIntMap()
insertions := [...]int{4, 1, 2, 9, 10, 7, 3}
for _, i := range insertions {
s.Set(i, i)
}
for _, i := range insertions {
s.check(t, i, i)
}
}
func makeRandomList(n int) *SkipList {
s := NewIntMap()
for i := 0; i < n; i++ {
insert := rand.Int()
s.Set(insert, insert)
}
return s
}
func LookupBenchmark(b *testing.B, n int) {
b.StopTimer()
s := makeRandomList(n)
b.StartTimer()
for i := 0; i < b.N; i++ {
s.Get(rand.Int())
}
}
func SetBenchmark(b *testing.B, n int) {
b.StopTimer()
values := []int{}
for i := 0; i < b.N; i++ {
values = append(values, rand.Int())
}
s := NewIntMap()
b.StartTimer()
for i := 0; i < b.N; i++ {
s.Set(values[i], values[i])
}
}
// Make sure that all the keys are unique and are returned in order.
func TestSanity(t *testing.T) {
s := NewIntMap()
for i := 0; i < 10000; i++ {
insert := rand.Int()
s.Set(insert, insert)
}
var last int = 0
i := s.Iterator()
defer i.Close()
for i.Next() {
if last != 0 && i.Key().(int) <= last {
t.Errorf("Not in order!")
}
last = i.Key().(int)
}
for i.Previous() {
if last != 0 && i.Key().(int) > last {
t.Errorf("Not in order!")
}
last = i.Key().(int)
}
}
type MyOrdered struct {
value int
}
func (me MyOrdered) LessThan(other Ordered) bool {
return me.value < other.(MyOrdered).value
}
func TestOrdered(t *testing.T) {
s := New()
s.Set(MyOrdered{0}, 0)
s.Set(MyOrdered{1}, 1)
if val, _ := s.Get(MyOrdered{0}); val != 0 {
t.Errorf("Wrong value for MyOrdered{0}. Should have been %d.", val)
}
}
func TestNewStringMap(t *testing.T) {
s := NewStringMap()
s.Set("a", 1)
s.Set("b", 2)
if value, _ := s.Get("a"); value != 1 {
t.Errorf("Expected 1, got %v.", value)
}
}
func TestGetNilKey(t *testing.T) {
s := NewStringMap()
if v, present := s.Get(nil); v != nil || present {
t.Errorf("s.Get(nil) should return nil, false (not %v, %v).", v, present)
}
}
func TestSetNilKey(t *testing.T) {
s := NewStringMap()
defer func() {
if err := recover(); err == nil {
t.Errorf("s.Set(nil, 0) should have panicked.")
}
}()
s.Set(nil, 0)
}
func TestSetMaxLevelInFlight(t *testing.T) {
s := NewIntMap()
s.MaxLevel = 2
for i := 0; i < 64; i++ {
insert := 2 * rand.Int()
s.Set(insert, insert)
}
s.MaxLevel = 64
for i := 0; i < 65536; i++ {
insert := 2*rand.Int() + 1
s.Set(insert, insert)
}
i := s.Iterator()
defer i.Close()
for i.Next() {
if v, _ := s.Get(i.Key()); v != i.Key() {
t.Errorf("Bad values in the skip list (%v). Inserted before the call to s.SetMax(): %t.", v, i.Key().(int)%2 == 0)
}
}
}
func TestDeletingHighestLevelNodeDoesntBreakSkiplist(t *testing.T) {
s := NewIntMap()
elements := []int{1, 3, 5, 7, 0, 4, 5, 10, 11}
for _, i := range elements {
s.Set(i, i)
}
highestLevelNode := s.header.forward[len(s.header.forward)-1]
s.Delete(highestLevelNode.key)
seen := 0
i := s.Iterator()
defer i.Close()
for i.Next() {
seen++
}
if seen == 0 {
t.Errorf("Iteration is broken (no elements seen).")
}
}
func TestNewSet(t *testing.T) {
set := NewIntSet()
elements := []int{1, 3, 5, 7, 0, 4, 5}
for _, i := range elements {
set.Add(i)
}
if length := set.Len(); length != 6 {
t.Errorf("set.Len() should be equal to 6, not %v.", length)
}
if !set.Contains(3) {
t.Errorf("set should contain 3.")
}
if set.Contains(1000) {
t.Errorf("set should not contain 1000.")
}
removed := set.Remove(1)
if !removed {
t.Errorf("Remove returned false for element that was present in set.")
}
seen := 0
i := set.Iterator()
defer i.Close()
for i.Next() {
seen++
}
if seen != 5 {
t.Errorf("Iterator() iterated through %v elements. Should have been 5.", seen)
}
if set.Contains(1) {
t.Errorf("1 was removed, set should not contain 1.")
}
if length := set.Len(); length != 5 {
t.Errorf("After removing one element, set.Len() should be equal to 5, not %v.", length)
}
set.SetMaxLevel(10)
if ml := set.GetMaxLevel(); ml != 10 {
t.Errorf("MaxLevel for set should be 10, not %v", ml)
}
}
func TestSetRangeIterator(t *testing.T) {
set := NewIntSet()
elements := []int{0, 1, 3, 5}
for _, i := range elements {
set.Add(i)
}
seen := 0
for i := set.Range(2, 1000); i.Next(); {
seen++
}
if seen != 2 {
t.Errorf("There should have been 2 elements in Range(2, 1000), not %v.", seen)
}
}
func TestNewStringSet(t *testing.T) {
set := NewStringSet()
strings := []string{"ala", "ma", "kota"}
for _, v := range strings {
set.Add(v)
}
if !set.Contains("ala") {
t.Errorf("set should contain \"ala\".")
}
}
func TestIteratorPrevHoles(t *testing.T) {
m := NewIntMap()
i := m.Iterator()
defer i.Close()
m.Set(0, 0)
m.Set(1, 1)
m.Set(2, 2)
if !i.Next() {
t.Errorf("Expected iterator to move successfully to the next.")
}
if !i.Next() {
t.Errorf("Expected iterator to move successfully to the next.")
}
if !i.Next() {
t.Errorf("Expected iterator to move successfully to the next.")
}
if i.Key().(int) != 2 || i.Value().(int) != 2 {
t.Errorf("Expected iterator to reach key 2 and value 2, got %v and %v.", i.Key(), i.Value())
}
if !i.Previous() {
t.Errorf("Expected iterator to move successfully to the previous.")
}
if i.Key().(int) != 1 || i.Value().(int) != 1 {
t.Errorf("Expected iterator to reach key 1 and value 1, got %v and %v.", i.Key(), i.Value())
}
if !i.Next() {
t.Errorf("Expected iterator to move successfully to the next.")
}
m.Delete(1)
if !i.Previous() {
t.Errorf("Expected iterator to move successfully to the previous.")
}
if i.Key().(int) != 0 || i.Value().(int) != 0 {
t.Errorf("Expected iterator to reach key 0 and value 0, got %v and %v.", i.Key(), i.Value())
}
}
func TestIteratorSeek(t *testing.T) {
m := NewIntMap()
i := m.Seek(0)
if i != nil {
t.Errorf("Expected nil iterator, but got %v.", i)
}
i = m.SeekToFirst()
if i != nil {
t.Errorf("Expected nil iterator, but got %v.", i)
}
i = m.SeekToLast()
if i != nil {
t.Errorf("Expected nil iterator, but got %v.", i)
}
m.Set(0, 0)
i = m.SeekToFirst()
defer i.Close()
if i.Key().(int) != 0 || i.Value().(int) != 0 {
t.Errorf("Expected iterator to reach key 0 and value 0, got %v and %v.", i.Key(), i.Value())
}
i = m.SeekToLast()
defer i.Close()
if i.Key().(int) != 0 || i.Value().(int) != 0 {
t.Errorf("Expected iterator to reach key 0 and value 0, got %v and %v.", i.Key(), i.Value())
}
m.Set(1, 1)
i = m.SeekToFirst()
defer i.Close()
if i.Key().(int) != 0 || i.Value().(int) != 0 {
t.Errorf("Expected iterator to reach key 0 and value 0, got %v and %v.", i.Key(), i.Value())
}
i = m.SeekToLast()
defer i.Close()
if i.Key().(int) != 1 || i.Value().(int) != 1 {
t.Errorf("Expected iterator to reach key 1 and value 1, got %v and %v.", i.Key(), i.Value())
}
m.Set(2, 2)
i = m.SeekToFirst()
defer i.Close()
if i.Key().(int) != 0 || i.Value().(int) != 0 {
t.Errorf("Expected iterator to reach key 0 and value 0, got %v and %v.", i.Key(), i.Value())
}
i = m.SeekToLast()
defer i.Close()
if i.Key().(int) != 2 || i.Value().(int) != 2 {
t.Errorf("Expected iterator to reach key 2 and value 2, got %v and %v.", i.Key(), i.Value())
}
i = m.Seek(0)
defer i.Close()
if i.Key().(int) != 0 || i.Value().(int) != 0 {
t.Errorf("Expected iterator to reach key 0 and value 0, got %v and %v.", i.Key(), i.Value())
}
i = m.Seek(2)
defer i.Close()
if i.Key().(int) != 2 || i.Value().(int) != 2 {
t.Errorf("Expected iterator to reach key 2 and value 2, got %v and %v.", i.Key(), i.Value())
}
i = m.Seek(1)
defer i.Close()
if i.Key().(int) != 1 || i.Value().(int) != 1 {
t.Errorf("Expected iterator to reach key 1 and value 1, got %v and %v.", i.Key(), i.Value())
}
i = m.Seek(3)
if i != nil {
t.Errorf("Expected to receive nil iterator, got %v.", i)
}
m.Set(4, 4)
i = m.Seek(4)
defer i.Close()
if i.Key().(int) != 4 || i.Value().(int) != 4 {
t.Errorf("Expected iterator to reach key 4 and value 4, got %v and %v.", i.Key(), i.Value())
}
i = m.Seek(3)
defer i.Close()
if i.Key().(int) != 4 || i.Value().(int) != 4 {
t.Errorf("Expected iterator to reach key 4 and value 4, got %v and %v.", i.Key(), i.Value())
}
m.Delete(4)
i = m.SeekToFirst()
defer i.Close()
if i.Key().(int) != 0 || i.Value().(int) != 0 {
t.Errorf("Expected iterator to reach key 0 and value 0, got %v and %v.", i.Key(), i.Value())
}
i = m.SeekToLast()
defer i.Close()
if i.Key().(int) != 2 || i.Value().(int) != 2 {
t.Errorf("Expected iterator to reach key 2 and value 2, got %v and %v.", i.Key(), i.Value())
}
if !i.Seek(2) {
t.Error("Expected iterator to seek to key.")
}
if i.Key().(int) != 2 || i.Value().(int) != 2 {
t.Errorf("Expected iterator to reach key 2 and value 2, got %v and %v.", i.Key(), i.Value())
}
if !i.Seek(1) {
t.Error("Expected iterator to seek to key.")
}
if i.Key().(int) != 1 || i.Value().(int) != 1 {
t.Errorf("Expected iterator to reach key 1 and value 1, got %v and %v.", i.Key(), i.Value())
}
if !i.Seek(0) {
t.Error("Expected iterator to seek to key.")
}
if i.Key().(int) != 0 || i.Value().(int) != 0 {
t.Errorf("Expected iterator to reach key 0 and value 0, got %v and %v.", i.Key(), i.Value())
}
i = m.SeekToFirst()
defer i.Close()
if !i.Seek(0) {
t.Error("Expected iterator to seek to key.")
}
if i.Key().(int) != 0 || i.Value().(int) != 0 {
t.Errorf("Expected iterator to reach key 0 and value 0, got %v and %v.", i.Key(), i.Value())
}
}
func TestRank(t *testing.T) {
s := NewIntMap()
for i := 0; i < 10; i++ {
s.Set(i, i)
}
for i := 0; i < 10; i++ {
if rank := s.GetRank(i); rank != (i + 1) {
t.Errorf("%d should be rank %d", i, i+1)
}
}
}
func TestGetElementByRank(t *testing.T) {
s := NewIntMap()
for i := 0; i < 10; i++ {
s.Set(i, i)
}
for i := 0; i < 10; i++ {
if v, ok := s.GetElementByRank(i + 1); !ok || v != i {
t.Errorf("%d should be rank %d", i, i+1)
}
}
}
func BenchmarkLookup16(b *testing.B) {
LookupBenchmark(b, 16)
}
func BenchmarkLookup256(b *testing.B) {
LookupBenchmark(b, 256)
}
func BenchmarkLookup65536(b *testing.B) {
LookupBenchmark(b, 65536)
}
func BenchmarkSet16(b *testing.B) {
SetBenchmark(b, 16)
}
func BenchmarkSet256(b *testing.B) {
SetBenchmark(b, 256)
}
func BenchmarkSet65536(b *testing.B) {
SetBenchmark(b, 65536)
}
func BenchmarkRandomSeek(b *testing.B) {
b.StopTimer()
values := []int{}
s := NewIntMap()
for i := 0; i < b.N; i++ {
r := rand.Int()
values = append(values, r)
s.Set(r, r)
}
b.StartTimer()
for i := 0; i < b.N; i++ {
iterator := s.Seek(values[i])
if iterator == nil {
b.Errorf("got incorrect value for index %d", i)
}
}
}
const (
lookAhead = 10
)
// This test is used for the baseline comparison of Iterator.Seek when
// performing forward sequential seek operations.
func BenchmarkForwardSeek(b *testing.B) {
b.StopTimer()
values := []int{}
s := NewIntMap()
valueCount := b.N
for i := 0; i < valueCount; i++ {
r := rand.Int()
values = append(values, r)
s.Set(r, r)
}
sort.Ints(values)
b.StartTimer()
for i := 0; i < b.N; i++ {
key := values[i]
iterator := s.Seek(key)
if i < valueCount-lookAhead {
nextKey := values[i+lookAhead]
iterator = s.Seek(nextKey)
if iterator.Key().(int) != nextKey || iterator.Value().(int) != nextKey {
b.Errorf("%d. expected %d key and %d value, got %d key and %d value", i, nextKey, nextKey, iterator.Key(), iterator.Value())
}
}
}
}
// This test demonstrates the amortized cost of a forward sequential seek.
func BenchmarkForwardSeekReusedIterator(b *testing.B) {
b.StopTimer()
values := []int{}
s := NewIntMap()
valueCount := b.N
for i := 0; i < valueCount; i++ {
r := rand.Int()
values = append(values, r)
s.Set(r, r)
}
sort.Ints(values)
b.StartTimer()
for i := 0; i < b.N; i++ {
key := values[i]
iterator := s.Seek(key)
if i < valueCount-lookAhead {
nextKey := values[i+lookAhead]
if !iterator.Seek(nextKey) {
b.Errorf("%d. expected iterator to seek to %d key; failed.", i, nextKey)
} else if iterator.Key().(int) != nextKey || iterator.Value().(int) != nextKey {
b.Errorf("%d. expected %d key and %d value, got %d key and %d value", i, nextKey, nextKey, iterator.Key(), iterator.Value())
}
}
}
}

View File

@ -0,0 +1,60 @@
package container
import (
"container/list"
"sync"
)
type SynchronizedList struct {
list *list.List
lock *sync.Mutex
}
func NewSynchronizedList() *SynchronizedList {
sl := &SynchronizedList{
list: list.New(),
lock: new(sync.Mutex),
}
return sl
}
func (sl *SynchronizedList) PushFront(v interface{}) {
sl.lock.Lock()
sl.list.PushFront(v)
sl.lock.Unlock()
}
func (sl *SynchronizedList) PopFront() (v interface{}) {
sl.lock.Lock()
e := sl.list.Front()
if e != nil {
v = e.Value
sl.list.Remove(e)
}
sl.lock.Unlock()
return v
}
func (sl *SynchronizedList) PushBack(v interface{}) {
sl.lock.Lock()
sl.list.PushBack(v)
sl.lock.Unlock()
}
func (sl *SynchronizedList) PopBack() (v interface{}) {
sl.lock.Lock()
e := sl.list.Back()
if e != nil {
v = e.Value
sl.list.Remove(e)
}
sl.lock.Unlock()
return v
}
func (sl *SynchronizedList) Len() (n int) {
sl.lock.Lock()
n = sl.list.Len()
sl.lock.Unlock()
return
}

View File

@ -0,0 +1,82 @@
package container
import (
"sync"
)
type SynchronizedMap struct {
lock *sync.RWMutex
m map[interface{}]interface{}
}
// NewSynchronizedMap return new SynchronizedMap
func NewSynchronizedMap() *SynchronizedMap {
return &SynchronizedMap{
lock: new(sync.RWMutex),
m: make(map[interface{}]interface{}),
}
}
// Get from maps return the k's value
func (m *SynchronizedMap) Get(k interface{}) interface{} {
m.lock.RLock()
if val, ok := m.m[k]; ok {
m.lock.RUnlock()
return val
}
m.lock.RUnlock()
return nil
}
// Maps the given key and value. Returns false
// if the key is already in the map and changes nothing.
func (m *SynchronizedMap) Set(k interface{}, v interface{}) bool {
m.lock.Lock()
if val, ok := m.m[k]; !ok {
m.m[k] = v
} else if val != v {
m.m[k] = v
} else {
m.lock.Unlock()
return false
}
m.lock.Unlock()
return true
}
// Returns true if k is exist in the map.
func (m *SynchronizedMap) IsExist(k interface{}) bool {
m.lock.RLock()
if _, ok := m.m[k]; !ok {
m.lock.RUnlock()
return false
}
m.lock.RUnlock()
return true
}
// Delete the given key and value.
func (m *SynchronizedMap) Delete(k interface{}) {
m.lock.Lock()
delete(m.m, k)
m.lock.Unlock()
}
// Items returns all items in SynchronizedMap.
func (m *SynchronizedMap) Items() map[interface{}]interface{} {
mm := make(map[interface{}]interface{})
m.lock.RLock()
for k, v := range m.m {
mm[k] = v
}
m.lock.RUnlock()
return mm
}
func (m *SynchronizedMap) Foreach(cb func(k, v interface{})) {
m.lock.Lock()
defer m.lock.Unlock()
for k, v := range m.m {
cb(k, v)
}
}

94
core/ctx.go Normal file
View File

@ -0,0 +1,94 @@
package core
import (
"fmt"
"os"
"path/filepath"
"mongo.games.com/goserver/core/basic"
"mongo.games.com/goserver/core/utils"
)
const (
HOOK_BEFORE_START int = iota
HOOK_AFTER_STOP
HOOK_MAX
)
var (
AppCtx *Ctx = newCtx()
hooks [HOOK_MAX][]hookfunc
)
type hookfunc func() error
type Ctx struct {
*basic.Object
CoreObj *basic.Object
}
func newCtx() *Ctx {
ctx := &Ctx{}
ctx.init()
return ctx
}
func (ctx *Ctx) init() {
ctx.Object = basic.NewObject(ObjId_RootId,
"root",
basic.Options{
MaxDone: 1024,
QueueBacklog: 1024,
},
nil)
ctx.Object.Waitor = utils.NewWaitor("core.Ctx")
ctx.UserData = ctx
ctx.Active()
}
func LaunchChild(o *basic.Object) {
AppCtx.LaunchChild(o)
}
func Terminate(o *basic.Object) {
AppCtx.Terminate(o)
}
func CoreObject() *basic.Object {
//return AppCtx.GetChildById(ObjId_CoreId)
return AppCtx.CoreObj
}
func RegisteHook(hookpos int, f hookfunc) {
if hookpos < 0 || hookpos > HOOK_MAX {
return
}
hooks[hookpos] = append(hooks[hookpos], f)
}
func ExecuteHook(hookpos int) error {
if hookpos < 0 || hookpos > HOOK_MAX {
return nil
}
var err error
for _, h := range hooks[hookpos] {
err = h()
if err != nil {
return err
}
}
return nil
}
func WritePid() {
if len(os.Args) > 0 {
baseName := filepath.Base(os.Args[0])
f, err := os.OpenFile(baseName+".pid", os.O_CREATE|os.O_TRUNC|os.O_RDWR, os.ModePerm)
if err != nil {
panic(fmt.Sprintf("%s had running", os.Args[0]))
return
}
f.WriteString(fmt.Sprintf("%v", os.Getpid()))
}
}

27
core/doc.go Normal file
View File

@ -0,0 +1,27 @@
package core
/*
core struct
AppCtx---------------------------------------------
| | | |
| TimerMgr TaskExecutor Profile
|
AppModules--------------------------------------
| | |
| | XXX_UserCustomModule
| |
| TransactModule
|
|
NetModule------------------------
| |
| Connector-----------------
| | |
| Session Socket Connect
|
Acceptor---------------------
| |
Session0 Session1..n
*/

160
core/i18n/config.go Normal file
View File

@ -0,0 +1,160 @@
package i18n
import (
"crypto/md5"
"encoding/hex"
"encoding/json"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/howeyc/fsnotify"
"mongo.games.com/goserver/core"
"mongo.games.com/goserver/core/basic"
"mongo.games.com/goserver/core/logger"
)
var Config = Configuration{}
type Configuration struct {
RootPath string
hashCodes map[string]string
watcher *fsnotify.Watcher
}
func (this *Configuration) Name() string {
return "i18n"
}
func (this *Configuration) Init() error {
var err error
workDir, err := os.Getwd()
if err != nil {
return err
}
this.RootPath = filepath.Join(workDir, this.RootPath)
this.watcher, err = fsnotify.NewWatcher()
if err != nil {
logger.Logger.Warn(" fsnotify.NewWatcher err:", err)
return err
}
// Process events
go func() {
defer func() {
if err := recover(); err != nil {
logger.Logger.Warn("watch data director modify goroutine err:", err)
}
}()
for {
select {
case ev := <-this.watcher.Event:
if ev != nil && ev.IsModify() && filepath.Ext(ev.Name) == ".json" {
core.CoreObject().SendCommand(&fileModifiedCommand{fileName: ev.Name}, false)
logger.Logger.Trace("fsnotify event:", ev)
}
case err := <-this.watcher.Error:
logger.Logger.Warn("fsnotify error:", err)
}
}
logger.Logger.Warn(this.RootPath, " watcher quit!")
}()
this.watcher.Watch(this.RootPath)
this.hashCodes = make(map[string]string)
//获得配置目录中所有的数据文件
var files = []string{}
filepath.Walk(this.RootPath, func(path string, info os.FileInfo, err error) error {
if info.IsDir() == false && filepath.Ext(info.Name()) == ".json" {
files = append(files, info.Name())
}
return nil
})
//加载这些数据文件
h := md5.New()
for _, f := range files {
logger.Logger.Trace("load file name ======", f)
buf, err := ioutil.ReadFile(filepath.Join(this.RootPath, f))
if err != nil {
logger.Logger.Warn("i18n Config.Init ioutil.ReadFile error", err)
return err
}
kv := make(map[string]string)
err = json.Unmarshal(buf, &kv)
if err != nil {
logger.Logger.Warn("i18n Config.Init json.Unmarshal error", err)
return err
}
nameAndExt := strings.SplitN(f, ".", 2)
if len(nameAndExt) == 2 {
lang := nameAndExt[0]
loc := &locale{lang: lang, message: kv}
if loc != nil {
locales.Add(loc)
}
h.Reset()
h.Write(buf)
this.hashCodes[f] = hex.EncodeToString(h.Sum(nil))
}
}
return nil
}
func (this *Configuration) Close() error {
this.watcher.Close()
return nil
}
type fileModifiedCommand struct {
fileName string
}
func (fmc *fileModifiedCommand) Done(o *basic.Object) error {
fn := filepath.Base(fmc.fileName)
hashCode := Config.hashCodes[fn]
buf, err := ioutil.ReadFile(filepath.Join(Config.RootPath, fn))
if err != nil {
logger.Logger.Warn("i18n fileModifiedCommand ioutil.ReadFile error", err)
return err
}
if len(buf) == 0 {
return nil
}
h := md5.New()
h.Reset()
h.Write(buf)
newCode := hex.EncodeToString(h.Sum(nil))
if newCode != hashCode {
logger.Logger.Trace("modified file name ======", fn)
kv := make(map[string]string)
err = json.Unmarshal(buf, &kv)
if err != nil {
logger.Logger.Warn("i18n Config.Init json.Unmarshal error", err)
return err
}
nameAndExt := strings.SplitN(fn, ".", 2)
if len(nameAndExt) == 2 {
lang := nameAndExt[0]
loc, exist := locales.getLocale(lang)
if exist {
loc.message = kv
} else {
loc = &locale{lang: lang, message: kv}
if loc != nil {
locales.Add(loc)
}
}
Config.hashCodes[fn] = newCode
}
}
return nil
}
func init() {
core.RegistePackage(&Config)
}

115
core/i18n/i18n.go Normal file
View File

@ -0,0 +1,115 @@
package i18n
import (
"fmt"
"reflect"
)
var (
locales = &localeStore{store: make(map[string]*locale)}
)
type locale struct {
id int
lang string
message map[string]string
}
type localeStore struct {
langs []string
store map[string]*locale
}
// Get locale from localeStore use specify lang string
func (d *localeStore) getLocale(lang string) (*locale, bool) {
if l, ok := d.store[lang]; ok {
return l, true
}
return nil, false
}
// Get target language string
func (d *localeStore) Get(lang, key string) (string, bool) {
if locale, ok := d.getLocale(lang); ok {
if value, ok := locale.message[key]; ok {
return value, true
}
}
return "", false
}
func (d *localeStore) Add(lc *locale) bool {
if _, ok := d.store[lc.lang]; ok {
return false
}
lc.id = len(d.langs)
d.langs = append(d.langs, lc.lang)
d.store[lc.lang] = lc
return true
}
// List all locale languages
func ListLangs() []string {
langs := make([]string, len(locales.langs))
copy(langs, locales.langs)
return langs
}
// Check language name if exist
func IsExist(lang string) bool {
_, ok := locales.store[lang]
return ok
}
// Check language name if exist
func IndexLang(lang string) int {
if lc, ok := locales.store[lang]; ok {
return lc.id
}
return -1
}
// Get language by index id
func GetLangByIndex(index int) string {
if index < 0 || index >= len(locales.langs) {
return ""
}
return locales.langs[index]
}
// A Locale describles the information of localization.
type Locale struct {
Lang string
}
// Tr translate content to target language.
func (l Locale) Tr(key string, args ...interface{}) string {
return Tr(l.Lang, key, args...)
}
// Index get lang index of LangStore
func (l Locale) Index() int {
return IndexLang(l.Lang)
}
// Tr translate content to target language.
func Tr(lang, key string, args ...interface{}) string {
value, ok := locales.Get(lang, key)
if ok && len(args) > 0 {
params := make([]interface{}, 0, len(args))
for _, arg := range args {
if arg != nil {
val := reflect.ValueOf(arg)
if val.Kind() == reflect.Slice {
for i := 0; i < val.Len(); i++ {
params = append(params, val.Index(i).Interface())
}
} else {
params = append(params, arg)
}
}
}
return fmt.Sprintf(value, params...)
}
return fmt.Sprintf(value)
}

9
core/ids.go Normal file
View File

@ -0,0 +1,9 @@
package core
const (
ObjId_RootId int = iota
ObjId_CoreId
ObjId_ExecutorId
ObjId_TimerId
ObjId_ProfileId
)

102
core/loader.go Normal file
View File

@ -0,0 +1,102 @@
package core
import (
"encoding/json"
"io"
"io/ioutil"
"path"
"mongo.games.com/goserver/core/logger"
)
type Package interface {
Name() string
Init() error
io.Closer
}
type ConfigFileEncryptorHook interface {
IsCipherText([]byte) bool
Encrypt([]byte) []byte
Decrtypt([]byte) []byte
}
var packages = make(map[string]Package)
var packagesLoaded = make(map[string]bool)
var configFileEH ConfigFileEncryptorHook
func RegistePackage(p Package) {
packages[p.Name()] = p
}
func IsPackageRegisted(name string) bool {
if _, exist := packages[name]; exist {
return true
}
return false
}
func IsPackageLoaded(name string) bool {
if _, exist := packagesLoaded[name]; exist {
return true
}
return false
}
func RegisterConfigEncryptor(h ConfigFileEncryptorHook) {
configFileEH = h
}
func LoadPackages(configFile string) {
//logger.Logger.Infof("Build time is: %s", BuildTime())
switch path.Ext(configFile) {
case ".json":
fileBuff, err := ioutil.ReadFile(configFile)
if err != nil {
logger.Logger.Errorf("Error while reading config file %s: %s", configFile, err)
break
}
if configFileEH != nil {
if configFileEH.IsCipherText(fileBuff) {
fileBuff = configFileEH.Decrtypt(fileBuff)
}
}
var fileData interface{}
err = json.Unmarshal(fileBuff, &fileData)
if err != nil {
break
}
fileMap := fileData.(map[string]interface{})
for name, pkg := range packages {
if moduleData, ok := fileMap[name]; ok {
if data, ok := moduleData.(map[string]interface{}); ok {
modelBuff, _ := json.Marshal(data)
err = json.Unmarshal(modelBuff, &pkg)
if err != nil {
logger.Logger.Errorf("Error while unmarshalling JSON from config file %s: %s", configFile, err)
} else {
err = pkg.Init()
if err != nil {
logger.Logger.Errorf("Error while initializing package %s: %s", pkg.Name(), err)
} else {
packagesLoaded[pkg.Name()] = true
logger.Logger.Infof("package [%16s] load success", pkg.Name())
}
}
} else {
logger.Logger.Errorf("Package %v init data unmarshal failed.", pkg.Name())
}
} else {
logger.Logger.Errorf("Package %v init data not exist.", pkg.Name())
}
}
default:
panic("Unsupported config file: " + configFile)
}
}
func ClosePackages() {
for _, pkg := range packages {
err := pkg.Close()
if err != nil {
logger.Logger.Errorf("Error while closing package %s: %s", pkg.Name(), err)
}
}
}

21
core/logger/ilogger.go Normal file
View File

@ -0,0 +1,21 @@
package logger
type ILogger interface {
Tracef(format string, params ...interface{})
Debugf(format string, params ...interface{})
Infof(format string, params ...interface{})
Warnf(format string, params ...interface{}) error
Errorf(format string, params ...interface{}) error
Criticalf(format string, params ...interface{}) error
Trace(v ...interface{})
Debug(v ...interface{})
Info(v ...interface{})
Warn(v ...interface{}) error
Error(v ...interface{}) error
Critical(v ...interface{}) error
Close()
Flush()
Closed() bool
}

107
core/logger/log.go Normal file
View File

@ -0,0 +1,107 @@
package logger
import (
"fmt"
"github.com/cihub/seelog"
)
var (
Logger seelog.LoggerInterface
)
func init() {
Logger, _ = seelog.LoggerFromConfigAsFile("logger.xml")
seelog.ReplaceLogger(Logger)
}
func Reload(fileName string) error {
newLogger, err := seelog.LoggerFromConfigAsFile(fileName)
if err != nil {
return err
}
if newLogger != nil {
Logger = newLogger
seelog.ReplaceLogger(Logger)
fmt.Println("Reload success")
}
return nil
}
func Tracef(format string, params ...interface{}) {
if Logger != nil {
Logger.Tracef(format, params...)
}
}
func Debugf(format string, params ...interface{}) {
if Logger != nil {
Logger.Debugf(format, params...)
}
}
func Infof(format string, params ...interface{}) {
if Logger != nil {
Logger.Infof(format, params...)
}
}
func Warnf(format string, params ...interface{}) error {
if Logger != nil {
return Logger.Warnf(format, params...)
}
return nil
}
func Errorf(format string, params ...interface{}) error {
if Logger != nil {
return Logger.Errorf(format, params...)
}
return nil
}
func Criticalf(format string, params ...interface{}) error {
if Logger != nil {
return Logger.Criticalf(format, params...)
}
return nil
}
func Trace(v ...interface{}) {
if Logger != nil {
Logger.Trace(v...)
}
}
func Debug(v ...interface{}) {
if Logger != nil {
Logger.Debug(v...)
}
}
func Info(v ...interface{}) {
if Logger != nil {
Logger.Info(v...)
}
}
func Warn(v ...interface{}) error {
if Logger != nil {
return Logger.Warn(v...)
}
return nil
}
func Error(v ...interface{}) error {
if Logger != nil {
return Logger.Error(v...)
}
return nil
}
func Critical(v ...interface{}) error {
if Logger != nil {
return Logger.Critical(v...)
}
return nil
}

42
core/module/config.go Normal file
View File

@ -0,0 +1,42 @@
package module
import (
"time"
"mongo.games.com/goserver/core"
"mongo.games.com/goserver/core/basic"
)
var Config = Configuration{}
type Configuration struct {
Options basic.Options
}
func (c *Configuration) Name() string {
return "module"
}
func (c *Configuration) Init() error {
if c.Options.QueueBacklog <= 0 {
c.Options.QueueBacklog = 1024
}
if c.Options.MaxDone <= 0 {
c.Options.MaxDone = 1024
}
if c.Options.Interval <= 0 {
c.Options.Interval = time.Millisecond * 10
} else {
c.Options.Interval = time.Millisecond * c.Options.Interval
}
return nil
}
func (c *Configuration) Close() error {
return nil
}
func init() {
core.RegistePackage(&Config)
}

13
core/module/module.go Normal file
View File

@ -0,0 +1,13 @@
package module
const (
ModuleName_Net string = "net-module"
ModuleName_Transact = "dtc-module"
)
type Module interface {
ModuleName() string
Init()
Update()
Shutdown()
}

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