testrig

package
v0.13.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 6, 2024 License: AGPL-3.0 Imports: 31 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Start action.GTSAction = func(ctx context.Context) error {
	var state state.State

	testrig.InitTestConfig()
	testrig.InitTestLog()

	parsedLangs, err := language.InitLangs(config.GetInstanceLanguages().TagStrs())
	if err != nil {
		return fmt.Errorf("error initializing languages: %w", err)
	}
	config.SetInstanceLanguages(parsedLangs)

	if err := tracing.Initialize(); err != nil {
		return fmt.Errorf("error initializing tracing: %w", err)
	}

	if err := metrics.Initialize(); err != nil {
		return fmt.Errorf("error initializing metrics: %w", err)
	}

	state.DB = testrig.NewTestDB(&state)

	state.Caches.Start()
	defer state.Caches.Stop()

	testrig.StandardDBSetup(state.DB, nil)

	if os.Getenv("GTS_STORAGE_BACKEND") == "s3" {
		var err error
		state.Storage, err = storage.NewS3Storage()
		if err != nil {
			return fmt.Errorf("error initializing storage: %w", err)
		}
	} else {
		state.Storage = testrig.NewInMemoryStorage()
	}
	testrig.StandardStorageSetup(state.Storage, "./testrig/media")

	state.Workers.Start()
	defer state.Workers.Stop()

	transportController := testrig.NewTestTransportController(&state, testrig.NewMockHTTPClient(func(req *http.Request) (*http.Response, error) {
		r := io.NopCloser(bytes.NewReader([]byte{}))
		return &http.Response{
			StatusCode: 200,
			Body:       r,
		}, nil
	}, ""))
	mediaManager := testrig.NewTestMediaManager(&state)
	federator := testrig.NewTestFederator(&state, transportController, mediaManager)

	emailSender := testrig.NewEmailSender("./web/template/", nil)
	typeConverter := typeutils.NewConverter(&state)
	filter := visibility.NewFilter(&state)

	state.Timelines.Home = timeline.NewManager(
		tlprocessor.HomeTimelineGrab(&state),
		tlprocessor.HomeTimelineFilter(&state, filter),
		tlprocessor.HomeTimelineStatusPrepare(&state, typeConverter),
		tlprocessor.SkipInsert(),
	)
	if err := state.Timelines.Home.Start(); err != nil {
		return fmt.Errorf("error starting home timeline: %s", err)
	}

	state.Timelines.List = timeline.NewManager(
		tlprocessor.ListTimelineGrab(&state),
		tlprocessor.ListTimelineFilter(&state, filter),
		tlprocessor.ListTimelineStatusPrepare(&state, typeConverter),
		tlprocessor.SkipInsert(),
	)
	if err := state.Timelines.List.Start(); err != nil {
		return fmt.Errorf("error starting list timeline: %s", err)
	}

	processor := testrig.NewTestProcessor(&state, federator, emailSender, mediaManager)

	router := testrig.NewTestRouter(state.DB)
	middlewares := []gin.HandlerFunc{
		middleware.AddRequestID(config.GetRequestIDHeader()),
	}
	if config.GetTracingEnabled() {
		middlewares = append(middlewares, tracing.InstrumentGin())
	}

	if config.GetMetricsEnabled() {
		middlewares = append(middlewares, metrics.InstrumentGin())
	}

	middlewares = append(middlewares, []gin.HandlerFunc{
		middleware.Logger(config.GetLogClientIP()),
		middleware.UserAgent(),
		middleware.CORS(),
		middleware.ExtraHeaders(),
	}...)

	cspExtraURIs := make([]string, 0)

	storageCSPUri, err := state.Storage.ProbeCSPUri(ctx)
	if err != nil {
		return fmt.Errorf("error deriving Content-Security-Policy uri from storage: %w", err)
	}

	if storageCSPUri != "" {
		cspExtraURIs = append(cspExtraURIs, storageCSPUri)
	}

	cspExtraURIs = append(cspExtraURIs, config.GetAdvancedCSPExtraURIs()...)

	middlewares = append(middlewares, middleware.ContentSecurityPolicy(cspExtraURIs...))

	router.AttachGlobalMiddleware(middlewares...)

	router.AttachNoRouteHandler(func(c *gin.Context) {
		apiutil.ErrorHandler(c, gtserror.NewErrorNotFound(errors.New(http.StatusText(http.StatusNotFound))), processor.InstanceGetV1)
	})

	// build router modules
	var idp oidc.IDP
	if config.GetOIDCEnabled() {
		idp, err = oidc.NewIDP(ctx)
		if err != nil {
			return fmt.Errorf("error creating oidc idp: %w", err)
		}
	}

	routerSession, err := state.DB.GetSession(ctx)
	if err != nil {
		return fmt.Errorf("error retrieving router session for session middleware: %w", err)
	}

	sessionName, err := middleware.SessionName()
	if err != nil {
		return fmt.Errorf("error generating session name for session middleware: %w", err)
	}

	var (
		authModule        = api.NewAuth(state.DB, processor, idp, routerSession, sessionName) // auth/oauth paths
		clientModule      = api.NewClient(state.DB, processor)                                // api client endpoints
		metricsModule     = api.NewMetrics()                                                  // Metrics endpoints
		fileserverModule  = api.NewFileserver(processor)                                      // fileserver endpoints
		wellKnownModule   = api.NewWellKnown(processor)                                       // .well-known endpoints
		nodeInfoModule    = api.NewNodeInfo(processor)                                        // nodeinfo endpoint
		activityPubModule = api.NewActivityPub(state.DB, processor)                           // ActivityPub endpoints
		webModule         = web.New(state.DB, processor)                                      // web pages + user profiles + settings panels etc
	)

	authModule.Route(router)
	clientModule.Route(router)
	metricsModule.Route(router)
	fileserverModule.Route(router)
	wellKnownModule.Route(router)
	nodeInfoModule.Route(router)
	activityPubModule.Route(router)
	activityPubModule.RoutePublicKey(router)
	webModule.Route(router)

	cleaner := cleaner.New(&state)

	gts := gotosocial.NewServer(state.DB, router, cleaner)
	if err := gts.Start(ctx); err != nil {
		return fmt.Errorf("error starting gotosocial service: %s", err)
	}

	sigs := make(chan os.Signal, 1)
	signal.Notify(sigs, os.Interrupt, syscall.SIGTERM)
	sig := <-sigs
	log.Infof(ctx, "received signal %s, shutting down", sig)

	testrig.StandardDBTeardown(state.DB)
	testrig.StandardStorageTeardown(state.Storage)

	if err := gts.Stop(ctx); err != nil {
		return fmt.Errorf("error closing gotosocial service: %s", err)
	}

	log.Info(ctx, "done! exiting...")
	return nil
}

Start creates and starts a gotosocial testrig server

Functions

This section is empty.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL