func Serve()

in pkg/sdk/platform/server.go [54:146]


func Serve(ctx context.Context, srv *Server) error {
	// Generate an instance identifier
	appID := uniuri.NewLen(64)

	// Prepare logger
	log.Setup(ctx, &log.Options{
		Debug:    srv.Debug,
		AppName:  srv.Name,
		AppID:    appID,
		Version:  srv.Version,
		Revision: srv.Revision,
		LogLevel: srv.Instrumentation.Logs.Level,
	})

	// Preparing instrumentation
	instrumentationRouter := instrumentServer(ctx, srv)

	// Configure graceful restart
	upg := reloader.Create(ctx)

	var group run.Group

	// Instrumentation server
	{
		ln, err := upg.Listen(srv.Instrumentation.Network, srv.Instrumentation.Listen)
		if err != nil {
			return fmt.Errorf("platform: unable to start instrumentation server: %w", err)
		}

		server := &http.Server{
			Handler:           instrumentationRouter,
			ReadHeaderTimeout: time.Duration(srv.Instrumentation.TimeOut) * time.Second,
		}

		group.Add(
			func() error {
				log.For(ctx).Info("Starting instrumentation server", zap.String("address", ln.Addr().String()))
				return server.Serve(ln)
			},
			func(_ error) {
				log.For(ctx).Info("Shutting instrumentation server down")

				ctxShutdown, cancel := context.WithTimeout(ctx, 60*time.Second)
				defer cancel()

				log.CheckErrCtx(ctx, "Error raised while shutting down the server", server.Shutdown(ctxShutdown))
				log.SafeClose(server, "Unable to close instrumentation server")
			},
		)
	}

	// Initialiaze network listener
	ln, err := upg.Listen(srv.Network, srv.Address)
	if err != nil {
		return fmt.Errorf("unable to start server listener: %w", err)
	}

	// Initialize the component
	srv.Builder(ln, &group)

	// Setup signal handler
	{
		var (
			cancelInterrupt = make(chan struct{})
			ch              = make(chan os.Signal, 2)
		)
		defer close(ch)

		group.Add(
			func() error {
				signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)

				select {
				case <-ch:
					log.For(ctx).Info("Captured signal")
				case <-cancelInterrupt:
				}

				return nil
			},
			func(_ error) {
				close(cancelInterrupt)
				signal.Stop(ch)
			},
		)
	}

	// Register graceful restart handler
	upg.SetupGracefulRestart(ctx, group)

	// Run goroutine group
	return group.Run()
}