1
0
mirror of https://github.com/kataras/iris.git synced 2025-12-19 02:47:04 +00:00

ok make it cleaner, it's working well and blazing fast but I have to do a lot cleaning and commenting and docs as well before push it to master --- hope at christmas day, also thinking some internal ideas - the whole code is not ready to be readen by a third person yet.

Former-commit-id: 0b3fb2841d5032ff47bdca42a6f4ccfeb789ce3c
This commit is contained in:
Gerasimos (Makis) Maropoulos
2017-12-19 23:40:42 +02:00
parent 4261b5784a
commit c15763c556
11 changed files with 343 additions and 313 deletions

View File

@@ -35,7 +35,7 @@ type BeforeActivation interface {
type AfterActivation interface {
shared
DependenciesReadOnly() di.ValuesReadOnly
IsRequestScoped() bool
Singleton() bool
}
var (
@@ -85,14 +85,10 @@ func newControllerActivator(router router.Party, controller interface{}, depende
val = reflect.ValueOf(controller)
typ = val.Type()
// the full name of the controller, it's its type including the package path.
// the full name of the controller: its type including the package path.
fullName = getNameOf(typ)
)
// add the manual filled fields to the dependencies.
filledFieldValues := di.LookupNonZeroFieldsValues(val)
dependencies.AddValue(filledFieldValues...)
c := &ControllerActivator{
// give access to the Router to the end-devs if they need it for some reason,
// i.e register done handlers.
@@ -141,26 +137,16 @@ func (c *ControllerActivator) Router() router.Party {
return c.router
}
// IsRequestScoped returns new if each request has its own instance
// of the controller and it contains dependencies that are not manually
// filled by the struct initialization from the caller.
func (c *ControllerActivator) IsRequestScoped() bool {
// if the c.injector == nil means that is not seted to invalidate state,
// so it contains more fields that are filled by the end-dev.
// This "strange" check happens because the `IsRequestScoped` may
// called before the controller activation complete its task (see Handle: if c.injector == nil).
if c.injector == nil { // is nil so it contains more fields, maybe request-scoped or dependencies.
return true
// Singleton returns new if all incoming clients' requests
// have the same controller instance.
// This is done automatically by iris to reduce the creation
// of a new controller on each request, if the controller doesn't contain
// any unexported fields and all fields are services-like, static.
func (c *ControllerActivator) Singleton() bool {
if c.injector == nil {
panic("MVC: IsRequestScoped used on an invalid state the API gives access to it only `AfterActivation`, report this as bug")
}
if c.injector.Valid {
// if injector is not nil:
// if it is !Valid then all fields are manually filled by the end-dev (see `newControllerActivator`).
// if it is Valid then it's filled on the first `Handle`
// and it has more than one valid dependency from the registered values.
return true
}
// it's not nil and it's !Valid.
return false
return c.injector.State == di.Singleton
}
// checks if a method is already registered.
@@ -191,21 +177,16 @@ func (c *ControllerActivator) parseMethod(m reflect.Method) {
// register all available, exported methods to handlers if possible.
func (c *ControllerActivator) parseMethods() {
n := c.Type.NumMethod()
// wg := &sync.WaitGroup{}
// wg.Add(n)
for i := 0; i < n; i++ {
m := c.Type.Method(i)
c.parseMethod(m)
}
// wg.Wait()
}
func (c *ControllerActivator) activate() {
c.parseMethods()
}
var emptyIn = []reflect.Value{}
// Handle registers a route based on a http method, the route's path
// and a function name that belongs to the controller, it accepts
// a forth, optionally, variadic parameter which is the before handlers.
@@ -221,6 +202,30 @@ func (c *ControllerActivator) Handle(method, path, funcName string, middleware .
return nil
}
// Remember:
// we cannot simply do that and expect to work:
// hasStructInjector = c.injector != nil && c.injector.Valid
// hasFuncInjector = funcInjector != nil && funcInjector.Valid
// because
// the `Handle` can be called from `BeforeActivation` callbacks
// and before activation, the c.injector is nil because
// we may not have the dependencies binded yet. But if `c.injector.Valid`
// inside the Handelr works because it's set on the `activate()` method.
// To solve this we can make check on the FIRST `Handle`,
// if c.injector is nil, then set it with the current bindings,
// so the user should bind the dependencies needed before the `Handle`
// this is a logical flow, so we will choose that one ->
if c.injector == nil {
// first, set these bindings to the passed controller, they will be useless
// if the struct contains any dynamic value because this controller will
// be never fired as it's but we make that in order to get the length of the static
// matched dependencies of the struct.
c.injector = di.MakeStructInjector(c.Value, hijacker, typeChecker, c.dependencies...)
if c.injector.HasFields {
golog.Debugf("MVC dependencies of '%s':\n%s", c.fullName, c.injector.String())
}
}
// get the method from the controller type.
m, ok := c.Type.MethodByName(funcName)
if !ok {
@@ -238,77 +243,17 @@ func (c *ControllerActivator) Handle(method, path, funcName string, middleware .
return nil
}
// add this as a reserved method name in order to
// be sure that the same func will not be registered again, even if a custom .Handle later on.
c.reservedMethods = append(c.reservedMethods, funcName)
// get the function's input.
funcIn := getInputArgsFromFunc(m.Type)
// get the path parameters bindings from the template,
// use the function's input except the receiver which is the
// end-dev's controller pointer.
pathParams := getPathParamsForInput(tmpl.Params, funcIn[1:]...)
// get the function's input arguments' bindings.
funcDependencies := c.dependencies.Clone()
funcDependencies.AddValue(pathParams...)
funcDependencies.AddValues(pathParams...)
// fmt.Printf("for %s | values: %s\n", funcName, funcDependencies)
funcInjector := di.MakeFuncInjector(m.Func, hijacker, typeChecker, funcDependencies...)
// fmt.Printf("actual injector's inputs length: %d\n", funcInjector.Length)
// the element value, not the pointer, wil lbe used to create a
// new controller on each incoming request.
// Remember:
// we cannot simply do that and expect to work:
// hasStructInjector = c.injector != nil && c.injector.Valid
// hasFuncInjector = funcInjector != nil && funcInjector.Valid
// because
// the `Handle` can be called from `BeforeActivation` callbacks
// and before activation, the c.injector is nil because
// we may not have the dependencies binded yet. But if `c.injector.Valid`
// inside the Handelr works because it's set on the `activate()` method.
// To solve this we can make check on the FIRST `Handle`,
// if c.injector is nil, then set it with the current bindings,
// so the user should bind the dependencies needed before the `Handle`
// this is a logical flow, so we will choose that one ->
if c.injector == nil {
// check if manually filled + any dependencies are only static, if so
// and the total struct's fields are equal these static dependencies length
// then we don't need to create a new struct on each request.
//
// We use our custom NumFields here because the std "reflect" package
// checks only for the current struct and not for embedded's exported fields.
totalFieldsLength := di.NumFields(di.IndirectType(c.Type))
// first, set these bindings to the passed controller, they will be useless
// if the struct contains any dynamic value because this controller will
// be never fired as it's but we make that in order to get the length of the static
// matched dependencies of the struct.
c.injector = di.MakeStructInjector(c.Value, hijacker, typeChecker, c.dependencies...)
matchedStaticDependenciesLength := c.injector.InjectElemStaticOnly(di.IndirectValue(c.Value))
if c.injector.Valid {
golog.Debugf("MVC dependencies of '%s':\n%s", c.fullName, c.injector.String())
}
if matchedStaticDependenciesLength == totalFieldsLength {
// all fields are filled by the end-developer or via static dependencies (if context is there then it will be filled by the MakeStructInjector so we don't worry about it),
// the controller doesn't contain any other field neither any dynamic binding as well.
// Therefore we don't need to create a new controller each time.
// Set the c.injector now instead on the first `Handle` and set it to invalid state
// in order to `buildControllerHandler` ignore the
// creation of a new controller value on each incoming request.
c.injector = &di.StructInjector{Valid: false}
}
}
if funcInjector.Valid {
golog.Debugf("MVC dependencies of method '%s.%s':\n%s", c.fullName, funcName, funcInjector.String())
}
handler := buildControllerHandler(m, c.Type, c.Value, c.injector, funcInjector, funcIn)
handler := c.handlerOf(m, funcDependencies)
// register the handler now.
route := c.router.Handle(method, path, append(middleware, handler)...)
@@ -316,98 +261,55 @@ func (c *ControllerActivator) Handle(method, path, funcName string, middleware .
// change the main handler's name in order to respect the controller's and give
// a proper debug message.
route.MainHandlerName = fmt.Sprintf("%s.%s", c.fullName, funcName)
// add this as a reserved method name in order to
// be sure that the same func will not be registered again,
// even if a custom .Handle later on.
c.reservedMethods = append(c.reservedMethods, funcName)
}
return route
}
// buildControllerHandler has many many dublications but we do that to achieve the best
// performance possible, to use the information we know
// and calculate what is needed and what not in serve-time.
func buildControllerHandler(m reflect.Method, typ reflect.Type, initRef reflect.Value, structInjector *di.StructInjector, funcInjector *di.FuncInjector, funcIn []reflect.Type) context.Handler {
var (
hasStructInjector = structInjector != nil && structInjector.Valid
hasFuncInjector = funcInjector != nil && funcInjector.Valid
implementsBase = isBaseController(typ)
// we will make use of 'n' to make a slice of reflect.Value
// to pass into if the function has input arguments that
// are will being filled by the funcDependencies.
n = len(funcIn)
elemTyp = di.IndirectType(typ)
)
// if it doesn't implement the base controller,
// it may have struct injector and/or func injector.
if !implementsBase {
if !hasStructInjector {
// if the controller doesn't have a struct injector
// and the controller's fields are empty or all set-ed by the end-dev
// then we don't need a new controller instance, we use the passed controller instance.
if !hasFuncInjector {
return func(ctx context.Context) {
DispatchFuncResult(ctx, initRef.Method(m.Index).Call(emptyIn))
}
}
return func(ctx context.Context) {
in := make([]reflect.Value, n, n)
in[0] = initRef
funcInjector.Inject(&in, reflect.ValueOf(ctx))
if ctx.IsStopped() {
return
}
DispatchFuncResult(ctx, m.Func.Call(in))
}
}
// it has struct injector for sure and maybe a func injector.
if !hasFuncInjector {
return func(ctx context.Context) {
ctrl := reflect.New(elemTyp)
ctxValue := reflect.ValueOf(ctx)
elem := ctrl.Elem()
structInjector.InjectElem(elem, ctxValue)
if ctx.IsStopped() {
return
}
DispatchFuncResult(ctx, ctrl.Method(m.Index).Call(emptyIn))
}
}
// has struct injector and func injector.
return func(ctx context.Context) {
ctrl := reflect.New(elemTyp)
ctxValue := reflect.ValueOf(ctx)
elem := ctrl.Elem()
structInjector.InjectElem(elem, ctxValue)
if ctx.IsStopped() {
return
}
in := make([]reflect.Value, n, n)
in[0] = ctrl
funcInjector.Inject(&in, ctxValue)
if ctx.IsStopped() {
return
}
DispatchFuncResult(ctx, m.Func.Call(in))
}
var emptyIn = []reflect.Value{}
func (c *ControllerActivator) handlerOf(m reflect.Method, funcDependencies []reflect.Value) context.Handler {
// fmt.Printf("for %s | values: %s\n", funcName, funcDependencies)
funcInjector := di.MakeFuncInjector(m.Func, hijacker, typeChecker, funcDependencies...)
// fmt.Printf("actual injector's inputs length: %d\n", funcInjector.Length)
if funcInjector.Valid {
golog.Debugf("MVC dependencies of method '%s.%s':\n%s", c.fullName, m.Name, funcInjector.String())
}
// if implements the base controller,
// it may have struct injector and func injector as well.
return func(ctx context.Context) {
ctrl := reflect.New(elemTyp)
var (
implementsBase = isBaseController(c.Type)
hasBindableFields = c.injector.CanInject
hasBindableFuncInputs = funcInjector.Valid
call = m.Func.Call
)
if !implementsBase && !hasBindableFields && !hasBindableFuncInputs {
return func(ctx context.Context) {
DispatchFuncResult(ctx, call(c.injector.NewAsSlice()))
}
}
n := m.Type.NumIn()
return func(ctx context.Context) {
var (
ctrl = c.injector.New()
ctxValue reflect.Value
)
// inject struct fields first before the BeginRequest and EndRequest, if any,
// in order to be able to have access there.
if hasBindableFields {
ctxValue = reflect.ValueOf(ctx)
c.injector.InjectElem(ctrl.Elem(), ctxValue)
}
// check if has BeginRequest & EndRequest, before try to bind the method's inputs.
if implementsBase {
// the Interface(). is faster than MethodByName or pre-selected methods.
b := ctrl.Interface().(BaseController)
@@ -422,36 +324,20 @@ func buildControllerHandler(m reflect.Method, typ reflect.Type, initRef reflect.
defer b.EndRequest(ctx)
}
if !hasStructInjector && !hasFuncInjector {
DispatchFuncResult(ctx, ctrl.Method(m.Index).Call(emptyIn))
} else {
ctxValue := reflect.ValueOf(ctx)
if hasStructInjector {
elem := ctrl.Elem()
structInjector.InjectElem(elem, ctxValue)
if ctx.IsStopped() {
return
}
// we do this in order to reduce in := make...
// if not func input binders, we execute the handler with empty input args.
if !hasFuncInjector {
DispatchFuncResult(ctx, ctrl.Method(m.Index).Call(emptyIn))
}
}
// otherwise, it has one or more valid input binders,
// make the input and call the func using those.
if hasFuncInjector {
in := make([]reflect.Value, n, n)
in[0] = ctrl
funcInjector.Inject(&in, ctxValue)
if ctx.IsStopped() {
return
}
DispatchFuncResult(ctx, m.Func.Call(in))
if hasBindableFuncInputs {
// means that ctxValue is not initialized before by the controller's struct injector.
if !hasBindableFields {
ctxValue = reflect.ValueOf(ctx)
}
in := make([]reflect.Value, n, n)
in[0] = ctrl
funcInjector.Inject(&in, ctxValue)
DispatchFuncResult(ctx, call(in))
return
}
DispatchFuncResult(ctx, ctrl.Method(m.Index).Call(emptyIn))
}
}