Open source AI coding agent. Designed for large projects and real world tasks.
Go aiai-agentsai-developer-toolsai-toolsclicommand-linedeveloper-toolsgitgolanggpt-4llmopenaipolyglot-programmingterminalterminal-basedterminal-ui
[44;97;1m π€ Plandex [0;0;22m π Create deployment script for CloudFormation stack, Docker image, and ECS service update π New files: β’ infra/deploy.sh β’ infra/ecs-container-definitions.json
Dane Schneider1394ec233033
diff --git a/app/Dockerfile.server b/app/Dockerfile.servernew file mode 100644index 00000000..900110a9--- /dev/null+++ b/app/Dockerfile.server@@ -0,0 +1,16 @@+FROM golang:1.21++WORKDIR /app++COPY ./shared/go.mod ./shared/go.sum ./shared/+RUN cd shared && go mod download++COPY ./server/go.mod ./server/go.sum ./server/+RUN cd server && go mod download++COPY ./server ./server+COPY ./shared ./shared++RUN cd server && go build -o plandex-server .++CMD ["./server/plandex-server"]diff --git a/app/cli/cmd/branches.go b/app/cli/cmd/branches.gonew file mode 100644index 00000000..c7b5125e--- /dev/null+++ b/app/cli/cmd/branches.go@@ -0,0 +1,87 @@+package cmd++import (+ "fmt"+ "os"+ "plandex/api"+ "plandex/auth"+ "plandex/format"+ "plandex/lib"+ "plandex/term"+ "strconv"++ "github.com/fatih/color"+ "github.com/olekukonko/tablewriter"+ "github.com/spf13/cobra"+)++var branchesCmd = &cobra.Command{+ Use: "branches",+ Aliases: []string{"br"},+ Short: "List plan branches",+ Run: branches,+}++func init() {+ RootCmd.AddCommand(branchesCmd)+}++func branches(cmd *cobra.Command, args []string) {+ auth.MustResolveAuthWithOrg()+ lib.MustResolveProject()++ if lib.CurrentPlanId == "" {+ fmt.Println("π€·ββοΈ No current plan")+ return+ }++ branches, apiErr := api.Client.ListBranches(lib.CurrentPlanId)++ if apiErr != nil {+ fmt.Println("Error getting branches:", apiErr)+ return+ }++ table := tablewriter.NewWriter(os.Stdout)+ table.SetAutoWrapText(false)+ table.SetHeader([]string{"#", "Name", "Updated", "Created", "Context", "Convo"})++ for i, b := range branches {++ var name string+ if b.Id == lib.CurrentPlanId {+ name = color.New(color.Bold, color.FgGreen).Sprint(b.Name) + color.New(color.FgWhite).Sprint(" π current")+ } else {+ name = b.Name+ }++ row := []string{+ strconv.Itoa(i + 1),+ name,+ format.Time(b.UpdatedAt),+ format.Time(b.CreatedAt),+ strconv.Itoa(b.ContextTokens) + " πͺ",+ strconv.Itoa(b.ConvoTokens) + " πͺ",+ }++ var style []tablewriter.Colors+ if b.Name == lib.CurrentPlanId {+ style = []tablewriter.Colors{+ {tablewriter.FgGreenColor, tablewriter.Bold},+ }+ } else {+ style = []tablewriter.Colors{+ {tablewriter.FgHiWhiteColor, tablewriter.Bold},+ {tablewriter.FgHiWhiteColor},+ }+ }++ table.Rich(row, style)++ }+ table.Render()++ fmt.Println()+ term.PrintCmds("", "checkout")++}diff --git a/app/cli/cmd/checkout.go b/app/cli/cmd/checkout.gonew file mode 100644index 00000000..3481b0ce--- /dev/null+++ b/app/cli/cmd/checkout.go@@ -0,0 +1,137 @@+package cmd++import (+ "fmt"+ "os"+ "plandex/api"+ "plandex/auth"+ "plandex/lib"+ "plandex/term"+ "strings"++ "github.com/plandex/plandex/shared"+ "github.com/spf13/cobra"+)++const (+ OptCreateNewBranch = "Create a new branch"+)++var checkoutCmd = &cobra.Command{+ Use: "checkout",+ Aliases: []string{"co"},+ Short: "Checkout an existing plan branch or create a new one",+ Run: checkout,+ Args: cobra.MaximumNArgs(1),+}++func init() {+ RootCmd.AddCommand(checkoutCmd)+}++func checkout(cmd *cobra.Command, args []string) {+ auth.MustResolveAuthWithOrg()+ lib.MustResolveProject()++ if lib.CurrentPlanId == "" {+ fmt.Println("π€·ββοΈ No current plan")+ return+ }++ branches, apiErr := api.Client.ListBranches(lib.CurrentPlanId)++ if apiErr != nil {+ fmt.Println("Error getting branches:", apiErr)+ return+ }++ branchName := ""+ willCreate := false+ if len(args) > 0 {+ branchName = strings.TrimSpace(args[0])+ }++ if branchName == "" {+ opts := make([]string, len(branches))+ for i, branch := range branches {+ opts[i] = branch.Name+ }+ opts = append(opts, OptCreateNewBranch)++ selected, err := term.SelectFromList("Select a branch", opts)++ if err != nil {+ fmt.Println("Error selecting branch:", err)+ return+ }++ if selected == OptCreateNewBranch {+ branchName, err = term.GetUserStringInput("Branch name")+ if err != nil {+ fmt.Println("Error getting branch name:", err)+ return+ }+ willCreate = true+ } else {+ branchName = selected+ }+ }++ if branchName == "" {+ // should never happen+ fmt.Fprintln(os.Stderr, "π¨ Error selecting branch")+ os.Exit(1)+ }++ if !willCreate {+ found := false+ for _, branch := range branches {+ if branch.Name == branchName {+ found = true+ break+ }+ }++ if !found {+ fmt.Printf("π€·ββοΈ Branch '%s' not found\n", branchName)+ res, err := term.ConfirmYesNo("Create it now?")++ if err != nil {+ fmt.Println("Error getting user input:", err)+ }++ if res {+ willCreate = true+ } else {+ return+ }+ }+ }++ if willCreate {+ term.StartSpinner("π± Creating branch...")+ err := api.Client.CreateBranch(lib.CurrentPlanId, lib.CurrentBranch, shared.CreateBranchRequest{Name: branchName})++ if err != nil {+ term.StopSpinner()+ fmt.Println("Error creating branch:", err)+ return+ }++ term.StopSpinner()+ fmt.Printf("β Created branch '%s'\n", branchName)+ }++ err := lib.WriteCurrentBranch(branchName)++ if err != nil {+ fmt.Println("Error setting current branch:", err)+ return+ }++ fmt.Printf("β Checked out branch '%s'\n", branchName)++ fmt.Println()+ term.PrintCmds("", "load", "tell", "branches", "delete-branch")++}diff --git a/app/cli/cmd/delete_branch.go b/app/cli/cmd/delete_branch.gonew file mode 100644index 00000000..3ab199b6--- /dev/null+++ b/app/cli/cmd/delete_branch.go@@ -0,0 +1,96 @@+package cmd++import (+ "fmt"+ "plandex/api"+ "plandex/auth"+ "plandex/lib"+ "plandex/term"+ "strings"++ "github.com/spf13/cobra"+)++var deleteBranchCmd = &cobra.Command{+ Use: "delete-branch",+ Aliases: []string{""},+ Short: "Delete a plan branch",+ Run: deleteBranch,+}++func init() {+ RootCmd.AddCommand(deleteBranchCmd)+}++func deleteBranch(cmd *cobra.Command, args []string) {+ auth.MustResolveAuthWithOrg()+ lib.MustResolveProject()++ if lib.CurrentPlanId == "" {+ fmt.Println("π€·ββοΈ No current plan")+ return+ }++ branch := strings.TrimSpace(args[0])++ if branch == "main" {+ fmt.Println("π¨ Cannot delete main branch")+ return+ }++ branches, apiErr := api.Client.ListBranches(lib.CurrentPlanId)++ if apiErr != nil {+ fmt.Println("Error getting branches:", apiErr)+ return+ }++ if branch == "" {+ opts := make([]string, len(branches))+ for i, branch := range branches {+ if branch.Name == "main" {+ continue+ }+ opts[i] = branch.Name+ }++ if len(opts) == 0 {+ fmt.Println("π€·ββοΈ No branches to delete")+ return+ }++ sel, err := term.SelectFromList("Select a branch to delete", opts)++ if err != nil {+ fmt.Println("Error selecting branch:", err)+ return+ }++ branch = sel+ }++ found := false+ for _, b := range branches {+ if b.Name == branch {+ found = true+ break+ }+ }++ if !found {+ fmt.Printf("π€·ββοΈ Branch '%s' does not exist\n", branch)+ return+ }++ err := api.Client.DeleteBranch(lib.CurrentPlanId, branch)++ if err != nil {+ fmt.Println("Error deleting branch:", err)+ return+ }++ fmt.Printf("β Deleted branch '%s'\n", branch)++ fmt.Println()+ term.PrintCmds("", "branches")+}diff --git a/app/server/db/branch_helpers.go b/app/server/db/branch_helpers.gonew file mode 100644index 00000000..fc80e232--- /dev/null+++ b/app/server/db/branch_helpers.go@@ -0,0 +1,189 @@+package db++import (+ "database/sql"+ "fmt"+ "log"++ "github.com/plandex/plandex/shared"+)++func CreateBranch(plan *Plan, parentBranch *Branch, name string, tx *sql.Tx) (*Branch, error) {++ query := `INSERT INTO branches (org_id, owner_id, plan_id, parent_branch_id, name, status, context_tokens, convo_tokens)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)+ RETURNING id, created_at, updated_at`++ var (+ contextTokens int+ convoTokens int+ parentBranchId *string+ )++ if parentBranch != nil {+ parentBranchId = &parentBranch.Id++ contextTokens = parentBranch.ContextTokens+ convoTokens = parentBranch.ConvoTokens+ }++ branch := &Branch{+ OrgId: plan.OrgId,+ OwnerId: plan.OwnerId,+ PlanId: plan.Id,+ ParentBranchId: parentBranchId,+ Name: name,+ Status: shared.PlanStatusDraft,+ }++ var err error++ if tx == nil {+ err = Conn.QueryRow(+ query,+ branch.OrgId,+ branch.OwnerId,+ branch.PlanId,+ branch.ParentBranchId,+ branch.Name,+ branch.Status,+ contextTokens,+ convoTokens,+ ).Scan(+ &branch.Id,+ &branch.CreatedAt,+ &branch.UpdatedAt,+ )+ } else {+ err = tx.QueryRow(+ query,+ branch.OrgId,+ branch.OwnerId,+ branch.PlanId,+ branch.ParentBranchId,+ branch.Name,+ branch.Status,+ contextTokens,+ convoTokens,+ ).Scan(+ &branch.Id,+ &branch.CreatedAt,+ &branch.UpdatedAt,+ )+ }++ if err != nil {+ return nil, fmt.Errorf("error creating branch: %v", err)+ }++ // Create the git branch (except for main, which is created by default on repo init)+ if name != "main" {+ parentBranchName := "main"+ if parentBranch != nil {+ parentBranchName = parentBranch.Name+ }++ err = GitCreateBranch(plan.OrgId, plan.Id, parentBranchName, name)++ if err != nil {+ return nil, fmt.Errorf("error creating git branch: %v", err)+ }+ }++ err = IncActiveBranches(plan.Id, 1, tx)++ if err != nil {+ return nil, fmt.Errorf("error incrementing active branches: %v", err)+ }++ return branch, nil+}++func GetDbBranch(planId, name string) (*Branch, error) {+ var branch Branch+ err := Conn.Get(&branch, "SELECT * FROM branches WHERE plan_id = $1 AND name = $2", planId, name)++ if err != nil {+ if err == sql.ErrNoRows {+ return nil, nil+ }++ return nil, fmt.Errorf("error getting branch: %v", err)+ }++ return &branch, nil+}++func ListBranches(orgId, planId string) ([]*Branch, error) {+ var branches []*Branch+ err := Conn.Select(&branches, "SELECT * FROM branches WHERE plan_id = $1 ORDER BY created_at", planId)++ if err != nil {+ return nil, fmt.Errorf("error listing branches: %v", err)+ }++ gitBranches, err := GitListBranches(orgId, planId)++ if err != nil {+ return nil, fmt.Errorf("error listing git branches: %v", err)+ }++ var nameSet = make(map[string]bool)+ for _, name := range gitBranches {+ nameSet[name] = true+ }++ var res []*Branch+ for _, branch := range branches {+ if nameSet[branch.Name] {+ res = append(res, branch)+ }+ }++ return res, nil+}++func DeleteBranch(orgId, planId, branch string) error {+ tx, err := Conn.Begin()++ // Ensure that rollback is attempted in case of failure+ defer func() {+ if err != nil {+ if rbErr := tx.Rollback(); rbErr != nil {+ log.Printf("transaction rollback error: %v\n", rbErr)+ } else {+ log.Println("transaction rolled back")+ }+ }+ }()++ if err != nil {+ return fmt.Errorf("error starting transaction: %v", err)+ }++ _, err = tx.Exec("DELETE FROM branches WHERE plan_id = $1 AND name = $2", planId, branch)++ if err != nil {+ return fmt.Errorf("error deleting branch: %v", err)+ }++ err = IncActiveBranches(planId, -1, tx)++ if err != nil {+ return fmt.Errorf("error decrementing active branches: %v", err)+ }++ err = GitDeleteBranch(orgId, planId, branch)++ if err != nil {+ return fmt.Errorf("error deleting branch dir: %v", err)+ }++ err = tx.Commit()++ if err != nil {+ return fmt.Errorf("error committing transaction: %v", err)+ }++ return nil+}diff --git a/app/server/db/stream_helpers.go b/app/server/db/stream_helpers.gonew file mode 100644index 00000000..7b76ac0a--- /dev/null+++ b/app/server/db/stream_helpers.go@@ -0,0 +1,92 @@+package db++import (+ "database/sql"+ "fmt"+ "time"+)++func StoreModelStream(stream *ModelStream) error {+ query := `INSERT INTO model_streams (org_id, plan_id, internal_ip, branch) VALUES (:org_id, :plan_id, :internal_ip, :branch) RETURNING id, created_at`++ row, err := Conn.NamedQuery(query, stream)++ if err != nil {+ return fmt.Errorf("error storing model stream: %v", err)+ }++ defer row.Close()++ if row.Next() {+ var createdAt time.Time+ var id string+ if err := row.Scan(&id, &createdAt); err != nil {+ return fmt.Errorf("error storing model stream: %v", err)+ }++ stream.Id = id+ stream.CreatedAt = createdAt+ }++ return nil+}++func SetModelStreamFinished(id string) error {+ _, err := Conn.Exec("UPDATE model_streams SET finished_at = NOW() WHERE id = $1", id)++ if err != nil {+ return fmt.Errorf("error setting model stream finished: %v", err)+ }++ return nil+}++func GetActiveModelStream(planId, branch string) (*ModelStream, error) {+ var stream ModelStream+ err := Conn.Get(&stream, "SELECT * FROM model_streams WHERE plan_id = $1 AND branch = $2 AND finished_at IS NULL", planId, branch)++ if err != nil {+ if err == sql.ErrNoRows {+ return nil, nil+ }++ return nil, fmt.Errorf("error getting active model stream: %v", err)+ }++ return &stream, nil+}++// func StoreModelStreamSubscription(subscription *ModelStreamSubscription) error {+// query := `INSERT INTO model_stream_subscriptions (model_stream_id, org_id, plan_id, user_id, user_ip) VALUES (:model_stream_id, :org_id, :plan_id, :user_id, :user_ip) RETURNING id, created_at`++// row, err := Conn.NamedQuery(query, subscription)++// if err != nil {+// return fmt.Errorf("error storing model stream subscription: %v", err)+// }++// defer row.Close()++// if row.Next() {+// var createdAt time.Time+// var id string+// if err := row.Scan(&id, &createdAt); err != nil {+// return fmt.Errorf("error storing model stream subscription: %v", err)+// }++// subscription.Id = id+// subscription.CreatedAt = createdAt+// }++// return nil+// }++// func SetModelStreamSubscriptionFinished(id string) error {+// _, err := Conn.Exec("UPDATE model_stream_subscriptions SET finished_at = NOW() WHERE id = $1", id)++// if err != nil {+// return fmt.Errorf("error setting model stream subscription finished: %v", err)+// }++// return nil+// }diff --git a/app/server/db/summary_helpers.go b/app/server/db/summary_helpers.gonew file mode 100644index 00000000..0143aea8--- /dev/null+++ b/app/server/db/summary_helpers.go@@ -0,0 +1,42 @@+package db++import (+ "fmt"+ "time"+)++func GetPlanSummaries(planId string) ([]*ConvoSummary, error) {+ var summaries []*ConvoSummary++ err := Conn.Select(&summaries, "SELECT * FROM convo_summaries WHERE plan_id = $1 ORDER BY created_at", planId)++ if err != nil {+ return nil, fmt.Errorf("error getting plan summaries: %v", err)+ }+ return summaries, nil+}++func StoreSummary(summary *ConvoSummary) error {+ query := "INSERT INTO convo_summaries (org_id, plan_id, latest_convo_message_id, latest_convo_message_created_at, summary, tokens, num_messages) VALUES (:org_id, :plan_id, :latest_convo_message_id, :latest_convo_message_created_at, :summary, :tokens, :num_messages) RETURNING id, created_at"++ row, err := Conn.NamedQuery(query, summary)++ if err != nil {+ return fmt.Errorf("error storing summary: %v", err)+ }++ defer row.Close()++ if row.Next() {+ var createdAt time.Time+ var id string+ if err := row.Scan(&id, &createdAt); err != nil {+ return fmt.Errorf("error storing summary: %v", err)+ }++ summary.Id = id+ summary.CreatedAt = createdAt+ }++ return nil+}diff --git a/app/server/handlers/branches.go b/app/server/handlers/branches.gonew file mode 100644index 00000000..cd23ebc8--- /dev/null+++ b/app/server/handlers/branches.go@@ -0,0 +1,183 @@+package handlers++import (+ "encoding/json"+ "io"+ "log"+ "net/http"+ "plandex-server/db"++ "github.com/gorilla/mux"+ "github.com/plandex/plandex/shared"+)++func ListBranchesHandler(w http.ResponseWriter, r *http.Request) {+ log.Println("Received request for ListBranchesHandler")++ auth := authenticate(w, r, true)+ if auth == nil {+ return+ }++ vars := mux.Vars(r)+ planId := vars["planId"]++ log.Println("planId: ", planId)++ if authorizePlan(w, planId, auth) == nil {+ return+ }++ unlockFn := lockRepo(w, r, auth, db.LockScopeRead)+ if unlockFn == nil {+ return+ } else {+ defer (*unlockFn)()+ }++ branches, err := db.ListBranches(auth.OrgId, planId)++ if err != nil {+ log.Printf("Error getting branches: %v\n", err)+ http.Error(w, "Error getting branches: "+err.Error(), http.StatusInternalServerError)+ return+ }++ jsonBytes, err := json.Marshal(branches)++ if err != nil {+ log.Printf("Error marshalling branches: %v\n", err)+ http.Error(w, "Error marshalling branches: "+err.Error(), http.StatusInternalServerError)+ return+ }++ log.Println("Successfully retrieved branches")++ w.Write(jsonBytes)+}++func CreateBranchHandler(w http.ResponseWriter, r *http.Request) {+ log.Println("Received request for CreateBranchHandler")++ auth := authenticate(w, r, true)+ if auth == nil {+ return+ }++ vars := mux.Vars(r)+ planId := vars["planId"]+ branch := vars["branch"]++ log.Println("planId: ", planId)++ plan := authorizePlan(w, planId, auth)+ if plan == nil {+ return+ }++ body, err := io.ReadAll(r.Body)+ if err != nil {+ log.Printf("Error reading request body: %v\n", err)+ http.Error(w, "Error reading request body", http.StatusInternalServerError)+ return+ }+ defer func() {+ log.Println("Closing request body")+ r.Body.Close()+ }()++ var req shared.CreateBranchRequest+ if err := json.Unmarshal(body, &req); err != nil {+ log.Printf("Error parsing request body: %v\n", err)+ http.Error(w, "Error parsing request body ", http.StatusBadRequest)+ return+ }++ parentBranch, err := db.GetDbBranch(planId, branch)++ if err != nil {+ log.Printf("Error getting parent branch: %v\n", err)+ http.Error(w, "Error getting parent branch: "+err.Error(), http.StatusInternalServerError)+ return+ }++ unlockFn := lockRepo(w, r, auth, db.LockScopeWrite)+ if unlockFn == nil {+ return+ } else {+ defer (*unlockFn)()+ }++ tx, err := db.Conn.Begin()+ if err != nil {+ log.Printf("Error starting transaction: %v\n", err)+ http.Error(w, "Error starting transaction: "+err.Error(), http.StatusInternalServerError)+ return+ }++ _, err = db.CreateBranch(plan, parentBranch, req.Name, tx)++ if err != nil {+ log.Printf("Error creating branch: %v\n", err)+ http.Error(w, "Error creating branch: "+err.Error(), http.StatusInternalServerError)+ return+ }++ // commit the transaction+ if err := tx.Commit(); err != nil {+ log.Printf("Error committing transaction: %v\n", err)+ http.Error(w, "Error committing transaction: "+err.Error(), http.StatusInternalServerError)+ return+ }++ log.Println("Successfully created branch")+}++func DeleteBranchHandler(w http.ResponseWriter, r *http.Request) {+ log.Println("Received request for DeleteBranchHandler")++ auth := authenticate(w, r, true)+ if auth == nil {+ return+ }++ vars := mux.Vars(r)+ planId := vars["planId"]+ branch := vars["branch"]++ log.Println("planId: ", planId)++ if authorizePlan(w, planId, auth) == nil {+ return+ }++ if branch == "main" {+ log.Println("Cannot delete main branch")+ http.Error(w, "Cannot delete main branch", http.StatusBadRequest)+ return+ }++ repoLockId, err := db.LockRepo(auth.OrgId, auth.User.Id, planId, "main", db.LockScopeRead)+ if err != nil {+ log.Printf("Error locking repo: %v\n", err)+ http.Error(w, "Error locking repo: "+err.Error(), http.StatusInternalServerError)+ return+ }++ defer func() {+ err := db.UnlockRepo(repoLockId)+ if err != nil {+ log.Printf("Error unlocking repo: %v\n", err)+ }+ }()++ err = db.DeleteBranch(auth.OrgId, planId, branch)++ if err != nil {+ log.Printf("Error deleting branch: %v\n", err)+ http.Error(w, "Error deleting branch: "+err.Error(), http.StatusInternalServerError)+ return+ }++ log.Println("Successfully deleted branch")+}diff --git a/app/server/handlers/fs_helper.go b/app/server/handlers/fs_helper.gonew file mode 100644index 00000000..61f21777--- /dev/null+++ b/app/server/handlers/fs_helper.go@@ -0,0 +1,32 @@+package handlers++import (+ "log"+ "net/http"+ "plandex-server/db"+ "plandex-server/types"++ "github.com/gorilla/mux"+)++func lockRepo(w http.ResponseWriter, r *http.Request, auth *types.ServerAuth, scope db.LockScope) *func() {+ vars := mux.Vars(r)+ planId := vars["planId"]+ branch := vars["branch"]++ repoLockId, err := db.LockRepo(auth.OrgId, auth.User.Id, planId, branch, db.LockScopeRead)+ if err != nil {+ log.Printf("Error locking repo: %v\n", err)+ http.Error(w, "Error locking repo: "+err.Error(), http.StatusInternalServerError)+ return nil+ }++ fn := func() {+ err := db.UnlockRepo(repoLockId)+ if err != nil {+ log.Printf("Error unlocking repo: %v\n", err)+ }+ }++ return &fn+}diff --git a/app/server/handlers/proxy_helper.go b/app/server/handlers/proxy_helper.gonew file mode 100644index 00000000..c6a619cd--- /dev/null+++ b/app/server/handlers/proxy_helper.go@@ -0,0 +1,49 @@+package handlers++import (+ "io"+ "log"+ "net/http"+)++func proxyRequest(w http.ResponseWriter, originalRequest *http.Request, url string) {+ client := &http.Client{}++ // Create a new request based on the original request+ req, err := http.NewRequest(originalRequest.Method, url, originalRequest.Body)+ if err != nil {+ log.Printf("Error creating request for proxy: %v\n", err)+ http.Error(w, "Error creating request for proxy", http.StatusInternalServerError)+ return+ }++ // Copy the headers from the original request to the new request+ for name, headers := range originalRequest.Header {+ for _, h := range headers {+ req.Header.Add(name, h)+ }+ }++ // Make the request+ resp, err := client.Do(req)+ if err != nil {+ log.Printf("Error forwarding request: %v\n", err)+ http.Error(w, "Error forwarding request", http.StatusInternalServerError)+ return+ }+ defer resp.Body.Close()++ // Copy the response headers and status code+ for name, headers := range resp.Header {+ for _, h := range headers {+ w.Header().Add(name, h)+ }+ }+ w.WriteHeader(resp.StatusCode)++ // Copy the response body+ if _, err := io.Copy(w, resp.Body); err != nil {+ log.Printf("Error copying response body: %v\n", err)+ http.Error(w, "Error copying response body", http.StatusInternalServerError)+ }+}diff --git a/app/server/migrations/2024012400_streams.down.sql b/app/server/migrations/2024012400_streams.down.sqlnew file mode 100644index 00000000..e7ab7555--- /dev/null+++ b/app/server/migrations/2024012400_streams.down.sql@@ -0,0 +1,2 @@+DROP TABLE IF EXISTS model_streams;+-- DROP TABLE IF EXISTS model_stream_subscriptions;\ No newline at end of filediff --git a/app/server/migrations/2024012400_streams.up.sql b/app/server/migrations/2024012400_streams.up.sqlnew file mode 100644index 00000000..a8c27c7d--- /dev/null+++ b/app/server/migrations/2024012400_streams.up.sql@@ -0,0 +1,23 @@+CREATE TABLE IF NOT EXISTS model_streams (+ id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),+ org_id UUID NOT NULL REFERENCES orgs(id) ON DELETE CASCADE,+ plan_id UUID NOT NULL REFERENCES plans(id) ON DELETE CASCADE,+ branch VARCHAR(255) NOT NULL,+ internal_ip VARCHAR(45) NOT NULL,+ created_at TIMESTAMP NOT NULL DEFAULT NOW(),+ finished_at TIMESTAMP+);++CREATE UNIQUE INDEX model_streams_plan_idx ON model_streams(plan_id, branch, finished_at);++-- CREATE TABLE IF NOT EXISTS model_stream_subscriptions (+-- id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),+-- org_id UUID NOT NULL REFERENCES orgs(id) ON DELETE CASCADE,+-- plan_id UUID NOT NULL REFERENCES plans(id) ON DELETE CASCADE,+-- model_stream_id UUID NOT NULL REFERENCES model_streams(id) ON DELETE CASCADE,+-- user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,+-- user_ip VARCHAR(45) NOT NULL,+-- created_at TIMESTAMP NOT NULL DEFAULT NOW()+-- finished_at TIMESTAMP+-- );+diff --git a/app/server/migrations/2024012500_locks.down.sql b/app/server/migrations/2024012500_locks.down.sqlnew file mode 100644index 00000000..13a5a8ec--- /dev/null+++ b/app/server/migrations/2024012500_locks.down.sql@@ -0,0 +1 @@+DROP TABLE IF EXISTS repo_locks;\ No newline at end of filediff --git a/app/server/migrations/2024012500_locks.up.sql b/app/server/migrations/2024012500_locks.up.sqlnew file mode 100644index 00000000..755301ba--- /dev/null+++ b/app/server/migrations/2024012500_locks.up.sql@@ -0,0 +1,13 @@++CREATE UNLOGGED TABLE IF NOT EXISTS repo_locks (+ id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),+ org_id UUID NOT NULL REFERENCES orgs(id) ON DELETE CASCADE,+ user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,+ plan_id UUID NOT NULL REFERENCES plans(id) ON DELETE CASCADE,+ scope VARCHAR(1) NOT NULL,+ branch VARCHAR(255),+ created_at TIMESTAMP NOT NULL DEFAULT NOW()+);++CREATE INDEX repo_locks_plan_idx ON repo_locks(plan_id);+CREATE UNIQUE INDEX repo_locks_write_idx ON repo_locks(plan_id) WHERE scope = 'w';diff --git a/infra/deploy.sh b/infra/deploy.shnew file mode 100644index 00000000..5608563a--- /dev/null+++ b/infra/deploy.sh@@ -0,0 +1,56 @@+#!/bin/bash++# Set variables for the ECR repository and image tag+ECR_REPOSITORY=$(aws ecr describe-repositories --repository-names plandex-ecr-repository | jq -r '.repositories[0].repositoryUri')+IMAGE_TAG=$(git rev-parse --short HEAD)++# Function to deploy or update the CloudFormation stack using AWS CDK+deploy_or_update_stack() {+ # Check if the stack exists+ STACK_EXISTS=$(aws cloudformation describe-stacks --stack-name plandex-stack | jq -r '.Stacks | length')++ if [ "$STACK_EXISTS" -eq "0" ]; then+ # Deploy the stack if it does not exist+ npx cdk deploy "plandex-stack-*" --require-approval never+ else+ # Update the stack if it exists+ npx cdk deploy "plandex-stack-*" --require-approval never+ fi+}++# Function to build and push the Docker image to ECR+build_and_push_image() {+ # Login to ECR+ aws ecr get-login-password --region $(aws configure get region) | docker login --username AWS --password-stdin $ECR_REPOSITORY++ # Build the Docker image+ docker build -t plandex-server:$IMAGE_TAG -f app/Dockerfile.server .++ # Tag the image for the ECR repository+ docker tag plandex-server:$IMAGE_TAG $ECR_REPOSITORY:$IMAGE_TAG++ # Push the image to ECR+ docker push $ECR_REPOSITORY:$IMAGE_TAG+}++# Function to update the ECS service with the new Docker image+update_ecs_service() {+ # Replace placeholders in ecs-container-definitions.json with actual values+ sed -i "s|\${ECR_REPOSITORY_URI}|$ECR_REPOSITORY|g" ecs-container-definitions.json+ sed -i "s|\${IMAGE_TAG}|$IMAGE_TAG|g" ecs-container-definitions.json+ sed -i "s|\${AWS_REGION}|$(aws configure get region)|g" ecs-container-definitions.json+ # Register a new task definition with the new image+ TASK_DEF_ARN=$(aws ecs register-task-definition --family plandex-task-definition --container-definitions file://ecs-container-definitions.json | jq -r '.taskDefinition.taskDefinitionArn')++ # Update the ECS service to use the new task definition+ aws ecs update-service --cluster plandex-ecs-cluster --service plandex-fargate-service --task-definition $TASK_DEF_ARN+}++# Deploy or update the CloudFormation stack+deploy_or_update_stack++# Build and push the Docker image to ECR+build_and_push_image++# Update the ECS service with the new Docker image+update_ecs_servicediff --git a/infra/ecs-container-definitions.json b/infra/ecs-container-definitions.jsonnew file mode 100644index 00000000..b17b4446--- /dev/null+++ b/infra/ecs-container-definitions.json@@ -0,0 +1,36 @@+[+ {+ "name": "plandex-server",+ "image": "${ECR_REPOSITORY_URI}:${IMAGE_TAG}",+ "cpu": 256,+ "memory": 512,+ "essential": true,+ "portMappings": [+ {+ "containerPort": 80,+ "hostPort": 80+ }+ ],+ "environment": [+ {+ "name": "ECS_CONTAINER_STOP_TIMEOUT",+ "value": "60m"+ }+ ],+ "mountPoints": [+ {+ "sourceVolume": "plandex-efs-volume",+ "containerPath": "/plandex-server",+ "readOnly": false+ }+ ],+ "logConfiguration": {+ "logDriver": "awslogs",+ "options": {+ "awslogs-group": "/ecs/plandex-server",+ "awslogs-region": "${AWS_REGION}",+ "awslogs-stream-prefix": "ecs"+ }+ }+ }+]