Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion cmd/procyon/version.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,9 @@
package main

import (
"codnect.io/procyon"
"fmt"

"codnect.io/procyon"
"github.com/spf13/cobra"
)

Expand Down
8 changes: 8 additions & 0 deletions component/singleton.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@

package component

import "context"

// SingletonRegistry defines methods for managing singleton instances within the component system.
type SingletonRegistry interface {
// RegisterSingleton registers a singleton instance with the given name.
Expand All @@ -36,3 +38,9 @@ type SingletonRegistry interface {
// SingletonNames returns a slice of all registered singleton names.
SingletonNames() []string
}

// AfterSingleton is called once after singleton initialization, before lifecycle
// startup. Callbacks must not rely on the order of other completion callbacks.
type AfterSingleton interface {
SingletonsInitialized(ctx context.Context) error
}
6 changes: 5 additions & 1 deletion config.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,14 @@ package procyon
import (
"context"

"codnect.io/procyon/component"
"codnect.io/procyon/runtime"
"codnect.io/procyon/runtime/config"
)

// Compile-time check that configPropertiesProcessor implements component.AfterInitProcessor.
var _ component.AfterInitProcessor = (*configPropertiesProcessor)(nil)

// configPropertiesProcessor binds configuration properties to components
// that implement the config.Properties interface.
type configPropertiesProcessor struct {
Expand All @@ -41,7 +45,7 @@ func newConfigPropertiesProcessor(env runtime.Environment) *configPropertiesProc

// ProcessAfterInit binds configuration properties to the given component
// if it implements the config.Properties interface.
func (c *configPropertiesProcessor) ProcessAfterInit(_ context.Context, instance any) (any, error) {
func (c *configPropertiesProcessor) ProcessAfterInit(_ context.Context, _ string, instance any) (any, error) {
if properties, ok := instance.(config.Properties); ok {
binder := config.NewDefaultPropertyBinder(c.env.PropertySources())

Expand Down
25 changes: 25 additions & 0 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,10 @@ func (c *Context) doRefresh(ctx context.Context) (err error) {
return err
}

if err = c.invokeAfterSingletons(ctx); err != nil {
return err
}

if err = c.resolveLifecycleManager(ctx); err != nil {
return err
}
Expand Down Expand Up @@ -529,6 +533,27 @@ func (c *Context) initializeSingletons(ctx context.Context) error {
return nil
}

// invokeAfterSingletons invokes completion callbacks on singleton components
// whose definitions implement AfterSingleton. Callback order is unspecified.
func (c *Context) invokeAfterSingletons(ctx context.Context) error {
definitions := c.container.DefinitionsOf(reflect.TypeFor[component.AfterSingleton]())
for _, definition := range definitions {
if !definition.IsSingleton() {
continue
}
name := definition.Name()
instance, err := c.container.Resolve(ctx, name)
if err != nil {
return fmt.Errorf("resolve after-singleton component %q: %w", name, err)
}
callback := instance.(component.AfterSingleton)
if err := callback.SingletonsInitialized(ctx); err != nil {
return fmt.Errorf("after singletons initialized %q: %w", name, err)
}
}
return nil
}

// cancelRefresh rolls back a failed refresh attempt by stopping lifecycle management, destroying initialized
// singletons, and clearing context state.
func (c *Context) cancelRefresh(ctx context.Context) error {
Expand Down
6 changes: 3 additions & 3 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module codnect.io/procyon

go 1.24.0
go 1.27.0

require (
codnect.io/logy v1.0.2
Expand All @@ -16,6 +16,6 @@ require (
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/spf13/pflag v1.0.6 // indirect
github.com/stretchr/objx v0.5.2 // indirect
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
golang.org/x/sys v0.35.0 // indirect
github.com/xo/terminfo v1.2.0 // indirect
golang.org/x/sys v0.48.0 // indirect
)
4 changes: 4 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,14 @@ github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
github.com/xo/terminfo v1.2.0 h1:d0ZTOCpuGE0lwSAOs0zcJjwz3jWQyqcRt9XbGJpCOl4=
github.com/xo/terminfo v1.2.0/go.mod h1:lGzkSo8Fe7IRh/w+Gqz7n5mDog4FVXCj3gy/DYTBqio=
golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561 h1:MDc5xs78ZrZr3HMQugiXOAkSZtfTpbJLDr/lwfgO53E=
golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561/go.mod h1:cyybsKvd6eL0RnXn6p/Grxp8F5bW7iYuBgsNCOHpMYE=
golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI=
golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
Expand Down
23 changes: 15 additions & 8 deletions http/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,11 @@
package http

import (
"context"
"errors"
"net/http"
"time"
)

type serverContext interface {
context.Context
SetValue(key, value any)
Request() *ServerRequest
Response() *ServerResponse
}

// Context represents the context for an HTTP request and response.
type Context struct {
endpoint *Endpoint
Expand Down Expand Up @@ -117,6 +109,13 @@ func (c *Context) SetEndpoint(endpoint *Endpoint) {
// reset clears the context state and assigns a new HTTP request and response writer.
func (c *Context) reset(r *http.Request, w http.ResponseWriter) {
c.err = nil
c.endpoint = nil
c.req.ctx = c
c.res.ctx = c
c.req.pathValues.reset()
if c.res.headers == nil {
c.res.headers = make(Header)
}
clear(c.values)

c.req.nativeReq = r
Expand All @@ -130,6 +129,10 @@ func (c *Context) reset(r *http.Request, w http.ResponseWriter) {
clear(c.res.headers)
}

func (c *Context) private() {

}

// EndpointContext represents a typed context for an HTTP endpoint handler.
// It wraps the base Context and provides access to parsed input data
// from path parameters, query strings, and request body.
Expand Down Expand Up @@ -190,3 +193,7 @@ func (e *EndpointContext[I]) NativeContext() *Context {
func (e *EndpointContext[I]) setContext(ctx *Context) {
e.ctx = ctx
}

func (e *EndpointContext[I]) private() {

}
35 changes: 34 additions & 1 deletion http/dispatcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,44 @@

package http

import (
"context"
"fmt"
)

// Dispatcher interface represents a dispatcher that can process
// an HTTP request contained in the Context.
type Dispatcher interface {
Dispatch(ctx *Context) error
}

type RequestDispatcher struct {
delegate RequestDelegate
delegate RequestDelegate
dataSource *endpointDataSource
middlewares []Middleware
}

// newRequestDispatcher defers pipeline construction until mapping is complete.
func newRequestDispatcher(source *endpointDataSource, middlewares []Middleware) *RequestDispatcher {
return &RequestDispatcher{dataSource: source, middlewares: middlewares}
}

func (d *RequestDispatcher) SingletonsInitialized(ctx context.Context) error {
if d.delegate != nil {
return nil
}
d.dataSource.sealed = true
matcher, err := buildEndpointMatcher(d.dataSource)
if err != nil {
return err
}
for _, middleware := range d.middlewares {
if isNilResultValue(middleware) {
return fmt.Errorf("nil HTTP middleware")
}
}
d.delegate = buildPipeline(matcher, d.middlewares...)
return nil
}

// NewRequestDispatcher creates a new dispatcher by building
Expand All @@ -46,6 +76,9 @@ func NewRequestDispatcher(endpointMatcher EndpointMatcher, middlewares ...Middle

// Dispatch executes the built pipeline for the given request context.
func (d *RequestDispatcher) Dispatch(ctx *Context) error {
if d.delegate == nil {
return fmt.Errorf("HTTP dispatcher is not initialized")
}
return d.delegate(ctx)
}

Expand Down
88 changes: 87 additions & 1 deletion http/endpoint.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
package http

import (
"context"
"fmt"
"path"
"strings"
)
Expand Down Expand Up @@ -71,12 +73,26 @@ type EndpointDataSource interface {

type endpointDataSource struct {
endpoints []*Endpoint
sealed bool
}

func newEndpointDataSource() *endpointDataSource {
return &endpointDataSource{}
}

func NewEndpointDataSource(endpoints ...*Endpoint) EndpointDataSource {
return &endpointDataSource{endpoints: endpoints}
}

// register collects executable endpoints before the dispatcher is initialized.
func (s *endpointDataSource) register(endpoint *Endpoint) error {
if s.sealed {
return fmt.Errorf("endpoint mapping has already completed")
}
s.endpoints = append(s.endpoints, endpoint)
return nil
}

func (s *endpointDataSource) Endpoints() []*Endpoint {
return s.endpoints
}
Expand Down Expand Up @@ -159,7 +175,13 @@ func newEndpointGroup(prefix string) *EndpointGroup {

// MapAny maps a handler function to the specified path for all HTTP methods within the group.
func (g *EndpointGroup) MapAny(path string, handler Handler) *EndpointBuilder {
return g.MapMethods(path, nil, handler)
return g.MapMethods(path, []Method{
MethodGet,
MethodPost,
MethodPut,
MethodDelete,
MethodPatch,
}, handler)
}

// MapMethods maps a handler function to the specified path for the given HTTP methods within the group.
Expand Down Expand Up @@ -204,6 +226,70 @@ func (g *EndpointGroup) MapGroup(prefix string) *EndpointGroup {
return group
}

// endpointMappingProcessor collects mappings after the configurer's Init hook
// has completed, so mappings can use initialized component state.
type endpointMappingProcessor struct {
dataSource *endpointDataSource
executors *ResultExecutorRegistry
}

func newEndpointMappingProcessor(dataSource *endpointDataSource, executors *ResultExecutorRegistry) *endpointMappingProcessor {
if dataSource == nil {
panic("nil endpoint data source")
}

return &endpointMappingProcessor{dataSource: dataSource, executors: executors}
}

func (p *endpointMappingProcessor) ProcessAfterInit(ctx context.Context, name string, instance any) (any, error) {
configurer, ok := instance.(EndpointConfigurer)
if !ok {
return instance, nil
}

group := newEndpointGroup("/")
configurer.ConfigureEndpoints(group)

if err := p.collect(group); err != nil {
return nil, fmt.Errorf("map endpoints for %q: %w", name, err)
}
return instance, nil
}

func (p *endpointMappingProcessor) collect(group *EndpointGroup) error {
for _, route := range group.routes {
if isNilResultValue(route.handler) {
return fmt.Errorf("nil handler for %s", route.path)
}
handler := route.handler
delegate := RequestDelegate(func(ctx *Context) error {
result, err := handler.Handle(ctx)
if err != nil {
return err
}
if isNilResultValue(result) {
return nil
}
executor, ok := p.executors.Resolve(result)
if !ok {
return fmt.Errorf("no result executor for %T", result)
}
return executor.Execute(ctx, result)
})
for _, method := range route.methods {
if err := p.dataSource.register(NewEndpoint(method, route.path, delegate)); err != nil {
return err
}
}
}
for _, child := range group.children {
if err := p.collect(child); err != nil {
return err
}
}
return nil
}

// joinPaths joins multiple path elements into a single path string,
// ensuring that there is exactly one '/' separator between elements
// and preserving leading and trailing slashes.
Expand Down
Loading