Skip to content

Commit

Permalink
Refactor job scheduler to use memdb for jobs (#782)
Browse files Browse the repository at this point in the history
* internal/job: Introduce Job & related types

* internal/state: Introduce new 'jobs' table

* internal/scheduler: Introduce general-purpose job scheduler

* internal/terraform/module(watcher+walker): Update references

* internal/langserver/handlers: Update references

* internal/terraform/module: Remove module manager & loader & queue

* internal/terraform/module: Repurpose old mod mgr test cases

In the old test we would be checking what *all* schemas are available for a given path after indexing via walker.

This part of API is however being deprecated in favour of more straightforward one (see state.ProviderSchemaStore -> ProviderSchema()) which picks the single most appropriate schema from a list of candidates and retains the decision logic as an implementation detail within it, so the whole list of candidates is not really available from the outside (by design), hence not something we should test from the outside.

ProviderSchemaStore itself already has plenty of tests testing the decision logic within, which is better place for testing this anyway.

* jobs benchmarks
  • Loading branch information
radeksimko authored Feb 24, 2022
1 parent 726a5fb commit 99e30e1
Show file tree
Hide file tree
Showing 68 changed files with 2,532 additions and 1,538 deletions.
5 changes: 1 addition & 4 deletions internal/cmd/completion_command.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ import (
ilsp "github.com/hashicorp/terraform-ls/internal/lsp"
lsp "github.com/hashicorp/terraform-ls/internal/protocol"
"github.com/hashicorp/terraform-ls/internal/state"
"github.com/hashicorp/terraform-ls/internal/terraform/module"
"github.com/mitchellh/cli"
)

Expand Down Expand Up @@ -113,9 +112,7 @@ func (c *CompletionCommand) Run(args []string) int {

ctx := context.Background()

modMgr := module.NewSyncModuleManager(ctx, fs, ss.DocumentStore, ss.Modules, ss.ProviderSchemas)

_, err = modMgr.AddModule(dh.Dir.Path())
err = ss.Modules.Add(dh.Dir.Path())
if err != nil {
c.Ui.Error(err.Error())
return 1
Expand Down
8 changes: 3 additions & 5 deletions internal/cmd/inspect_module_command.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
"github.com/hashicorp/terraform-ls/internal/logging"
"github.com/hashicorp/terraform-ls/internal/state"
"github.com/hashicorp/terraform-ls/internal/terraform/datadir"
"github.com/hashicorp/terraform-ls/internal/terraform/exec"
"github.com/hashicorp/terraform-ls/internal/terraform/module"
"github.com/mitchellh/cli"
)
Expand Down Expand Up @@ -93,10 +94,7 @@ func (c *InspectModuleCommand) inspect(rootPath string) error {

ctx := context.Background()

modMgr := module.NewSyncModuleManager(ctx, fs, ss.DocumentStore, ss.Modules, ss.ProviderSchemas)
modMgr.SetLogger(c.logger)

walker := module.SyncWalker(fs, ss.DocumentStore, modMgr)
walker := module.SyncWalker(fs, ss.DocumentStore, ss.Modules, ss.ProviderSchemas, ss.JobStore, exec.NewExecutor)
walker.SetLogger(c.logger)

ctx, cancel := ictx.WithSignalCancel(context.Background(),
Expand All @@ -109,7 +107,7 @@ func (c *InspectModuleCommand) inspect(rootPath string) error {
return err
}

modules, err := modMgr.ListModules()
modules, err := ss.Modules.List()
if err != nil {
return err
}
Expand Down
26 changes: 0 additions & 26 deletions internal/context/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,6 @@ var (
ctxTfExecLogPath = &contextKey{"terraform executor log path"}
ctxTfExecTimeout = &contextKey{"terraform execution timeout"}
ctxWatcher = &contextKey{"watcher"}
ctxModuleMngr = &contextKey{"module manager"}
ctxModuleFinder = &contextKey{"module finder"}
ctxModuleWalker = &contextKey{"module walker"}
ctxRootDir = &contextKey{"root directory"}
ctxCommandPrefix = &contextKey{"command prefix"}
Expand Down Expand Up @@ -68,18 +66,6 @@ func Watcher(ctx context.Context) (module.Watcher, error) {
return w, nil
}

func WithModuleManager(ctx context.Context, wm module.ModuleManager) context.Context {
return context.WithValue(ctx, ctxModuleMngr, wm)
}

func ModuleManager(ctx context.Context) (module.ModuleManager, error) {
wm, ok := ctx.Value(ctxModuleMngr).(module.ModuleManager)
if !ok {
return nil, missingContextErr(ctxModuleMngr)
}
return wm, nil
}

func WithTerraformExecPath(ctx context.Context, path string) context.Context {
return context.WithValue(ctx, ctxTfExecPath, path)
}
Expand All @@ -89,18 +75,6 @@ func TerraformExecPath(ctx context.Context) (string, bool) {
return path, ok
}

func WithModuleFinder(ctx context.Context, mf module.ModuleFinder) context.Context {
return context.WithValue(ctx, ctxModuleFinder, mf)
}

func ModuleFinder(ctx context.Context) (module.ModuleFinder, error) {
cf, ok := ctx.Value(ctxModuleFinder).(module.ModuleFinder)
if !ok {
return nil, missingContextErr(ctxModuleFinder)
}
return cf, nil
}

func WithRootDirectory(ctx context.Context, dir *string) context.Context {
return context.WithValue(ctx, ctxRootDir, dir)
}
Expand Down
40 changes: 40 additions & 0 deletions internal/job/job.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package job

import (
"context"

"github.com/hashicorp/terraform-ls/internal/document"
)

type Job struct {
// Func represents the job to execute
Func func(ctx context.Context) error

// Dir describes the directory which the job belongs to,
// which is used for deduplication of queued jobs (along with Type)
// and prioritization
Dir document.DirHandle

// Type describes type of the job (e.g. GetTerraformVersion),
// which is used for deduplication of queued jobs along with Dir.
Type string

// Defer is a function to execute after Func is executed
// and before the job is marked as done (StateDone).
// This can be used to schedule jobs dependent on the main job.
Defer DeferFunc
}

// DeferFunc represents a deferred function scheduling more jobs
// based on jobErr (any error returned from the main job).
// Newly queued job IDs should be returned to allow for synchronization.
type DeferFunc func(ctx context.Context, jobErr error) IDs

func (job Job) Copy() Job {
return Job{
Func: job.Func,
Dir: job.Dir,
Type: job.Type,
Defer: job.Defer,
}
}
19 changes: 19 additions & 0 deletions internal/job/job_id.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package job

type ID string

func (id ID) String() string {
return string(id)
}

type IDs []ID

func (ids IDs) Copy() IDs {
newIds := make([]ID, len(ids))

for i, id := range ids {
newIds[i] = id
}

return newIds
}
25 changes: 25 additions & 0 deletions internal/job/job_store.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package job

import (
"context"
"fmt"
)

type JobStore interface {
EnqueueJob(newJob Job) (ID, error)
WaitForJobs(ctx context.Context, ids ...ID) error
}

type jobStoreCtxKey struct{}

func WithJobStore(ctx context.Context, js JobStore) context.Context {
return context.WithValue(ctx, jobStoreCtxKey{}, js)
}

func JobStoreFromContext(ctx context.Context) (JobStore, error) {
js, ok := ctx.Value(jobStoreCtxKey{}).(JobStore)
if !ok {
return nil, fmt.Errorf("not found JobStore in context")
}
return js, nil
}
4 changes: 0 additions & 4 deletions internal/langserver/handlers/code_lens_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"fmt"
"path/filepath"
"testing"
"time"

"github.com/hashicorp/go-version"
tfjson "github.com/hashicorp/terraform-json"
Expand Down Expand Up @@ -262,9 +261,6 @@ variable "instances" {
type = number
}
`, submodUri.URI)})
// TODO remove once we support synchronous dependent tasks
// See https://github.com/hashicorp/terraform-ls/issues/719
time.Sleep(2 * time.Second)
ls.CallAndExpectResponse(t, &langserver.CallRequest{
Method: "textDocument/codeLens",
ReqParams: fmt.Sprintf(`{
Expand Down
7 changes: 7 additions & 0 deletions internal/langserver/handlers/command/handler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package command

import "github.com/hashicorp/terraform-ls/internal/state"

type CmdHandler struct {
StateStore *state.StateStore
}
19 changes: 9 additions & 10 deletions internal/langserver/handlers/command/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,16 @@ import (
"fmt"

"github.com/creachadair/jrpc2/code"
lsctx "github.com/hashicorp/terraform-ls/internal/context"
"github.com/hashicorp/terraform-ls/internal/document"
"github.com/hashicorp/terraform-ls/internal/langserver/cmd"
"github.com/hashicorp/terraform-ls/internal/langserver/errors"
"github.com/hashicorp/terraform-ls/internal/langserver/progress"
"github.com/hashicorp/terraform-ls/internal/state"
"github.com/hashicorp/terraform-ls/internal/terraform/module"
"github.com/hashicorp/terraform-ls/internal/uri"
)

func TerraformInitHandler(ctx context.Context, args cmd.CommandArgs) (interface{}, error) {
func (h *CmdHandler) TerraformInitHandler(ctx context.Context, args cmd.CommandArgs) (interface{}, error) {
dirUri, ok := args.GetString("uri")
if !ok || dirUri == "" {
return nil, fmt.Errorf("%w: expected module uri argument to be set", code.InvalidParams.Err())
Expand All @@ -26,15 +26,14 @@ func TerraformInitHandler(ctx context.Context, args cmd.CommandArgs) (interface{

dirHandle := document.DirHandleFromURI(dirUri)

modMgr, err := lsctx.ModuleManager(ctx)
mod, err := h.StateStore.Modules.ModuleByPath(dirHandle.Path())
if err != nil {
return nil, err
}

mod, err := modMgr.ModuleByPath(dirHandle.Path())
if err != nil {
if module.IsModuleNotFound(err) {
mod, err = modMgr.AddModule(dirHandle.Path())
if state.IsModuleNotFound(err) {
err = h.StateStore.Modules.Add(dirHandle.Path())
if err != nil {
return nil, err
}
mod, err = h.StateStore.Modules.ModuleByPath(dirHandle.Path())
if err != nil {
return nil, err
}
Expand Down
10 changes: 2 additions & 8 deletions internal/langserver/handlers/command/module_callers.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"sort"

"github.com/creachadair/jrpc2/code"
lsctx "github.com/hashicorp/terraform-ls/internal/context"
"github.com/hashicorp/terraform-ls/internal/langserver/cmd"
"github.com/hashicorp/terraform-ls/internal/uri"
)
Expand All @@ -22,7 +21,7 @@ type moduleCaller struct {
URI string `json:"uri"`
}

func ModuleCallersHandler(ctx context.Context, args cmd.CommandArgs) (interface{}, error) {
func (h *CmdHandler) ModuleCallersHandler(ctx context.Context, args cmd.CommandArgs) (interface{}, error) {
modUri, ok := args.GetString("uri")
if !ok || modUri == "" {
return nil, fmt.Errorf("%w: expected module uri argument to be set", code.InvalidParams.Err())
Expand All @@ -37,12 +36,7 @@ func ModuleCallersHandler(ctx context.Context, args cmd.CommandArgs) (interface{
return nil, err
}

mf, err := lsctx.ModuleFinder(ctx)
if err != nil {
return nil, err
}

modCallers, err := mf.CallersOfModule(modPath)
modCallers, err := h.StateStore.Modules.CallersOfModule(modPath)
if err != nil {
return nil, err
}
Expand Down
10 changes: 2 additions & 8 deletions internal/langserver/handlers/command/module_calls.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (
"strings"

"github.com/creachadair/jrpc2/code"
lsctx "github.com/hashicorp/terraform-ls/internal/context"
"github.com/hashicorp/terraform-ls/internal/langserver/cmd"
"github.com/hashicorp/terraform-ls/internal/terraform/datadir"
"github.com/hashicorp/terraform-ls/internal/uri"
Expand All @@ -29,7 +28,7 @@ type moduleCall struct {
DependentModules []moduleCall `json:"dependent_modules"`
}

func ModuleCallsHandler(ctx context.Context, args cmd.CommandArgs) (interface{}, error) {
func (h *CmdHandler) ModuleCallsHandler(ctx context.Context, args cmd.CommandArgs) (interface{}, error) {
response := moduleCallsResponse{
FormatVersion: moduleCallsVersion,
ModuleCalls: make([]moduleCall, 0),
Expand All @@ -49,12 +48,7 @@ func ModuleCallsHandler(ctx context.Context, args cmd.CommandArgs) (interface{},
return response, err
}

mm, err := lsctx.ModuleFinder(ctx)
if err != nil {
return response, err
}

found, _ := mm.ModuleByPath(modPath)
found, _ := h.StateStore.Modules.ModuleByPath(modPath)
if found == nil {
return response, nil
}
Expand Down
10 changes: 2 additions & 8 deletions internal/langserver/handlers/command/module_providers.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"fmt"

"github.com/creachadair/jrpc2/code"
lsctx "github.com/hashicorp/terraform-ls/internal/context"
"github.com/hashicorp/terraform-ls/internal/langserver/cmd"
op "github.com/hashicorp/terraform-ls/internal/terraform/module/operation"
"github.com/hashicorp/terraform-ls/internal/uri"
Expand All @@ -26,7 +25,7 @@ type providerRequirement struct {
DocsLink string `json:"docs_link,omitempty"`
}

func ModuleProvidersHandler(ctx context.Context, args cmd.CommandArgs) (interface{}, error) {
func (h *CmdHandler) ModuleProvidersHandler(ctx context.Context, args cmd.CommandArgs) (interface{}, error) {
response := moduleProvidersResponse{
FormatVersion: moduleProvidersVersion,
ProviderRequirements: make(map[string]providerRequirement),
Expand All @@ -47,12 +46,7 @@ func ModuleProvidersHandler(ctx context.Context, args cmd.CommandArgs) (interfac
return response, err
}

mm, err := lsctx.ModuleFinder(ctx)
if err != nil {
return response, err
}

mod, _ := mm.ModuleByPath(modPath)
mod, _ := h.StateStore.Modules.ModuleByPath(modPath)
if mod == nil {
return response, nil
}
Expand Down
Loading

0 comments on commit 99e30e1

Please sign in to comment.