Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ae1f347549 | |||
| 7e62ff6d9a | |||
| adcc9afe05 | |||
| 24d1e472a2 | |||
| da1b210865 | |||
| eadf630c61 | |||
| 4fb073a1ff | |||
| 9ddfa0c3c7 | |||
| a92e188f84 |
@@ -1,10 +1,16 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
"log"
|
"log"
|
||||||
|
"os/signal"
|
||||||
|
"syscall"
|
||||||
|
"time"
|
||||||
|
|
||||||
"moku-backend/internal/bootstrap"
|
"moku-backend/internal/bootstrap"
|
||||||
"moku-backend/internal/process"
|
"moku-backend/internal/jobs"
|
||||||
|
"moku-backend/internal/worker"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
@@ -18,9 +24,25 @@ func main() {
|
|||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
app.Logger.Info("worker ready", "service", app.ServiceName, "environment", app.Config.Environment)
|
jobStore := jobs.NewStore(app.Database)
|
||||||
|
runner := worker.NewRunner(jobStore, app.Logger, time.Second)
|
||||||
|
runner.Register(jobs.KindBootstrapStructureMaterialize, func(ctx context.Context, job jobs.Job) error {
|
||||||
|
var payload jobs.BootstrapStructureMaterializePayload
|
||||||
|
if len(job.Payload) > 0 {
|
||||||
|
if err := json.Unmarshal(job.Payload, &payload); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if err := process.WaitForShutdown(app.ServiceName, app.Logger); err != nil {
|
return bootstrap.NewService(app.Database, app.Config.POSIXRoot).ProcessBootstrapStructureMaterialization(ctx, payload.InstallationID)
|
||||||
|
})
|
||||||
|
|
||||||
|
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||||
|
defer stop()
|
||||||
|
|
||||||
|
app.Logger.Info("worker ready", "service", app.ServiceName, "environment", app.Config.Environment, "pollInterval", time.Second)
|
||||||
|
|
||||||
|
if err := runner.Run(ctx); err != nil {
|
||||||
app.Logger.Error("worker stopped", "error", err)
|
app.Logger.Error("worker stopped", "error", err)
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,64 @@
|
|||||||
|
-- +goose Up
|
||||||
|
|
||||||
|
CREATE TYPE bootstrap_materialization_status AS ENUM ('not_started', 'pending', 'running', 'succeeded', 'failed');
|
||||||
|
CREATE TYPE background_job_status AS ENUM ('pending', 'running', 'succeeded', 'failed');
|
||||||
|
|
||||||
|
ALTER TABLE installations
|
||||||
|
ADD COLUMN IF NOT EXISTS materialization_status bootstrap_materialization_status NOT NULL DEFAULT 'not_started',
|
||||||
|
ADD COLUMN IF NOT EXISTS materialization_error TEXT,
|
||||||
|
ADD COLUMN IF NOT EXISTS materialization_requested_at TIMESTAMPTZ,
|
||||||
|
ADD COLUMN IF NOT EXISTS materialization_started_at TIMESTAMPTZ,
|
||||||
|
ADD COLUMN IF NOT EXISTS materialization_finished_at TIMESTAMPTZ;
|
||||||
|
|
||||||
|
UPDATE installations
|
||||||
|
SET
|
||||||
|
materialization_status = CASE
|
||||||
|
WHEN is_bootstrapped THEN 'succeeded'::bootstrap_materialization_status
|
||||||
|
ELSE 'not_started'::bootstrap_materialization_status
|
||||||
|
END,
|
||||||
|
materialization_error = NULL,
|
||||||
|
materialization_requested_at = CASE
|
||||||
|
WHEN is_bootstrapped THEN COALESCE(bootstrapped_at, created_at, NOW())
|
||||||
|
ELSE NULL
|
||||||
|
END,
|
||||||
|
materialization_started_at = CASE
|
||||||
|
WHEN is_bootstrapped THEN COALESCE(bootstrapped_at, created_at, NOW())
|
||||||
|
ELSE NULL
|
||||||
|
END,
|
||||||
|
materialization_finished_at = CASE
|
||||||
|
WHEN is_bootstrapped THEN COALESCE(bootstrapped_at, created_at, NOW())
|
||||||
|
ELSE NULL
|
||||||
|
END
|
||||||
|
WHERE materialization_status = 'not_started'::bootstrap_materialization_status;
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS background_jobs (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
kind TEXT NOT NULL,
|
||||||
|
status background_job_status NOT NULL DEFAULT 'pending',
|
||||||
|
payload JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||||
|
attempts INTEGER NOT NULL DEFAULT 0,
|
||||||
|
max_attempts INTEGER NOT NULL DEFAULT 1,
|
||||||
|
available_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
started_at TIMESTAMPTZ,
|
||||||
|
finished_at TIMESTAMPTZ,
|
||||||
|
last_error TEXT,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_background_jobs_claim ON background_jobs (status, available_at, created_at);
|
||||||
|
|
||||||
|
-- +goose Down
|
||||||
|
|
||||||
|
DROP INDEX IF EXISTS idx_background_jobs_claim;
|
||||||
|
DROP TABLE IF EXISTS background_jobs;
|
||||||
|
|
||||||
|
ALTER TABLE installations
|
||||||
|
DROP COLUMN IF EXISTS materialization_finished_at,
|
||||||
|
DROP COLUMN IF EXISTS materialization_started_at,
|
||||||
|
DROP COLUMN IF EXISTS materialization_requested_at,
|
||||||
|
DROP COLUMN IF EXISTS materialization_error,
|
||||||
|
DROP COLUMN IF EXISTS materialization_status;
|
||||||
|
|
||||||
|
DROP TYPE IF EXISTS background_job_status;
|
||||||
|
DROP TYPE IF EXISTS bootstrap_materialization_status;
|
||||||
@@ -0,0 +1,159 @@
|
|||||||
|
package bootstrap
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
materializationNotStarted = "not_started"
|
||||||
|
materializationPending = "pending"
|
||||||
|
materializationRunning = "running"
|
||||||
|
materializationSucceeded = "succeeded"
|
||||||
|
materializationFailed = "failed"
|
||||||
|
)
|
||||||
|
|
||||||
|
type bootstrapStructurePrerequisites struct {
|
||||||
|
installation InstallationRecord
|
||||||
|
admin AdminSummary
|
||||||
|
}
|
||||||
|
|
||||||
|
func (service *Service) GetInstallation(ctx context.Context) (*InstallationRecord, error) {
|
||||||
|
record, err := scanInstallationRecord(service.db.Pool.QueryRow(ctx, `
|
||||||
|
SELECT
|
||||||
|
id::text,
|
||||||
|
name,
|
||||||
|
mode::text,
|
||||||
|
access::text,
|
||||||
|
protocol::text,
|
||||||
|
host,
|
||||||
|
is_bootstrapped,
|
||||||
|
materialization_status::text,
|
||||||
|
materialization_error
|
||||||
|
FROM installations
|
||||||
|
WHERE singleton = TRUE
|
||||||
|
LIMIT 1;
|
||||||
|
`))
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return &record, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func loadInstallation(ctx context.Context, tx pgx.Tx) (InstallationRecord, error) {
|
||||||
|
return scanInstallationRecord(tx.QueryRow(ctx, `
|
||||||
|
SELECT
|
||||||
|
id::text,
|
||||||
|
name,
|
||||||
|
mode::text,
|
||||||
|
access::text,
|
||||||
|
protocol::text,
|
||||||
|
host,
|
||||||
|
is_bootstrapped,
|
||||||
|
materialization_status::text,
|
||||||
|
materialization_error
|
||||||
|
FROM installations
|
||||||
|
WHERE singleton = TRUE
|
||||||
|
LIMIT 1;
|
||||||
|
`))
|
||||||
|
}
|
||||||
|
|
||||||
|
func updateBootstrappedInstallation(ctx context.Context, tx pgx.Tx) (InstallationRecord, error) {
|
||||||
|
return scanInstallationRecord(tx.QueryRow(ctx, `
|
||||||
|
UPDATE installations
|
||||||
|
SET
|
||||||
|
is_bootstrapped = TRUE,
|
||||||
|
bootstrapped_at = COALESCE(bootstrapped_at, NOW()),
|
||||||
|
materialization_status = 'pending'::bootstrap_materialization_status,
|
||||||
|
materialization_error = NULL,
|
||||||
|
materialization_requested_at = NOW(),
|
||||||
|
materialization_started_at = NULL,
|
||||||
|
materialization_finished_at = NULL,
|
||||||
|
updated_at = NOW()
|
||||||
|
WHERE singleton = TRUE
|
||||||
|
RETURNING
|
||||||
|
id::text,
|
||||||
|
name,
|
||||||
|
mode::text,
|
||||||
|
access::text,
|
||||||
|
protocol::text,
|
||||||
|
host,
|
||||||
|
is_bootstrapped,
|
||||||
|
materialization_status::text,
|
||||||
|
materialization_error;
|
||||||
|
`))
|
||||||
|
}
|
||||||
|
|
||||||
|
func scanInstallationRecord(row pgx.Row) (InstallationRecord, error) {
|
||||||
|
var record InstallationRecord
|
||||||
|
if err := row.Scan(
|
||||||
|
&record.ID,
|
||||||
|
&record.Name,
|
||||||
|
&record.Mode,
|
||||||
|
&record.Access,
|
||||||
|
&record.Protocol,
|
||||||
|
&record.Host,
|
||||||
|
&record.IsBootstrapped,
|
||||||
|
&record.MaterializationStatus,
|
||||||
|
&record.MaterializationError,
|
||||||
|
); err != nil {
|
||||||
|
return InstallationRecord{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if strings.TrimSpace(record.MaterializationStatus) == "" {
|
||||||
|
record.MaterializationStatus = materializationNotStarted
|
||||||
|
}
|
||||||
|
|
||||||
|
return record, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func loadPrimaryAdmin(ctx context.Context, tx pgx.Tx) (AdminSummary, error) {
|
||||||
|
var admin AdminSummary
|
||||||
|
if err := tx.QueryRow(ctx, `
|
||||||
|
SELECT id::text, email, display_name
|
||||||
|
FROM users
|
||||||
|
WHERE is_instance_admin = TRUE
|
||||||
|
ORDER BY created_at ASC
|
||||||
|
LIMIT 1;
|
||||||
|
`).Scan(&admin.ID, &admin.Email, &admin.DisplayName); err != nil {
|
||||||
|
return AdminSummary{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return admin, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (service *Service) loadBootstrapStructurePrerequisites(
|
||||||
|
ctx context.Context,
|
||||||
|
tx pgx.Tx,
|
||||||
|
) (bootstrapStructurePrerequisites, error) {
|
||||||
|
installation, err := loadInstallation(ctx, tx)
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
return bootstrapStructurePrerequisites{}, ErrInstallationNotConfigured
|
||||||
|
}
|
||||||
|
|
||||||
|
return bootstrapStructurePrerequisites{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
admin, err := loadPrimaryAdmin(ctx, tx)
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
return bootstrapStructurePrerequisites{}, ErrAdminNotConfigured
|
||||||
|
}
|
||||||
|
|
||||||
|
return bootstrapStructurePrerequisites{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return bootstrapStructurePrerequisites{
|
||||||
|
installation: installation,
|
||||||
|
admin: admin,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,180 @@
|
|||||||
|
package bootstrap
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"moku-backend/internal/jobs"
|
||||||
|
"moku-backend/internal/posixproj"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (service *Service) enqueueBootstrapStructureMaterialization(
|
||||||
|
ctx context.Context,
|
||||||
|
installation *InstallationRecord,
|
||||||
|
) error {
|
||||||
|
if installation == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
jobStore := jobs.NewStore(service.db)
|
||||||
|
if _, err := jobStore.Enqueue(ctx, jobs.EnqueueInput{
|
||||||
|
Kind: jobs.KindBootstrapStructureMaterialize,
|
||||||
|
Payload: jobs.BootstrapStructureMaterializePayload{
|
||||||
|
InstallationID: installation.ID,
|
||||||
|
},
|
||||||
|
}); err != nil {
|
||||||
|
failure := fmt.Sprintf("enqueue bootstrap materialization job: %v", err)
|
||||||
|
if markErr := service.markBootstrapMaterializationFailed(ctx, installation.ID, failure); markErr != nil {
|
||||||
|
return errors.Join(err, markErr)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The relational bootstrap write already committed successfully, so keep the
|
||||||
|
// response successful and surface the enqueue problem via materialization state.
|
||||||
|
installation.MaterializationStatus = materializationFailed
|
||||||
|
installation.MaterializationError = &failure
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (service *Service) ProcessBootstrapStructureMaterialization(ctx context.Context, installationID string) error {
|
||||||
|
trimmedInstallationID := strings.TrimSpace(installationID)
|
||||||
|
if trimmedInstallationID == "" {
|
||||||
|
return ErrInstallationNotConfigured
|
||||||
|
}
|
||||||
|
|
||||||
|
installation, err := service.GetInstallation(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if installation == nil || installation.ID != trimmedInstallationID {
|
||||||
|
return ErrInstallationNotConfigured
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := service.markBootstrapMaterializationRunning(ctx, trimmedInstallationID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := service.materializeBootstrapStructure(ctx, *installation); err != nil {
|
||||||
|
failure := strings.TrimSpace(err.Error())
|
||||||
|
if failure == "" {
|
||||||
|
failure = "bootstrap materialization failed"
|
||||||
|
}
|
||||||
|
|
||||||
|
if markErr := service.markBootstrapMaterializationFailed(ctx, trimmedInstallationID, failure); markErr != nil {
|
||||||
|
return errors.Join(err, markErr)
|
||||||
|
}
|
||||||
|
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return service.markBootstrapMaterializationSucceeded(ctx, trimmedInstallationID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (service *Service) materializeBootstrapStructure(ctx context.Context, installation InstallationRecord) error {
|
||||||
|
admin, err := service.GetAdmin(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if admin == nil {
|
||||||
|
return ErrAdminNotConfigured
|
||||||
|
}
|
||||||
|
|
||||||
|
organization, err := service.loadPrimaryOrganization(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if organization == nil {
|
||||||
|
return ErrBootstrapStructureMissing
|
||||||
|
}
|
||||||
|
|
||||||
|
department, err := service.loadPrimaryDepartment(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if department == nil {
|
||||||
|
return ErrBootstrapStructureMissing
|
||||||
|
}
|
||||||
|
|
||||||
|
team, err := service.loadPrimaryTeam(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if team == nil {
|
||||||
|
return ErrBootstrapStructureMissing
|
||||||
|
}
|
||||||
|
|
||||||
|
project, err := service.loadPrimaryProject(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if project == nil {
|
||||||
|
return ErrBootstrapStructureMissing
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := service.ensureBootstrapPOSIXSkeleton(
|
||||||
|
installation,
|
||||||
|
AdminSummary{ID: admin.ID, Email: admin.Email, DisplayName: admin.DisplayName},
|
||||||
|
namedRecord{ID: organization.ID, Name: organization.Name, Slug: organization.Slug},
|
||||||
|
namedRecord{ID: department.ID, Name: department.Name, Slug: department.Slug},
|
||||||
|
namedRecord{ID: team.ID, Name: team.Name, Slug: team.Slug},
|
||||||
|
namedRecord{ID: project.ID, Name: project.Name, Slug: project.Slug},
|
||||||
|
); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return service.rebuildProjection(ctx)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (service *Service) rebuildProjection(ctx context.Context) error {
|
||||||
|
if err := posixproj.NewProjector(service.db, service.posixRoot).Rebuild(ctx); err != nil {
|
||||||
|
return fmt.Errorf("rebuild POSIX projection: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (service *Service) markBootstrapMaterializationRunning(ctx context.Context, installationID string) error {
|
||||||
|
_, err := service.db.Pool.Exec(ctx, `
|
||||||
|
UPDATE installations
|
||||||
|
SET
|
||||||
|
materialization_status = 'running'::bootstrap_materialization_status,
|
||||||
|
materialization_error = NULL,
|
||||||
|
materialization_started_at = NOW(),
|
||||||
|
materialization_finished_at = NULL,
|
||||||
|
updated_at = NOW()
|
||||||
|
WHERE id = $1::uuid;
|
||||||
|
`, strings.TrimSpace(installationID))
|
||||||
|
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (service *Service) markBootstrapMaterializationSucceeded(ctx context.Context, installationID string) error {
|
||||||
|
_, err := service.db.Pool.Exec(ctx, `
|
||||||
|
UPDATE installations
|
||||||
|
SET
|
||||||
|
materialization_status = 'succeeded'::bootstrap_materialization_status,
|
||||||
|
materialization_error = NULL,
|
||||||
|
materialization_finished_at = NOW(),
|
||||||
|
updated_at = NOW()
|
||||||
|
WHERE id = $1::uuid;
|
||||||
|
`, strings.TrimSpace(installationID))
|
||||||
|
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (service *Service) markBootstrapMaterializationFailed(ctx context.Context, installationID, failure string) error {
|
||||||
|
_, err := service.db.Pool.Exec(ctx, `
|
||||||
|
UPDATE installations
|
||||||
|
SET
|
||||||
|
materialization_status = 'failed'::bootstrap_materialization_status,
|
||||||
|
materialization_error = $2,
|
||||||
|
materialization_finished_at = NOW(),
|
||||||
|
updated_at = NOW()
|
||||||
|
WHERE id = $1::uuid;
|
||||||
|
`, strings.TrimSpace(installationID), strings.TrimSpace(failure))
|
||||||
|
|
||||||
|
return err
|
||||||
|
}
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
package bootstrap
|
||||||
|
|
||||||
|
import "context"
|
||||||
|
|
||||||
|
func (service *Service) GetState(ctx context.Context) (BootstrapState, error) {
|
||||||
|
installation, err := service.GetInstallation(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return BootstrapState{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
admin, err := service.GetAdmin(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return BootstrapState{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
structure, err := service.GetStructure(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return BootstrapState{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return BootstrapState{
|
||||||
|
Installation: installation,
|
||||||
|
Admin: admin,
|
||||||
|
Structure: structure,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (service *Service) GetAppShellState(ctx context.Context) (AppShellState, error) {
|
||||||
|
installation, err := service.GetInstallation(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return AppShellState{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
admin, err := service.GetAdmin(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return AppShellState{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
organizations, err := service.listOrganizations(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return AppShellState{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
departments, err := service.listDepartments(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return AppShellState{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
teams, err := service.listTeams(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return AppShellState{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
projects, err := service.listProjects(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return AppShellState{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
workspaces, err := service.listWorkspaces(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return AppShellState{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return AppShellState{
|
||||||
|
Installation: installation,
|
||||||
|
Admin: admin,
|
||||||
|
Organizations: organizations,
|
||||||
|
Departments: departments,
|
||||||
|
Teams: teams,
|
||||||
|
Projects: projects,
|
||||||
|
Workspaces: workspaces,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -2,11 +2,73 @@ package bootstrap
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
type fakeRow struct {
|
||||||
|
scan func(dest ...any) error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (row fakeRow) Scan(dest ...any) error {
|
||||||
|
return row.scan(dest...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestScanInstallationRecordDefaultsMaterializationStatus(t *testing.T) {
|
||||||
|
record, err := scanInstallationRecord(fakeRow{scan: func(dest ...any) error {
|
||||||
|
*(dest[0].(*string)) = "installation-1"
|
||||||
|
*(dest[1].(*string)) = "MangoPig"
|
||||||
|
*(dest[2].(*string)) = "personal"
|
||||||
|
*(dest[3].(*string)) = "local"
|
||||||
|
*(dest[4].(*string)) = "http"
|
||||||
|
*(dest[5].(*string)) = "localhost"
|
||||||
|
*(dest[6].(*bool)) = true
|
||||||
|
*(dest[7].(*string)) = ""
|
||||||
|
*(dest[8].(**string)) = nil
|
||||||
|
return nil
|
||||||
|
}})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("scanInstallationRecord: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if record.MaterializationStatus != materializationNotStarted {
|
||||||
|
t.Fatalf("expected default materialization status %q, got %q", materializationNotStarted, record.MaterializationStatus)
|
||||||
|
}
|
||||||
|
if record.MaterializationError != nil {
|
||||||
|
t.Fatalf("expected nil materialization error, got %#v", record.MaterializationError)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestScanInstallationRecordPreservesMaterializationFields(t *testing.T) {
|
||||||
|
failure := "projection rebuild failed"
|
||||||
|
|
||||||
|
record, err := scanInstallationRecord(fakeRow{scan: func(dest ...any) error {
|
||||||
|
*(dest[0].(*string)) = "installation-2"
|
||||||
|
*(dest[1].(*string)) = "MangoPig"
|
||||||
|
*(dest[2].(*string)) = "personal"
|
||||||
|
*(dest[3].(*string)) = "local"
|
||||||
|
*(dest[4].(*string)) = "http"
|
||||||
|
*(dest[5].(*string)) = "localhost"
|
||||||
|
*(dest[6].(*bool)) = true
|
||||||
|
*(dest[7].(*string)) = materializationFailed
|
||||||
|
*(dest[8].(**string)) = &failure
|
||||||
|
return nil
|
||||||
|
}})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("scanInstallationRecord: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if record.MaterializationStatus != materializationFailed {
|
||||||
|
t.Fatalf("expected materialization status %q, got %q", materializationFailed, record.MaterializationStatus)
|
||||||
|
}
|
||||||
|
if record.MaterializationError == nil || *record.MaterializationError != failure {
|
||||||
|
t.Fatalf("expected materialization error %q, got %#v", failure, record.MaterializationError)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestEnsureBootstrapPOSIXSkeletonInitializesEmptyRoot(t *testing.T) {
|
func TestEnsureBootstrapPOSIXSkeletonInitializesEmptyRoot(t *testing.T) {
|
||||||
rootPath := filepath.Join(t.TempDir(), "POSIX")
|
rootPath := filepath.Join(t.TempDir(), "POSIX")
|
||||||
t.Setenv("POSIX_ROOT", rootPath)
|
t.Setenv("POSIX_ROOT", rootPath)
|
||||||
@@ -58,6 +120,10 @@ func TestEnsureBootstrapPOSIXSkeletonInitializesEmptyRoot(t *testing.T) {
|
|||||||
filepath.Join(rootPath, "users", "settings.json"),
|
filepath.Join(rootPath, "users", "settings.json"),
|
||||||
filepath.Join(rootPath, "users", "data.json"),
|
filepath.Join(rootPath, "users", "data.json"),
|
||||||
filepath.Join(rootPath, "users", "personals"),
|
filepath.Join(rootPath, "users", "personals"),
|
||||||
|
filepath.Join(rootPath, "users", "personals", "personal-ronald", "settings.json"),
|
||||||
|
filepath.Join(rootPath, "users", "personals", "personal-ronald", "layout.json"),
|
||||||
|
filepath.Join(rootPath, "users", "personals", "personal-ronald", "home.json"),
|
||||||
|
filepath.Join(rootPath, "users", "personals", "personal-ronald", "tree"),
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, path := range requiredPaths {
|
for _, path := range requiredPaths {
|
||||||
@@ -101,6 +167,25 @@ func TestEnsureBootstrapPOSIXSkeletonInitializesEmptyRoot(t *testing.T) {
|
|||||||
if usersSettings["primaryAdminId"] != "admin-1" {
|
if usersSettings["primaryAdminId"] != "admin-1" {
|
||||||
t.Fatalf("expected primary admin id admin-1, got %#v", usersSettings["primaryAdminId"])
|
t.Fatalf("expected primary admin id admin-1, got %#v", usersSettings["primaryAdminId"])
|
||||||
}
|
}
|
||||||
|
|
||||||
|
personalSettings := readJSONFileForTest[map[string]any](t, filepath.Join(rootPath, "users", "personals", "personal-ronald", "settings.json"))
|
||||||
|
if personalSettings["type"] != "personal" {
|
||||||
|
t.Fatalf("expected personal settings type personal, got %#v", personalSettings["type"])
|
||||||
|
}
|
||||||
|
if personalSettings["name"] != "Ronald" {
|
||||||
|
t.Fatalf("expected personal name Ronald, got %#v", personalSettings["name"])
|
||||||
|
}
|
||||||
|
if personalSettings["slug"] != "ronald" {
|
||||||
|
t.Fatalf("expected personal slug ronald, got %#v", personalSettings["slug"])
|
||||||
|
}
|
||||||
|
|
||||||
|
personalHome := readJSONFileForTest[map[string]any](t, filepath.Join(rootPath, "users", "personals", "personal-ronald", "home.json"))
|
||||||
|
if personalHome["type"] != "personal-home" {
|
||||||
|
t.Fatalf("expected personal home type personal-home, got %#v", personalHome["type"])
|
||||||
|
}
|
||||||
|
if personalHome["title"] != "Ronald's Home" {
|
||||||
|
t.Fatalf("expected personal home title Ronald's Home, got %#v", personalHome["title"])
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCreateProjectHierarchyFolderOnDiskCreatesExpectedFolderShape(t *testing.T) {
|
func TestCreateProjectHierarchyFolderOnDiskCreatesExpectedFolderShape(t *testing.T) {
|
||||||
@@ -142,6 +227,9 @@ func TestCreateProjectHierarchyFolderOnDiskCreatesExpectedFolderShape(t *testing
|
|||||||
}
|
}
|
||||||
|
|
||||||
folderPayload := readJSONFileForTest[map[string]any](t, filepath.Join(createdFolderPath, "folder.json"))
|
folderPayload := readJSONFileForTest[map[string]any](t, filepath.Join(createdFolderPath, "folder.json"))
|
||||||
|
if strings.TrimSpace(asStringForTest(folderPayload["id"])) == "" {
|
||||||
|
t.Fatalf("expected created folder to have stable id, got %#v", folderPayload["id"])
|
||||||
|
}
|
||||||
if folderPayload["name"] != "Design System" {
|
if folderPayload["name"] != "Design System" {
|
||||||
t.Fatalf("expected folder name Design System, got %#v", folderPayload["name"])
|
t.Fatalf("expected folder name Design System, got %#v", folderPayload["name"])
|
||||||
}
|
}
|
||||||
@@ -258,6 +346,9 @@ func TestRenameProjectHierarchyFolderOnDiskRenamesFolderShape(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
folderPayload := readJSONFileForTest[map[string]any](t, filepath.Join(renamedFolderPath, "folder.json"))
|
folderPayload := readJSONFileForTest[map[string]any](t, filepath.Join(renamedFolderPath, "folder.json"))
|
||||||
|
if strings.TrimSpace(asStringForTest(folderPayload["id"])) == "" {
|
||||||
|
t.Fatalf("expected renamed folder to preserve stable id, got %#v", folderPayload["id"])
|
||||||
|
}
|
||||||
if folderPayload["name"] != "Platform Design" {
|
if folderPayload["name"] != "Platform Design" {
|
||||||
t.Fatalf("expected renamed folder name Platform Design, got %#v", folderPayload["name"])
|
t.Fatalf("expected renamed folder name Platform Design, got %#v", folderPayload["name"])
|
||||||
}
|
}
|
||||||
@@ -310,11 +401,155 @@ func TestRenameProjectTreeFolderOnDiskRenamesFolderShape(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestMoveProjectHierarchyFolderOnDiskMovesFolderToNewParent(t *testing.T) {
|
||||||
|
rootPath := filepath.Join(t.TempDir(), "POSIX")
|
||||||
|
service := NewService(nil, rootPath)
|
||||||
|
|
||||||
|
err := service.ensureBootstrapPOSIXSkeleton(
|
||||||
|
InstallationRecord{ID: "installation-1", Name: "MangoPig", Mode: "personal", Access: "local", Protocol: "http", Host: "localhost", IsBootstrapped: true},
|
||||||
|
AdminSummary{ID: "admin-1", Email: "ronald@example.com", DisplayName: "Ronald"},
|
||||||
|
namedRecord{ID: "org-1", Name: "Primary Organization", Slug: "primary-organization"},
|
||||||
|
namedRecord{ID: "dept-1", Name: "Primary Department", Slug: "primary-department"},
|
||||||
|
namedRecord{ID: "team-1", Name: "Primary Team", Slug: "primary-team"},
|
||||||
|
namedRecord{ID: "project-1", Name: "Primary Project", Slug: "primary-project"},
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("ensure bootstrap POSIX skeleton: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
designPath, _, err := service.createProjectHierarchyFolderOnDisk("primary-project", "", "Design")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("create design folder: %v", err)
|
||||||
|
}
|
||||||
|
operationsPath, _, err := service.createProjectHierarchyFolderOnDisk("primary-project", "", "Operations")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("create operations folder: %v", err)
|
||||||
|
}
|
||||||
|
researchPath, _, err := service.createProjectHierarchyFolderOnDisk("primary-project", designPath, "Research")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("create research folder: %v", err)
|
||||||
|
}
|
||||||
|
nestedPath, _, err := service.createProjectHierarchyFolderOnDisk("primary-project", researchPath, "Interview Notes")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("create nested folder: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
previousPath, movedPath, err := service.moveProjectHierarchyFolderOnDisk("primary-project", researchPath, operationsPath)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("moveProjectHierarchyFolderOnDisk: %v", err)
|
||||||
|
}
|
||||||
|
if previousPath != researchPath {
|
||||||
|
t.Fatalf("expected previous path %s, got %s", researchPath, previousPath)
|
||||||
|
}
|
||||||
|
if movedPath != "projects/project-primary-project/children/folder-operations/children/folder-research" {
|
||||||
|
t.Fatalf("unexpected moved path: %s", movedPath)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := os.Stat(filepath.Join(rootPath, filepath.FromSlash(researchPath))); !os.IsNotExist(err) {
|
||||||
|
t.Fatalf("expected previous folder path to be gone, got err=%v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
movedFolderPath := filepath.Join(rootPath, filepath.FromSlash(movedPath))
|
||||||
|
if _, err := os.Stat(filepath.Join(movedFolderPath, "children", filepath.Base(nestedPath))); err != nil {
|
||||||
|
t.Fatalf("expected nested child folder to move with moved parent: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
folderPayload := readJSONFileForTest[map[string]any](t, filepath.Join(movedFolderPath, "folder.json"))
|
||||||
|
if strings.TrimSpace(asStringForTest(folderPayload["id"])) == "" {
|
||||||
|
t.Fatalf("expected moved folder to preserve stable id, got %#v", folderPayload["id"])
|
||||||
|
}
|
||||||
|
if folderPayload["name"] != "Research" {
|
||||||
|
t.Fatalf("expected moved folder name Research, got %#v", folderPayload["name"])
|
||||||
|
}
|
||||||
|
if folderPayload["slug"] != "research" {
|
||||||
|
t.Fatalf("expected moved folder slug research, got %#v", folderPayload["slug"])
|
||||||
|
}
|
||||||
|
if folderPayload["type"] != "folder" {
|
||||||
|
t.Fatalf("expected moved folder type folder, got %#v", folderPayload["type"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMoveProjectTreeFolderOnDiskMovesFolderToNewParent(t *testing.T) {
|
||||||
|
rootPath := filepath.Join(t.TempDir(), "POSIX")
|
||||||
|
service := NewService(nil, rootPath)
|
||||||
|
|
||||||
|
err := service.ensureBootstrapPOSIXSkeleton(
|
||||||
|
InstallationRecord{ID: "installation-1", Name: "MangoPig", Mode: "personal", Access: "local", Protocol: "http", Host: "localhost", IsBootstrapped: true},
|
||||||
|
AdminSummary{ID: "admin-1", Email: "ronald@example.com", DisplayName: "Ronald"},
|
||||||
|
namedRecord{ID: "org-1", Name: "Primary Organization", Slug: "primary-organization"},
|
||||||
|
namedRecord{ID: "dept-1", Name: "Primary Department", Slug: "primary-department"},
|
||||||
|
namedRecord{ID: "team-1", Name: "Primary Team", Slug: "primary-team"},
|
||||||
|
namedRecord{ID: "project-1", Name: "Primary Project", Slug: "primary-project"},
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("ensure bootstrap POSIX skeleton: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
docsPath, _, err := service.createProjectTreeFolderOnDisk("primary-project", "", "Docs")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("create docs folder: %v", err)
|
||||||
|
}
|
||||||
|
archivePath, _, err := service.createProjectTreeFolderOnDisk("primary-project", "", "Archive")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("create archive folder: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
previousPath, movedPath, err := service.moveProjectTreeFolderOnDisk("primary-project", docsPath, archivePath)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("moveProjectTreeFolderOnDisk: %v", err)
|
||||||
|
}
|
||||||
|
if previousPath != docsPath {
|
||||||
|
t.Fatalf("expected previous path %s, got %s", docsPath, previousPath)
|
||||||
|
}
|
||||||
|
if movedPath != "projects/project-primary-project/tree/folder-archive/children/folder-docs" {
|
||||||
|
t.Fatalf("unexpected moved path: %s", movedPath)
|
||||||
|
}
|
||||||
|
|
||||||
|
folderPayload := readJSONFileForTest[map[string]any](t, filepath.Join(rootPath, filepath.FromSlash(movedPath), "folder.json"))
|
||||||
|
if folderPayload["name"] != "Docs" {
|
||||||
|
t.Fatalf("expected moved folder name Docs, got %#v", folderPayload["name"])
|
||||||
|
}
|
||||||
|
if folderPayload["slug"] != "docs" {
|
||||||
|
t.Fatalf("expected moved folder slug docs, got %#v", folderPayload["slug"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMoveProjectHierarchyFolderOnDiskRejectsDescendantTarget(t *testing.T) {
|
||||||
|
rootPath := filepath.Join(t.TempDir(), "POSIX")
|
||||||
|
service := NewService(nil, rootPath)
|
||||||
|
|
||||||
|
err := service.ensureBootstrapPOSIXSkeleton(
|
||||||
|
InstallationRecord{ID: "installation-1", Name: "MangoPig", Mode: "personal", Access: "local", Protocol: "http", Host: "localhost", IsBootstrapped: true},
|
||||||
|
AdminSummary{ID: "admin-1", Email: "ronald@example.com", DisplayName: "Ronald"},
|
||||||
|
namedRecord{ID: "org-1", Name: "Primary Organization", Slug: "primary-organization"},
|
||||||
|
namedRecord{ID: "dept-1", Name: "Primary Department", Slug: "primary-department"},
|
||||||
|
namedRecord{ID: "team-1", Name: "Primary Team", Slug: "primary-team"},
|
||||||
|
namedRecord{ID: "project-1", Name: "Primary Project", Slug: "primary-project"},
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("ensure bootstrap POSIX skeleton: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
parentPath, _, err := service.createProjectHierarchyFolderOnDisk("primary-project", "", "Parent")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("create parent folder: %v", err)
|
||||||
|
}
|
||||||
|
childPath, _, err := service.createProjectHierarchyFolderOnDisk("primary-project", parentPath, "Child")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("create child folder: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
_, _, err = service.moveProjectHierarchyFolderOnDisk("primary-project", parentPath, childPath)
|
||||||
|
if !errors.Is(err, ErrInvalidProjectFolderMove) {
|
||||||
|
t.Fatalf("expected ErrInvalidProjectFolderMove, got %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestBuildProjectHierarchyFolderTreeBuildsNestedStructure(t *testing.T) {
|
func TestBuildProjectHierarchyFolderTreeBuildsNestedStructure(t *testing.T) {
|
||||||
rows := []projectHierarchyFolderRow{
|
rows := []projectHierarchyFolderRow{
|
||||||
{Path: "projects/project-primary-project/children/folder-design", ParentPath: projectHierarchyRootPath("primary-project"), Label: "Design"},
|
{ID: "folder-design-id", Path: "projects/project-primary-project/children/folder-design", ParentPath: projectHierarchyRootPath("primary-project"), Label: "Design"},
|
||||||
{Path: "projects/project-primary-project/children/folder-design/children/folder-research", ParentPath: "projects/project-primary-project/children/folder-design/children", Label: "Research"},
|
{ID: "folder-research-id", Path: "projects/project-primary-project/children/folder-design/children/folder-research", ParentPath: "projects/project-primary-project/children/folder-design/children", Label: "Research"},
|
||||||
{Path: "projects/project-primary-project/children/folder-ops", ParentPath: projectHierarchyRootPath("primary-project"), Label: "Ops"},
|
{ID: "folder-ops-id", Path: "projects/project-primary-project/children/folder-ops", ParentPath: projectHierarchyRootPath("primary-project"), Label: "Ops"},
|
||||||
}
|
}
|
||||||
|
|
||||||
folders := buildProjectHierarchyFolderTree(rows, projectHierarchyRootPath("primary-project"))
|
folders := buildProjectHierarchyFolderTree(rows, projectHierarchyRootPath("primary-project"))
|
||||||
@@ -327,6 +562,64 @@ func TestBuildProjectHierarchyFolderTreeBuildsNestedStructure(t *testing.T) {
|
|||||||
if len(folders[0].Children) != 1 || folders[0].Children[0].Label != "Research" {
|
if len(folders[0].Children) != 1 || folders[0].Children[0].Label != "Research" {
|
||||||
t.Fatalf("unexpected nested folder structure: %#v", folders[0].Children)
|
t.Fatalf("unexpected nested folder structure: %#v", folders[0].Children)
|
||||||
}
|
}
|
||||||
|
if folders[0].ID != "folder-design-id" || folders[0].Path != "projects/project-primary-project/children/folder-design" {
|
||||||
|
t.Fatalf("expected design folder to retain stable id/path, got %#v", folders[0])
|
||||||
|
}
|
||||||
|
if folders[0].Children[0].ID != "folder-research-id" || folders[1].ID != "folder-ops-id" {
|
||||||
|
t.Fatalf("expected nested/top-level folder ids to be preserved, got %#v / %#v", folders[0].Children[0], folders[1])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestApplyProjectHierarchyFolderOrderingOrdersRootAndChildrenByStableID(t *testing.T) {
|
||||||
|
folders := []ProjectHierarchyFolderRecord{
|
||||||
|
{
|
||||||
|
ID: "folder-design-id",
|
||||||
|
Path: "projects/project-primary-project/children/folder-design",
|
||||||
|
Label: "Design",
|
||||||
|
Children: []ProjectHierarchyFolderRecord{
|
||||||
|
{ID: "folder-research-id", Path: "projects/project-primary-project/children/folder-design/children/folder-research", Label: "Research"},
|
||||||
|
{ID: "folder-assets-id", Path: "projects/project-primary-project/children/folder-design/children/folder-assets", Label: "Assets"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ID: "folder-ops-id", Path: "projects/project-primary-project/children/folder-ops", Label: "Ops"},
|
||||||
|
{ID: "folder-qa-id", Path: "projects/project-primary-project/children/folder-qa", Label: "QA"},
|
||||||
|
}
|
||||||
|
|
||||||
|
ordered := applyProjectHierarchyFolderOrdering(folders, map[string][]string{
|
||||||
|
projectFolderOrderRootKey: {"folder-qa-id", "folder-design-id"},
|
||||||
|
"folder-design-id": {"folder-assets-id", "folder-research-id"},
|
||||||
|
})
|
||||||
|
|
||||||
|
if len(ordered) != 3 {
|
||||||
|
t.Fatalf("expected 3 ordered root folders, got %d", len(ordered))
|
||||||
|
}
|
||||||
|
if ordered[0].ID != "folder-qa-id" || ordered[1].ID != "folder-design-id" || ordered[2].ID != "folder-ops-id" {
|
||||||
|
t.Fatalf("unexpected ordered root ids: %#v", ordered)
|
||||||
|
}
|
||||||
|
if len(ordered[1].Children) != 2 {
|
||||||
|
t.Fatalf("expected design folder children to be preserved, got %#v", ordered[1].Children)
|
||||||
|
}
|
||||||
|
if ordered[1].Children[0].ID != "folder-assets-id" || ordered[1].Children[1].ID != "folder-research-id" {
|
||||||
|
t.Fatalf("unexpected ordered child ids: %#v", ordered[1].Children)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInsertFolderOrderReordersWithinSameParent(t *testing.T) {
|
||||||
|
folderOrder := map[string][]string{
|
||||||
|
projectFolderOrderRootKey: {"folder-a", "folder-b", "folder-c"},
|
||||||
|
}
|
||||||
|
|
||||||
|
insertFolderOrder(folderOrder, "", "folder-c", 0)
|
||||||
|
|
||||||
|
got := folderOrder[projectFolderOrderRootKey]
|
||||||
|
if len(got) != 3 || got[0] != "folder-c" || got[1] != "folder-a" || got[2] != "folder-b" {
|
||||||
|
t.Fatalf("unexpected reordered root children: %#v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func asStringForTest(value any) string {
|
||||||
|
text, _ := value.(string)
|
||||||
|
return text
|
||||||
}
|
}
|
||||||
|
|
||||||
func readJSONFileForTest[T any](t *testing.T, path string) T {
|
func readJSONFileForTest[T any](t *testing.T, path string) T {
|
||||||
|
|||||||
@@ -14,16 +14,26 @@ import (
|
|||||||
|
|
||||||
type createProjectFolderRequest struct {
|
type createProjectFolderRequest struct {
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
ParentFolderID string `json:"parentFolderId"`
|
ParentFolderPath string `json:"parentFolderId"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type renameProjectFolderRequest struct {
|
type renameProjectFolderRequest struct {
|
||||||
FolderID string `json:"folderId"`
|
FolderPath string `json:"folderId"`
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type deleteProjectFolderRequest struct {
|
type deleteProjectFolderRequest struct {
|
||||||
FolderID string `json:"folderId"`
|
FolderPath string `json:"folderId"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Keep the existing JSON contract for the frontend, but use clearer path-vs-stable-ID
|
||||||
|
// names internally so the move flow is easier to reason about.
|
||||||
|
type moveProjectFolderRequest struct {
|
||||||
|
FolderPath string `json:"folderId"`
|
||||||
|
FolderStableID string `json:"folderNodeId"`
|
||||||
|
ParentFolderPath string `json:"parentFolderId"`
|
||||||
|
ParentStableID string `json:"parentNodeId"`
|
||||||
|
TargetIndex int `json:"targetIndex"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (routes apiRoutes) handleProjectFolders(w http.ResponseWriter, r *http.Request) {
|
func (routes apiRoutes) handleProjectFolders(w http.ResponseWriter, r *http.Request) {
|
||||||
@@ -63,7 +73,7 @@ func (routes apiRoutes) handleCreateProjectFolder(w http.ResponseWriter, r *http
|
|||||||
}
|
}
|
||||||
|
|
||||||
payload.Name = strings.TrimSpace(payload.Name)
|
payload.Name = strings.TrimSpace(payload.Name)
|
||||||
payload.ParentFolderID = strings.TrimSpace(payload.ParentFolderID)
|
payload.ParentFolderPath = strings.TrimSpace(payload.ParentFolderPath)
|
||||||
if payload.Name == "" {
|
if payload.Name == "" {
|
||||||
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Folder name is required.")
|
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Folder name is required.")
|
||||||
return
|
return
|
||||||
@@ -71,7 +81,7 @@ func (routes apiRoutes) handleCreateProjectFolder(w http.ResponseWriter, r *http
|
|||||||
|
|
||||||
result, err := routes.bootstrapService().CreateProjectFolder(r.Context(), bootstrapservice.CreateProjectFolderInput{
|
result, err := routes.bootstrapService().CreateProjectFolder(r.Context(), bootstrapservice.CreateProjectFolderInput{
|
||||||
ProjectID: projectID,
|
ProjectID: projectID,
|
||||||
ParentFolderID: payload.ParentFolderID,
|
ParentFolderPath: payload.ParentFolderPath,
|
||||||
Name: payload.Name,
|
Name: payload.Name,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -96,14 +106,14 @@ func (routes apiRoutes) handleDeleteProjectFolder(w http.ResponseWriter, r *http
|
|||||||
}
|
}
|
||||||
|
|
||||||
payload := decodeDeleteProjectFolderRequest(r)
|
payload := decodeDeleteProjectFolderRequest(r)
|
||||||
if strings.TrimSpace(payload.FolderID) == "" {
|
if strings.TrimSpace(payload.FolderPath) == "" {
|
||||||
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Folder ID is required.")
|
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Folder ID is required.")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
result, err := routes.bootstrapService().DeleteProjectFolder(r.Context(), bootstrapservice.DeleteProjectFolderInput{
|
result, err := routes.bootstrapService().DeleteProjectFolder(r.Context(), bootstrapservice.DeleteProjectFolderInput{
|
||||||
ProjectID: projectID,
|
ProjectID: projectID,
|
||||||
FolderID: payload.FolderID,
|
FolderPath: payload.FolderPath,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
routes.writeProjectFolderError(w, r, err, "delete")
|
routes.writeProjectFolderError(w, r, err, "delete")
|
||||||
@@ -131,9 +141,9 @@ func (routes apiRoutes) handleRenameProjectFolder(w http.ResponseWriter, r *http
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
payload.FolderID = strings.TrimSpace(payload.FolderID)
|
payload.FolderPath = strings.TrimSpace(payload.FolderPath)
|
||||||
payload.Name = strings.TrimSpace(payload.Name)
|
payload.Name = strings.TrimSpace(payload.Name)
|
||||||
if payload.FolderID == "" {
|
if payload.FolderPath == "" {
|
||||||
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Folder ID is required.")
|
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Folder ID is required.")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -144,7 +154,7 @@ func (routes apiRoutes) handleRenameProjectFolder(w http.ResponseWriter, r *http
|
|||||||
|
|
||||||
result, err := routes.bootstrapService().RenameProjectFolder(r.Context(), bootstrapservice.RenameProjectFolderInput{
|
result, err := routes.bootstrapService().RenameProjectFolder(r.Context(), bootstrapservice.RenameProjectFolderInput{
|
||||||
ProjectID: projectID,
|
ProjectID: projectID,
|
||||||
FolderID: payload.FolderID,
|
FolderPath: payload.FolderPath,
|
||||||
Name: payload.Name,
|
Name: payload.Name,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -161,6 +171,49 @@ func (routes apiRoutes) handleRenameProjectFolder(w http.ResponseWriter, r *http
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (routes apiRoutes) handleMoveProjectFolder(w http.ResponseWriter, r *http.Request) {
|
||||||
|
projectID := strings.TrimSpace(chi.URLParam(r, "projectId"))
|
||||||
|
if projectID == "" {
|
||||||
|
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Project ID is required.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
payload, ok := decodeMoveProjectFolderRequest(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
payload.FolderPath = strings.TrimSpace(payload.FolderPath)
|
||||||
|
payload.FolderStableID = strings.TrimSpace(payload.FolderStableID)
|
||||||
|
payload.ParentFolderPath = strings.TrimSpace(payload.ParentFolderPath)
|
||||||
|
payload.ParentStableID = strings.TrimSpace(payload.ParentStableID)
|
||||||
|
if payload.FolderPath == "" {
|
||||||
|
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Folder ID is required.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
result, err := routes.bootstrapService().MoveProjectFolder(r.Context(), bootstrapservice.MoveProjectFolderInput{
|
||||||
|
ProjectID: projectID,
|
||||||
|
FolderPath: payload.FolderPath,
|
||||||
|
FolderStableID: payload.FolderStableID,
|
||||||
|
ParentFolderPath: payload.ParentFolderPath,
|
||||||
|
ParentStableID: payload.ParentStableID,
|
||||||
|
TargetIndex: payload.TargetIndex,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
routes.writeProjectFolderError(w, r, err, "move")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
WriteJSON(w, http.StatusOK, map[string]any{
|
||||||
|
"data": result,
|
||||||
|
"meta": map[string]any{
|
||||||
|
"resource": "project-folder-move",
|
||||||
|
"persisted": true,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
func (routes apiRoutes) handleProjectTreeFolders(w http.ResponseWriter, r *http.Request) {
|
func (routes apiRoutes) handleProjectTreeFolders(w http.ResponseWriter, r *http.Request) {
|
||||||
projectID := strings.TrimSpace(chi.URLParam(r, "projectId"))
|
projectID := strings.TrimSpace(chi.URLParam(r, "projectId"))
|
||||||
if projectID == "" {
|
if projectID == "" {
|
||||||
@@ -198,7 +251,7 @@ func (routes apiRoutes) handleCreateProjectTreeFolder(w http.ResponseWriter, r *
|
|||||||
}
|
}
|
||||||
|
|
||||||
payload.Name = strings.TrimSpace(payload.Name)
|
payload.Name = strings.TrimSpace(payload.Name)
|
||||||
payload.ParentFolderID = strings.TrimSpace(payload.ParentFolderID)
|
payload.ParentFolderPath = strings.TrimSpace(payload.ParentFolderPath)
|
||||||
if payload.Name == "" {
|
if payload.Name == "" {
|
||||||
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Folder name is required.")
|
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Folder name is required.")
|
||||||
return
|
return
|
||||||
@@ -206,7 +259,7 @@ func (routes apiRoutes) handleCreateProjectTreeFolder(w http.ResponseWriter, r *
|
|||||||
|
|
||||||
result, err := routes.bootstrapService().CreateProjectTreeFolder(r.Context(), bootstrapservice.CreateProjectFolderInput{
|
result, err := routes.bootstrapService().CreateProjectTreeFolder(r.Context(), bootstrapservice.CreateProjectFolderInput{
|
||||||
ProjectID: projectID,
|
ProjectID: projectID,
|
||||||
ParentFolderID: payload.ParentFolderID,
|
ParentFolderPath: payload.ParentFolderPath,
|
||||||
Name: payload.Name,
|
Name: payload.Name,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -231,14 +284,14 @@ func (routes apiRoutes) handleDeleteProjectTreeFolder(w http.ResponseWriter, r *
|
|||||||
}
|
}
|
||||||
|
|
||||||
payload := decodeDeleteProjectFolderRequest(r)
|
payload := decodeDeleteProjectFolderRequest(r)
|
||||||
if strings.TrimSpace(payload.FolderID) == "" {
|
if strings.TrimSpace(payload.FolderPath) == "" {
|
||||||
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Folder ID is required.")
|
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Folder ID is required.")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
result, err := routes.bootstrapService().DeleteProjectTreeFolder(r.Context(), bootstrapservice.DeleteProjectFolderInput{
|
result, err := routes.bootstrapService().DeleteProjectTreeFolder(r.Context(), bootstrapservice.DeleteProjectFolderInput{
|
||||||
ProjectID: projectID,
|
ProjectID: projectID,
|
||||||
FolderID: payload.FolderID,
|
FolderPath: payload.FolderPath,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
routes.writeProjectFolderError(w, r, err, "delete")
|
routes.writeProjectFolderError(w, r, err, "delete")
|
||||||
@@ -266,9 +319,9 @@ func (routes apiRoutes) handleRenameProjectTreeFolder(w http.ResponseWriter, r *
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
payload.FolderID = strings.TrimSpace(payload.FolderID)
|
payload.FolderPath = strings.TrimSpace(payload.FolderPath)
|
||||||
payload.Name = strings.TrimSpace(payload.Name)
|
payload.Name = strings.TrimSpace(payload.Name)
|
||||||
if payload.FolderID == "" {
|
if payload.FolderPath == "" {
|
||||||
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Folder ID is required.")
|
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Folder ID is required.")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -279,7 +332,7 @@ func (routes apiRoutes) handleRenameProjectTreeFolder(w http.ResponseWriter, r *
|
|||||||
|
|
||||||
result, err := routes.bootstrapService().RenameProjectTreeFolder(r.Context(), bootstrapservice.RenameProjectFolderInput{
|
result, err := routes.bootstrapService().RenameProjectTreeFolder(r.Context(), bootstrapservice.RenameProjectFolderInput{
|
||||||
ProjectID: projectID,
|
ProjectID: projectID,
|
||||||
FolderID: payload.FolderID,
|
FolderPath: payload.FolderPath,
|
||||||
Name: payload.Name,
|
Name: payload.Name,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -296,10 +349,55 @@ func (routes apiRoutes) handleRenameProjectTreeFolder(w http.ResponseWriter, r *
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (routes apiRoutes) handleMoveProjectTreeFolder(w http.ResponseWriter, r *http.Request) {
|
||||||
|
projectID := strings.TrimSpace(chi.URLParam(r, "projectId"))
|
||||||
|
if projectID == "" {
|
||||||
|
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Project ID is required.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
payload, ok := decodeMoveProjectFolderRequest(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
payload.FolderPath = strings.TrimSpace(payload.FolderPath)
|
||||||
|
payload.FolderStableID = strings.TrimSpace(payload.FolderStableID)
|
||||||
|
payload.ParentFolderPath = strings.TrimSpace(payload.ParentFolderPath)
|
||||||
|
payload.ParentStableID = strings.TrimSpace(payload.ParentStableID)
|
||||||
|
if payload.FolderPath == "" {
|
||||||
|
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Folder ID is required.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
result, err := routes.bootstrapService().MoveProjectTreeFolder(r.Context(), bootstrapservice.MoveProjectFolderInput{
|
||||||
|
ProjectID: projectID,
|
||||||
|
FolderPath: payload.FolderPath,
|
||||||
|
FolderStableID: payload.FolderStableID,
|
||||||
|
ParentFolderPath: payload.ParentFolderPath,
|
||||||
|
ParentStableID: payload.ParentStableID,
|
||||||
|
TargetIndex: payload.TargetIndex,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
routes.writeProjectFolderError(w, r, err, "move")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
WriteJSON(w, http.StatusOK, map[string]any{
|
||||||
|
"data": result,
|
||||||
|
"meta": map[string]any{
|
||||||
|
"resource": "project-tree-folder-move",
|
||||||
|
"persisted": true,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
func (routes apiRoutes) writeProjectFolderError(w http.ResponseWriter, r *http.Request, err error, operation string) {
|
func (routes apiRoutes) writeProjectFolderError(w http.ResponseWriter, r *http.Request, err error, operation string) {
|
||||||
switch {
|
switch {
|
||||||
case errors.Is(err, bootstrapservice.ErrProjectNotFound), errors.Is(err, bootstrapservice.ErrProjectFolderNotFound):
|
case errors.Is(err, bootstrapservice.ErrProjectNotFound), errors.Is(err, bootstrapservice.ErrProjectFolderNotFound):
|
||||||
WriteError(w, http.StatusNotFound, RequestIDFromContext(r.Context()), "not_found", err.Error())
|
WriteError(w, http.StatusNotFound, RequestIDFromContext(r.Context()), "not_found", err.Error())
|
||||||
|
case errors.Is(err, bootstrapservice.ErrInvalidProjectFolderMove):
|
||||||
|
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", err.Error())
|
||||||
default:
|
default:
|
||||||
routes.cfg.Logger.Error(operation+" project folder", "error", err, "path", r.URL.Path)
|
routes.cfg.Logger.Error(operation+" project folder", "error", err, "path", r.URL.Path)
|
||||||
message := "Failed to " + operation + " project folder."
|
message := "Failed to " + operation + " project folder."
|
||||||
@@ -310,9 +408,33 @@ func (routes apiRoutes) writeProjectFolderError(w http.ResponseWriter, r *http.R
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func decodeMoveProjectFolderRequest(w http.ResponseWriter, r *http.Request) (moveProjectFolderRequest, bool) {
|
||||||
|
var payload moveProjectFolderRequest
|
||||||
|
|
||||||
|
decoder := json.NewDecoder(r.Body)
|
||||||
|
decoder.DisallowUnknownFields()
|
||||||
|
|
||||||
|
if err := decoder.Decode(&payload); err != nil {
|
||||||
|
if errors.Is(err, io.EOF) {
|
||||||
|
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_json", "The request body is required and must be valid JSON.")
|
||||||
|
return payload, false
|
||||||
|
}
|
||||||
|
|
||||||
|
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_json", "The request body must be valid JSON.")
|
||||||
|
return payload, false
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
|
||||||
|
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_json", "The request body must contain a single JSON object.")
|
||||||
|
return payload, false
|
||||||
|
}
|
||||||
|
|
||||||
|
return payload, true
|
||||||
|
}
|
||||||
|
|
||||||
func decodeDeleteProjectFolderRequest(r *http.Request) deleteProjectFolderRequest {
|
func decodeDeleteProjectFolderRequest(r *http.Request) deleteProjectFolderRequest {
|
||||||
return deleteProjectFolderRequest{
|
return deleteProjectFolderRequest{
|
||||||
FolderID: strings.TrimSpace(r.URL.Query().Get("folderId")),
|
FolderPath: strings.TrimSpace(r.URL.Query().Get("folderId")),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -37,10 +37,12 @@ func (routes apiRoutes) Register(router chi.Router) {
|
|||||||
projectRouter.Get("/folders", routes.handleProjectFolders)
|
projectRouter.Get("/folders", routes.handleProjectFolders)
|
||||||
projectRouter.Post("/folders", routes.handleCreateProjectFolder)
|
projectRouter.Post("/folders", routes.handleCreateProjectFolder)
|
||||||
projectRouter.Patch("/folders", routes.handleRenameProjectFolder)
|
projectRouter.Patch("/folders", routes.handleRenameProjectFolder)
|
||||||
|
projectRouter.Patch("/folders/move", routes.handleMoveProjectFolder)
|
||||||
projectRouter.Delete("/folders", routes.handleDeleteProjectFolder)
|
projectRouter.Delete("/folders", routes.handleDeleteProjectFolder)
|
||||||
projectRouter.Get("/tree/folders", routes.handleProjectTreeFolders)
|
projectRouter.Get("/tree/folders", routes.handleProjectTreeFolders)
|
||||||
projectRouter.Post("/tree/folders", routes.handleCreateProjectTreeFolder)
|
projectRouter.Post("/tree/folders", routes.handleCreateProjectTreeFolder)
|
||||||
projectRouter.Patch("/tree/folders", routes.handleRenameProjectTreeFolder)
|
projectRouter.Patch("/tree/folders", routes.handleRenameProjectTreeFolder)
|
||||||
|
projectRouter.Patch("/tree/folders/move", routes.handleMoveProjectTreeFolder)
|
||||||
projectRouter.Delete("/tree/folders", routes.handleDeleteProjectTreeFolder)
|
projectRouter.Delete("/tree/folders", routes.handleDeleteProjectTreeFolder)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,196 @@
|
|||||||
|
package jobs
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
|
||||||
|
"moku-backend/internal/database"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
KindBootstrapStructureMaterialize = "bootstrap.structure.materialize"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Status string
|
||||||
|
|
||||||
|
const (
|
||||||
|
StatusPending Status = "pending"
|
||||||
|
StatusRunning Status = "running"
|
||||||
|
StatusSucceeded Status = "succeeded"
|
||||||
|
StatusFailed Status = "failed"
|
||||||
|
)
|
||||||
|
|
||||||
|
type BootstrapStructureMaterializePayload struct {
|
||||||
|
InstallationID string `json:"installationId"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Job struct {
|
||||||
|
ID string
|
||||||
|
Kind string
|
||||||
|
Status Status
|
||||||
|
Payload json.RawMessage
|
||||||
|
Attempts int
|
||||||
|
MaxAttempts int
|
||||||
|
AvailableAt time.Time
|
||||||
|
StartedAt *time.Time
|
||||||
|
FinishedAt *time.Time
|
||||||
|
LastError *string
|
||||||
|
CreatedAt time.Time
|
||||||
|
UpdatedAt time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
type EnqueueInput struct {
|
||||||
|
Kind string
|
||||||
|
Payload any
|
||||||
|
AvailableAt time.Time
|
||||||
|
MaxAttempts int
|
||||||
|
}
|
||||||
|
|
||||||
|
type Store struct {
|
||||||
|
db *database.DB
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewStore(db *database.DB) *Store {
|
||||||
|
return &Store{db: db}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (store *Store) Enqueue(ctx context.Context, input EnqueueInput) (Job, error) {
|
||||||
|
payload := json.RawMessage([]byte(`{}`))
|
||||||
|
if input.Payload != nil {
|
||||||
|
encoded, err := json.Marshal(input.Payload)
|
||||||
|
if err != nil {
|
||||||
|
return Job{}, err
|
||||||
|
}
|
||||||
|
payload = encoded
|
||||||
|
}
|
||||||
|
|
||||||
|
availableAt := input.AvailableAt
|
||||||
|
if availableAt.IsZero() {
|
||||||
|
availableAt = time.Now().UTC()
|
||||||
|
}
|
||||||
|
|
||||||
|
maxAttempts := input.MaxAttempts
|
||||||
|
if maxAttempts < 1 {
|
||||||
|
maxAttempts = 1
|
||||||
|
}
|
||||||
|
|
||||||
|
return scanJob(store.db.Pool.QueryRow(ctx, `
|
||||||
|
INSERT INTO background_jobs (kind, status, payload, attempts, max_attempts, available_at)
|
||||||
|
VALUES ($1, 'pending'::background_job_status, $2::jsonb, 0, $3, $4)
|
||||||
|
RETURNING
|
||||||
|
id::text,
|
||||||
|
kind,
|
||||||
|
status::text,
|
||||||
|
payload,
|
||||||
|
attempts,
|
||||||
|
max_attempts,
|
||||||
|
available_at,
|
||||||
|
started_at,
|
||||||
|
finished_at,
|
||||||
|
last_error,
|
||||||
|
created_at,
|
||||||
|
updated_at;
|
||||||
|
`, strings.TrimSpace(input.Kind), payload, maxAttempts, availableAt))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (store *Store) ClaimNext(ctx context.Context) (*Job, error) {
|
||||||
|
job, err := scanJob(store.db.Pool.QueryRow(ctx, `
|
||||||
|
WITH next_job AS (
|
||||||
|
SELECT id
|
||||||
|
FROM background_jobs
|
||||||
|
WHERE status = 'pending'::background_job_status
|
||||||
|
AND available_at <= NOW()
|
||||||
|
ORDER BY created_at ASC
|
||||||
|
LIMIT 1
|
||||||
|
FOR UPDATE SKIP LOCKED
|
||||||
|
)
|
||||||
|
UPDATE background_jobs AS jobs
|
||||||
|
SET
|
||||||
|
status = 'running'::background_job_status,
|
||||||
|
attempts = jobs.attempts + 1,
|
||||||
|
started_at = NOW(),
|
||||||
|
finished_at = NULL,
|
||||||
|
last_error = NULL,
|
||||||
|
updated_at = NOW()
|
||||||
|
FROM next_job
|
||||||
|
WHERE jobs.id = next_job.id
|
||||||
|
RETURNING
|
||||||
|
jobs.id::text,
|
||||||
|
jobs.kind,
|
||||||
|
jobs.status::text,
|
||||||
|
jobs.payload,
|
||||||
|
jobs.attempts,
|
||||||
|
jobs.max_attempts,
|
||||||
|
jobs.available_at,
|
||||||
|
jobs.started_at,
|
||||||
|
jobs.finished_at,
|
||||||
|
jobs.last_error,
|
||||||
|
jobs.created_at,
|
||||||
|
jobs.updated_at;
|
||||||
|
`))
|
||||||
|
if err != nil {
|
||||||
|
if err == pgx.ErrNoRows {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return &job, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (store *Store) MarkSucceeded(ctx context.Context, jobID string) error {
|
||||||
|
_, err := store.db.Pool.Exec(ctx, `
|
||||||
|
UPDATE background_jobs
|
||||||
|
SET
|
||||||
|
status = 'succeeded'::background_job_status,
|
||||||
|
finished_at = NOW(),
|
||||||
|
last_error = NULL,
|
||||||
|
updated_at = NOW()
|
||||||
|
WHERE id = $1::uuid;
|
||||||
|
`, strings.TrimSpace(jobID))
|
||||||
|
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (store *Store) MarkFailed(ctx context.Context, jobID, failure string) error {
|
||||||
|
_, err := store.db.Pool.Exec(ctx, `
|
||||||
|
UPDATE background_jobs
|
||||||
|
SET
|
||||||
|
status = 'failed'::background_job_status,
|
||||||
|
finished_at = NOW(),
|
||||||
|
last_error = $2,
|
||||||
|
updated_at = NOW()
|
||||||
|
WHERE id = $1::uuid;
|
||||||
|
`, strings.TrimSpace(jobID), strings.TrimSpace(failure))
|
||||||
|
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func scanJob(row pgx.Row) (Job, error) {
|
||||||
|
var job Job
|
||||||
|
var status string
|
||||||
|
if err := row.Scan(
|
||||||
|
&job.ID,
|
||||||
|
&job.Kind,
|
||||||
|
&status,
|
||||||
|
&job.Payload,
|
||||||
|
&job.Attempts,
|
||||||
|
&job.MaxAttempts,
|
||||||
|
&job.AvailableAt,
|
||||||
|
&job.StartedAt,
|
||||||
|
&job.FinishedAt,
|
||||||
|
&job.LastError,
|
||||||
|
&job.CreatedAt,
|
||||||
|
&job.UpdatedAt,
|
||||||
|
); err != nil {
|
||||||
|
return Job{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
job.Status = Status(status)
|
||||||
|
return job, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,118 @@
|
|||||||
|
package worker
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"log/slog"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"moku-backend/internal/jobs"
|
||||||
|
)
|
||||||
|
|
||||||
|
type JobStore interface {
|
||||||
|
ClaimNext(ctx context.Context) (*jobs.Job, error)
|
||||||
|
MarkSucceeded(ctx context.Context, jobID string) error
|
||||||
|
MarkFailed(ctx context.Context, jobID, failure string) error
|
||||||
|
}
|
||||||
|
|
||||||
|
type Handler func(ctx context.Context, job jobs.Job) error
|
||||||
|
|
||||||
|
type Runner struct {
|
||||||
|
store JobStore
|
||||||
|
logger *slog.Logger
|
||||||
|
pollInterval time.Duration
|
||||||
|
handlers map[string]Handler
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRunner(store JobStore, logger *slog.Logger, pollInterval time.Duration) *Runner {
|
||||||
|
interval := pollInterval
|
||||||
|
if interval <= 0 {
|
||||||
|
interval = time.Second
|
||||||
|
}
|
||||||
|
|
||||||
|
return &Runner{
|
||||||
|
store: store,
|
||||||
|
logger: logger,
|
||||||
|
pollInterval: interval,
|
||||||
|
handlers: make(map[string]Handler),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (runner *Runner) Register(kind string, handler Handler) {
|
||||||
|
runner.handlers[strings.TrimSpace(kind)] = handler
|
||||||
|
}
|
||||||
|
|
||||||
|
func (runner *Runner) Run(ctx context.Context) error {
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return nil
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
|
||||||
|
job, err := runner.store.ClaimNext(ctx)
|
||||||
|
if err != nil {
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if job == nil {
|
||||||
|
if err := waitForNextPoll(ctx, runner.pollInterval); err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
handler, ok := runner.handlers[job.Kind]
|
||||||
|
if !ok {
|
||||||
|
failure := fmt.Sprintf("no handler registered for job kind %q", job.Kind)
|
||||||
|
if err := runner.store.MarkFailed(ctx, job.ID, failure); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
runner.logger.Error("worker job failed", "jobID", job.ID, "kind", job.Kind, "error", failure)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := handler(ctx, *job); err != nil {
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
failure := strings.TrimSpace(err.Error())
|
||||||
|
if failure == "" {
|
||||||
|
failure = "job handler returned an empty error"
|
||||||
|
}
|
||||||
|
|
||||||
|
if markErr := runner.store.MarkFailed(ctx, job.ID, failure); markErr != nil {
|
||||||
|
return markErr
|
||||||
|
}
|
||||||
|
|
||||||
|
runner.logger.Error("worker job failed", "jobID", job.ID, "kind", job.Kind, "error", failure)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := runner.store.MarkSucceeded(ctx, job.ID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
runner.logger.Info("worker job succeeded", "jobID", job.ID, "kind", job.Kind)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func waitForNextPoll(ctx context.Context, interval time.Duration) error {
|
||||||
|
timer := time.NewTimer(interval)
|
||||||
|
defer timer.Stop()
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return ctx.Err()
|
||||||
|
case <-timer.C:
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,161 @@
|
|||||||
|
package worker
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"log/slog"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"moku-backend/internal/jobs"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestRunnerProcessesRegisteredJob(t *testing.T) {
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
store := &fakeJobStore{
|
||||||
|
job: &jobs.Job{
|
||||||
|
ID: "job-1",
|
||||||
|
Kind: jobs.KindBootstrapStructureMaterialize,
|
||||||
|
Payload: []byte(`{"installationId":"installation-1"}`),
|
||||||
|
},
|
||||||
|
cancel: cancel,
|
||||||
|
}
|
||||||
|
runner := NewRunner(store, slog.New(slog.NewTextHandler(io.Discard, nil)), 0)
|
||||||
|
|
||||||
|
handlerCalled := false
|
||||||
|
runner.Register(jobs.KindBootstrapStructureMaterialize, func(ctx context.Context, job jobs.Job) error {
|
||||||
|
handlerCalled = true
|
||||||
|
if job.ID != "job-1" {
|
||||||
|
t.Fatalf("expected job id job-1, got %s", job.ID)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
|
if err := runner.Run(ctx); err != nil {
|
||||||
|
t.Fatalf("runner returned error: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if !handlerCalled {
|
||||||
|
t.Fatal("expected handler to be called")
|
||||||
|
}
|
||||||
|
if len(store.succeeded) != 1 || store.succeeded[0] != "job-1" {
|
||||||
|
t.Fatalf("expected job to be marked succeeded once, got %#v", store.succeeded)
|
||||||
|
}
|
||||||
|
if len(store.failed) != 0 {
|
||||||
|
t.Fatalf("expected no failed jobs, got %#v", store.failed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRunnerMarksFailedWhenHandlerErrors(t *testing.T) {
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
store := &fakeJobStore{
|
||||||
|
job: &jobs.Job{
|
||||||
|
ID: "job-2",
|
||||||
|
Kind: jobs.KindBootstrapStructureMaterialize,
|
||||||
|
},
|
||||||
|
cancel: cancel,
|
||||||
|
}
|
||||||
|
runner := NewRunner(store, slog.New(slog.NewTextHandler(io.Discard, nil)), 0)
|
||||||
|
runner.Register(jobs.KindBootstrapStructureMaterialize, func(ctx context.Context, job jobs.Job) error {
|
||||||
|
return errors.New("boom")
|
||||||
|
})
|
||||||
|
|
||||||
|
if err := runner.Run(ctx); err != nil {
|
||||||
|
t.Fatalf("runner returned error: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(store.succeeded) != 0 {
|
||||||
|
t.Fatalf("expected no succeeded jobs, got %#v", store.succeeded)
|
||||||
|
}
|
||||||
|
if len(store.failed) != 1 {
|
||||||
|
t.Fatalf("expected one failed job, got %#v", store.failed)
|
||||||
|
}
|
||||||
|
if store.failed[0].jobID != "job-2" {
|
||||||
|
t.Fatalf("expected failed job id job-2, got %#v", store.failed[0])
|
||||||
|
}
|
||||||
|
if !strings.Contains(store.failed[0].failure, "boom") {
|
||||||
|
t.Fatalf("expected failure to mention handler error, got %#v", store.failed[0])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRunnerMarksFailedWhenHandlerMissing(t *testing.T) {
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
store := &fakeJobStore{
|
||||||
|
job: &jobs.Job{
|
||||||
|
ID: "job-3",
|
||||||
|
Kind: "unknown.kind",
|
||||||
|
},
|
||||||
|
cancel: cancel,
|
||||||
|
}
|
||||||
|
runner := NewRunner(store, slog.New(slog.NewTextHandler(io.Discard, nil)), 0)
|
||||||
|
|
||||||
|
if err := runner.Run(ctx); err != nil {
|
||||||
|
t.Fatalf("runner returned error: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(store.failed) != 1 {
|
||||||
|
t.Fatalf("expected one failed job, got %#v", store.failed)
|
||||||
|
}
|
||||||
|
if !strings.Contains(store.failed[0].failure, "no handler registered") {
|
||||||
|
t.Fatalf("expected missing handler failure, got %#v", store.failed[0])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type fakeJobStore struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
job *jobs.Job
|
||||||
|
claimed bool
|
||||||
|
succeeded []string
|
||||||
|
failed []fakeFailure
|
||||||
|
cancel context.CancelFunc
|
||||||
|
}
|
||||||
|
|
||||||
|
type fakeFailure struct {
|
||||||
|
jobID string
|
||||||
|
failure string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (store *fakeJobStore) ClaimNext(ctx context.Context) (*jobs.Job, error) {
|
||||||
|
store.mu.Lock()
|
||||||
|
defer store.mu.Unlock()
|
||||||
|
|
||||||
|
if store.claimed || store.job == nil {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
store.claimed = true
|
||||||
|
job := *store.job
|
||||||
|
return &job, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (store *fakeJobStore) MarkSucceeded(ctx context.Context, jobID string) error {
|
||||||
|
store.mu.Lock()
|
||||||
|
store.succeeded = append(store.succeeded, jobID)
|
||||||
|
store.mu.Unlock()
|
||||||
|
|
||||||
|
if store.cancel != nil {
|
||||||
|
store.cancel()
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (store *fakeJobStore) MarkFailed(ctx context.Context, jobID, failure string) error {
|
||||||
|
store.mu.Lock()
|
||||||
|
store.failed = append(store.failed, fakeFailure{jobID: jobID, failure: failure})
|
||||||
|
store.mu.Unlock()
|
||||||
|
|
||||||
|
if store.cancel != nil {
|
||||||
|
store.cancel()
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -36,6 +36,7 @@ type ProjectSelectorProps = {
|
|||||||
type ProjectFolderNode = {
|
type ProjectFolderNode = {
|
||||||
kind: "folder";
|
kind: "folder";
|
||||||
id: string;
|
id: string;
|
||||||
|
path: string;
|
||||||
label: string;
|
label: string;
|
||||||
meta?: string;
|
meta?: string;
|
||||||
children: ProjectTreeNode[];
|
children: ProjectTreeNode[];
|
||||||
@@ -50,6 +51,7 @@ type ProjectTreeNode = ProjectFolderNode | ProjectLeafNode;
|
|||||||
|
|
||||||
type PersistedProjectFolderRecord = {
|
type PersistedProjectFolderRecord = {
|
||||||
id: string;
|
id: string;
|
||||||
|
path: string;
|
||||||
label: string;
|
label: string;
|
||||||
children: PersistedProjectFolderRecord[];
|
children: PersistedProjectFolderRecord[];
|
||||||
};
|
};
|
||||||
@@ -58,7 +60,9 @@ type ProjectFoldersResponse = {
|
|||||||
data?: {
|
data?: {
|
||||||
folders?: PersistedProjectFolderRecord[];
|
folders?: PersistedProjectFolderRecord[];
|
||||||
renamedFolder?: PersistedProjectFolderRecord;
|
renamedFolder?: PersistedProjectFolderRecord;
|
||||||
|
movedFolder?: PersistedProjectFolderRecord;
|
||||||
previousFolderId?: string;
|
previousFolderId?: string;
|
||||||
|
previousFolderPath?: string;
|
||||||
};
|
};
|
||||||
error?: string;
|
error?: string;
|
||||||
message?: string;
|
message?: string;
|
||||||
@@ -90,6 +94,7 @@ const buildPersistedFolderNodes = (folders: readonly PersistedProjectFolderRecor
|
|||||||
folders.map((folder) => ({
|
folders.map((folder) => ({
|
||||||
kind: "folder",
|
kind: "folder",
|
||||||
id: folder.id,
|
id: folder.id,
|
||||||
|
path: folder.path,
|
||||||
label: folder.label,
|
label: folder.label,
|
||||||
children: buildPersistedFolderNodes(folder.children ?? []),
|
children: buildPersistedFolderNodes(folder.children ?? []),
|
||||||
}));
|
}));
|
||||||
@@ -98,6 +103,9 @@ const buildProjectTree = (
|
|||||||
items: readonly ProjectItem[],
|
items: readonly ProjectItem[],
|
||||||
folders: readonly PersistedProjectFolderRecord[] = [],
|
folders: readonly PersistedProjectFolderRecord[] = [],
|
||||||
): ProjectTreeNode[] => [
|
): ProjectTreeNode[] => [
|
||||||
|
// The selector still presents scaffold project leaves beside persisted folders.
|
||||||
|
// Keep that mixed root shape explicit here so the drag/drop logic can account
|
||||||
|
// for folder-only ordering when we persist sibling positions.
|
||||||
...items.map((item) => ({
|
...items.map((item) => ({
|
||||||
kind: "project" as const,
|
kind: "project" as const,
|
||||||
item,
|
item,
|
||||||
@@ -105,6 +113,11 @@ const buildProjectTree = (
|
|||||||
...buildPersistedFolderNodes(folders),
|
...buildPersistedFolderNodes(folders),
|
||||||
];
|
];
|
||||||
|
|
||||||
|
const countProjectFolderSiblingsBeforeIndex = (
|
||||||
|
siblings: readonly ProjectTreeNode[],
|
||||||
|
index: number,
|
||||||
|
): number => siblings.slice(0, index).filter((node) => node.kind === "folder").length;
|
||||||
|
|
||||||
const readPersistedFolders = (body: ProjectFoldersResponse): PersistedProjectFolderRecord[] =>
|
const readPersistedFolders = (body: ProjectFoldersResponse): PersistedProjectFolderRecord[] =>
|
||||||
Array.isArray(body.data?.folders) ? body.data.folders : [];
|
Array.isArray(body.data?.folders) ? body.data.folders : [];
|
||||||
|
|
||||||
@@ -574,9 +587,49 @@ export const ProjectSelector = (props: ProjectSelectorProps): JSX.Element => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
suppressTreeClickTemporarily();
|
suppressTreeClickTemporarily();
|
||||||
|
|
||||||
|
const currentNodes = projectTreeNodes();
|
||||||
|
const draggedLocation = findTreeNodeLocation(currentNodes, nextDragState.draggedNodeId, projectTreeAdapter);
|
||||||
|
const canPersistMove = isUuidString(selectedProject().id);
|
||||||
|
const draggedFolderPath = draggedLocation?.node.kind === "folder" ? draggedLocation.node.path : null;
|
||||||
|
const previewNodes = moveTreeNode(currentNodes, nextDragState.draggedNodeId, nextDragState.dropTarget as ProjectDragTarget, projectTreeAdapter);
|
||||||
|
const previewLocation = findTreeNodeLocation(previewNodes, nextDragState.draggedNodeId, projectTreeAdapter);
|
||||||
|
const persistedParentLocation = previewLocation?.parentId
|
||||||
|
? findTreeNodeLocation(previewNodes, previewLocation.parentId, projectTreeAdapter)
|
||||||
|
: null;
|
||||||
|
const persistedParentFolderPath =
|
||||||
|
persistedParentLocation?.node.kind === "folder" ? persistedParentLocation.node.path : null;
|
||||||
|
const previewSiblings = previewLocation?.parentId
|
||||||
|
? persistedParentLocation?.node.kind === "folder"
|
||||||
|
? persistedParentLocation.node.children
|
||||||
|
: []
|
||||||
|
: previewNodes;
|
||||||
|
// The preview tree includes project leaves and folders, but the backend only
|
||||||
|
// stores sibling order for folders. Persist a folder-only index so the server
|
||||||
|
// can reapply the same position against the authoritative ordered tree.
|
||||||
|
const targetIndex = previewLocation
|
||||||
|
? countProjectFolderSiblingsBeforeIndex(previewSiblings, previewLocation.index)
|
||||||
|
: 0;
|
||||||
|
|
||||||
|
if (
|
||||||
|
canPersistMove &&
|
||||||
|
draggedLocation?.node.kind === "folder" &&
|
||||||
|
draggedFolderPath &&
|
||||||
|
(!previewLocation?.parentId || persistedParentLocation?.node.kind === "folder")
|
||||||
|
) {
|
||||||
|
void movePersistedFolder(
|
||||||
|
draggedFolderPath,
|
||||||
|
persistedParentFolderPath,
|
||||||
|
draggedLocation.node.id,
|
||||||
|
persistedParentLocation?.node.kind === "folder" ? persistedParentLocation.node.id : null,
|
||||||
|
targetIndex,
|
||||||
|
);
|
||||||
|
} else {
|
||||||
setProjectTreeNodes((current) =>
|
setProjectTreeNodes((current) =>
|
||||||
moveTreeNode(current, nextDragState.draggedNodeId, nextDragState.dropTarget as ProjectDragTarget, projectTreeAdapter),
|
moveTreeNode(current, nextDragState.draggedNodeId, nextDragState.dropTarget as ProjectDragTarget, projectTreeAdapter),
|
||||||
);
|
);
|
||||||
|
}
|
||||||
|
|
||||||
setDragState(null);
|
setDragState(null);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -655,6 +708,11 @@ export const ProjectSelector = (props: ProjectSelectorProps): JSX.Element => {
|
|||||||
setPendingFolderRenameName(label);
|
setPendingFolderRenameName(label);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const resolveFolderPath = (folderId: string): string | null => {
|
||||||
|
const location = findTreeNodeLocation(projectTreeNodes(), folderId, projectTreeAdapter);
|
||||||
|
return location && location.node.kind === "folder" ? location.node.path : null;
|
||||||
|
};
|
||||||
|
|
||||||
const submitPendingFolder = async (): Promise<void> => {
|
const submitPendingFolder = async (): Promise<void> => {
|
||||||
const name = pendingFolderName().trim();
|
const name = pendingFolderName().trim();
|
||||||
const draft = pendingFolderDraft();
|
const draft = pendingFolderDraft();
|
||||||
@@ -675,6 +733,12 @@ export const ProjectSelector = (props: ProjectSelectorProps): JSX.Element => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const parentFolderPath = draft.parentId ? resolveFolderPath(draft.parentId) : null;
|
||||||
|
if (draft.parentId && !parentFolderPath) {
|
||||||
|
cancelPendingFolder();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`${resolveAPIBase()}/projects/${projectId}/folders`, {
|
const response = await fetch(`${resolveAPIBase()}/projects/${projectId}/folders`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
@@ -684,7 +748,7 @@ export const ProjectSelector = (props: ProjectSelectorProps): JSX.Element => {
|
|||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
name,
|
name,
|
||||||
parentFolderId: draft.parentId,
|
parentFolderId: parentFolderPath,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -708,9 +772,14 @@ export const ProjectSelector = (props: ProjectSelectorProps): JSX.Element => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const folderPath = resolveFolderPath(folderId);
|
||||||
|
if (!folderPath) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch(
|
const response = await fetch(
|
||||||
`${resolveAPIBase()}/projects/${projectId}/folders?folderId=${encodeURIComponent(folderId)}`,
|
`${resolveAPIBase()}/projects/${projectId}/folders?folderId=${encodeURIComponent(folderPath)}`,
|
||||||
{
|
{
|
||||||
method: "DELETE",
|
method: "DELETE",
|
||||||
headers: {
|
headers: {
|
||||||
@@ -732,6 +801,46 @@ export const ProjectSelector = (props: ProjectSelectorProps): JSX.Element => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const movePersistedFolder = async (
|
||||||
|
folderPath: string,
|
||||||
|
parentFolderPath: string | null,
|
||||||
|
folderStableId: string,
|
||||||
|
parentStableId: string | null,
|
||||||
|
targetIndex: number,
|
||||||
|
): Promise<void> => {
|
||||||
|
const projectId = selectedProject().id;
|
||||||
|
if (!folderPath || !folderStableId || !isUuidString(projectId)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${resolveAPIBase()}/projects/${projectId}/folders/move`, {
|
||||||
|
method: "PATCH",
|
||||||
|
headers: {
|
||||||
|
Accept: "application/json",
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
folderId: folderPath,
|
||||||
|
folderNodeId: folderStableId,
|
||||||
|
parentFolderId: parentFolderPath,
|
||||||
|
parentNodeId: parentStableId,
|
||||||
|
targetIndex,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const body = (await response.json()) as ProjectFoldersResponse;
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(body.message || "Failed to move project folder.");
|
||||||
|
}
|
||||||
|
|
||||||
|
setPersistedFolders(readPersistedFolders(body));
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const submitPendingFolderRename = async (): Promise<void> => {
|
const submitPendingFolderRename = async (): Promise<void> => {
|
||||||
const draft = pendingFolderRename();
|
const draft = pendingFolderRename();
|
||||||
const name = pendingFolderRenameName().trim();
|
const name = pendingFolderRenameName().trim();
|
||||||
@@ -752,6 +861,12 @@ export const ProjectSelector = (props: ProjectSelectorProps): JSX.Element => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const folderPath = resolveFolderPath(draft.folderId);
|
||||||
|
if (!folderPath) {
|
||||||
|
cancelPendingFolderRename();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`${resolveAPIBase()}/projects/${projectId}/folders`, {
|
const response = await fetch(`${resolveAPIBase()}/projects/${projectId}/folders`, {
|
||||||
method: "PATCH",
|
method: "PATCH",
|
||||||
@@ -760,7 +875,7 @@ export const ProjectSelector = (props: ProjectSelectorProps): JSX.Element => {
|
|||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
folderId: draft.folderId,
|
folderId: folderPath,
|
||||||
name,
|
name,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
@@ -774,14 +889,6 @@ export const ProjectSelector = (props: ProjectSelectorProps): JSX.Element => {
|
|||||||
setPersistedFolders(readPersistedFolders(body));
|
setPersistedFolders(readPersistedFolders(body));
|
||||||
setPendingFolderRename(null);
|
setPendingFolderRename(null);
|
||||||
setPendingFolderRenameName("");
|
setPendingFolderRenameName("");
|
||||||
|
|
||||||
const previousFolderId = body.data?.previousFolderId;
|
|
||||||
const renamedFolderId = body.data?.renamedFolder?.id;
|
|
||||||
if (previousFolderId && renamedFolderId && previousFolderId !== renamedFolderId) {
|
|
||||||
setCollapsedFolderIds((current) =>
|
|
||||||
current.map((id) => (id === previousFolderId ? renamedFolderId : id)),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(error);
|
console.error(error);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import { ProjectSelector } from "../ProjectSelector/ProjectSelector";
|
|||||||
import {
|
import {
|
||||||
collectBranchNodeIds,
|
collectBranchNodeIds,
|
||||||
findTreeNodeDepth,
|
findTreeNodeDepth,
|
||||||
|
findTreeNodeLocation,
|
||||||
getPointerRelativeY,
|
getPointerRelativeY,
|
||||||
isUuidString,
|
isUuidString,
|
||||||
moveTreeNode,
|
moveTreeNode,
|
||||||
@@ -51,6 +52,7 @@ type WorkspaceDragState = {
|
|||||||
|
|
||||||
type PersistedWorkspaceFolderRecord = {
|
type PersistedWorkspaceFolderRecord = {
|
||||||
id: string;
|
id: string;
|
||||||
|
path: string;
|
||||||
label: string;
|
label: string;
|
||||||
children?: PersistedWorkspaceFolderRecord[];
|
children?: PersistedWorkspaceFolderRecord[];
|
||||||
};
|
};
|
||||||
@@ -59,7 +61,9 @@ type WorkspaceFoldersResponse = {
|
|||||||
data?: {
|
data?: {
|
||||||
folders?: PersistedWorkspaceFolderRecord[];
|
folders?: PersistedWorkspaceFolderRecord[];
|
||||||
renamedFolder?: PersistedWorkspaceFolderRecord;
|
renamedFolder?: PersistedWorkspaceFolderRecord;
|
||||||
|
movedFolder?: PersistedWorkspaceFolderRecord;
|
||||||
previousFolderId?: string;
|
previousFolderId?: string;
|
||||||
|
previousFolderPath?: string;
|
||||||
};
|
};
|
||||||
error?: string;
|
error?: string;
|
||||||
message?: string;
|
message?: string;
|
||||||
@@ -79,6 +83,7 @@ const buildPersistedWorkspaceFolderNodes = (
|
|||||||
): WorkspaceTreeNode[] =>
|
): WorkspaceTreeNode[] =>
|
||||||
folders.map((folder) => ({
|
folders.map((folder) => ({
|
||||||
id: folder.id,
|
id: folder.id,
|
||||||
|
path: folder.path,
|
||||||
label: folder.label,
|
label: folder.label,
|
||||||
kind: "folder",
|
kind: "folder",
|
||||||
icon: Folder,
|
icon: Folder,
|
||||||
@@ -88,6 +93,11 @@ const buildPersistedWorkspaceFolderNodes = (
|
|||||||
const readPersistedWorkspaceFolders = (body: WorkspaceFoldersResponse): PersistedWorkspaceFolderRecord[] =>
|
const readPersistedWorkspaceFolders = (body: WorkspaceFoldersResponse): PersistedWorkspaceFolderRecord[] =>
|
||||||
Array.isArray(body.data?.folders) ? body.data.folders : [];
|
Array.isArray(body.data?.folders) ? body.data.folders : [];
|
||||||
|
|
||||||
|
const countWorkspaceFolderSiblingsBeforeIndex = (
|
||||||
|
siblings: readonly WorkspaceTreeNode[],
|
||||||
|
index: number,
|
||||||
|
): number => siblings.slice(0, index).filter((node) => node.kind === "folder").length;
|
||||||
|
|
||||||
const workspaceTreeAdapter: NavTreeAdapter<WorkspaceTreeNode> = {
|
const workspaceTreeAdapter: NavTreeAdapter<WorkspaceTreeNode> = {
|
||||||
getNodeId: getWorkspaceTreeNodeId,
|
getNodeId: getWorkspaceTreeNodeId,
|
||||||
isBranchNode: (node) => node.kind === "folder",
|
isBranchNode: (node) => node.kind === "folder",
|
||||||
@@ -527,9 +537,48 @@ export const WorkspaceSidebar = (props: WorkspaceSidebarProps): JSX.Element => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
suppressTreeClickTemporarily();
|
suppressTreeClickTemporarily();
|
||||||
|
|
||||||
|
const currentNodes = workspaceTreeNodes();
|
||||||
|
const draggedLocation = findTreeNodeLocation(currentNodes, nextDragState.draggedNodeId, workspaceTreeAdapter);
|
||||||
|
const canPersistMove = isUuidString(activeProject()?.id ?? "");
|
||||||
|
const draggedFolderPath = draggedLocation?.node.kind === "folder" ? draggedLocation.node.path ?? null : null;
|
||||||
|
const previewNodes = moveTreeNode(currentNodes, nextDragState.draggedNodeId, nextDragState.dropTarget as WorkspaceDragTarget, workspaceTreeAdapter);
|
||||||
|
const previewLocation = findTreeNodeLocation(previewNodes, nextDragState.draggedNodeId, workspaceTreeAdapter);
|
||||||
|
const persistedParentLocation = previewLocation?.parentId
|
||||||
|
? findTreeNodeLocation(previewNodes, previewLocation.parentId, workspaceTreeAdapter)
|
||||||
|
: null;
|
||||||
|
const persistedParentFolderPath = persistedParentLocation?.node.kind === "folder" ? persistedParentLocation.node.path ?? null : null;
|
||||||
|
const previewSiblings = previewLocation?.parentId
|
||||||
|
? persistedParentLocation?.node.kind === "folder"
|
||||||
|
? persistedParentLocation.node.children ?? []
|
||||||
|
: []
|
||||||
|
: previewNodes;
|
||||||
|
// The tree preview can include static/workspace items, but persisted ordering
|
||||||
|
// only applies to folder siblings. Convert the preview position into a folder-
|
||||||
|
// only index before sending it to the backend move endpoint.
|
||||||
|
const targetIndex = previewLocation
|
||||||
|
? countWorkspaceFolderSiblingsBeforeIndex(previewSiblings, previewLocation.index)
|
||||||
|
: 0;
|
||||||
|
|
||||||
|
if (
|
||||||
|
canPersistMove &&
|
||||||
|
draggedLocation?.node.kind === "folder" &&
|
||||||
|
draggedFolderPath &&
|
||||||
|
(!previewLocation?.parentId || persistedParentLocation?.node.kind === "folder")
|
||||||
|
) {
|
||||||
|
void movePersistedFolder(
|
||||||
|
draggedFolderPath,
|
||||||
|
persistedParentFolderPath,
|
||||||
|
draggedLocation.node.id,
|
||||||
|
persistedParentLocation?.node.kind === "folder" ? persistedParentLocation.node.id : null,
|
||||||
|
targetIndex,
|
||||||
|
);
|
||||||
|
} else {
|
||||||
setWorkspaceTreeNodes((current) =>
|
setWorkspaceTreeNodes((current) =>
|
||||||
moveTreeNode(current, nextDragState.draggedNodeId, nextDragState.dropTarget as WorkspaceDragTarget, workspaceTreeAdapter),
|
moveTreeNode(current, nextDragState.draggedNodeId, nextDragState.dropTarget as WorkspaceDragTarget, workspaceTreeAdapter),
|
||||||
);
|
);
|
||||||
|
}
|
||||||
|
|
||||||
setDragState(null);
|
setDragState(null);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -578,6 +627,11 @@ export const WorkspaceSidebar = (props: WorkspaceSidebarProps): JSX.Element => {
|
|||||||
setPendingFolderRenameName(label);
|
setPendingFolderRenameName(label);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const resolveFolderPath = (folderId: string): string | null => {
|
||||||
|
const location = findTreeNodeLocation(workspaceTreeNodes(), folderId, workspaceTreeAdapter);
|
||||||
|
return location?.node.kind === "folder" ? location.node.path ?? null : null;
|
||||||
|
};
|
||||||
|
|
||||||
const submitPendingFolder = async (): Promise<void> => {
|
const submitPendingFolder = async (): Promise<void> => {
|
||||||
const name = pendingFolderName().trim();
|
const name = pendingFolderName().trim();
|
||||||
const draft = pendingFolderDraft();
|
const draft = pendingFolderDraft();
|
||||||
@@ -598,6 +652,12 @@ export const WorkspaceSidebar = (props: WorkspaceSidebarProps): JSX.Element => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const parentFolderPath = draft.parentId ? resolveFolderPath(draft.parentId) : null;
|
||||||
|
if (draft.parentId && !parentFolderPath) {
|
||||||
|
cancelPendingFolder();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`${resolveAPIBase()}/projects/${projectId}/tree/folders`, {
|
const response = await fetch(`${resolveAPIBase()}/projects/${projectId}/tree/folders`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
@@ -607,7 +667,7 @@ export const WorkspaceSidebar = (props: WorkspaceSidebarProps): JSX.Element => {
|
|||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
name,
|
name,
|
||||||
parentFolderId: draft.parentId,
|
parentFolderId: parentFolderPath,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -627,13 +687,17 @@ export const WorkspaceSidebar = (props: WorkspaceSidebarProps): JSX.Element => {
|
|||||||
|
|
||||||
const deletePersistedFolder = async (folderId: string): Promise<void> => {
|
const deletePersistedFolder = async (folderId: string): Promise<void> => {
|
||||||
const projectId = activeProject()?.id ?? "";
|
const projectId = activeProject()?.id ?? "";
|
||||||
|
const folderPath = resolveFolderPath(folderId);
|
||||||
if (!folderId || !projectId || !isUuidString(projectId)) {
|
if (!folderId || !projectId || !isUuidString(projectId)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (!folderPath) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch(
|
const response = await fetch(
|
||||||
`${resolveAPIBase()}/projects/${projectId}/tree/folders?folderId=${encodeURIComponent(folderId)}`,
|
`${resolveAPIBase()}/projects/${projectId}/tree/folders?folderId=${encodeURIComponent(folderPath)}`,
|
||||||
{
|
{
|
||||||
method: "DELETE",
|
method: "DELETE",
|
||||||
headers: {
|
headers: {
|
||||||
@@ -655,6 +719,46 @@ export const WorkspaceSidebar = (props: WorkspaceSidebarProps): JSX.Element => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const movePersistedFolder = async (
|
||||||
|
folderPath: string,
|
||||||
|
parentFolderPath: string | null,
|
||||||
|
folderStableId: string,
|
||||||
|
parentStableId: string | null,
|
||||||
|
targetIndex: number,
|
||||||
|
): Promise<void> => {
|
||||||
|
const projectId = activeProject()?.id ?? "";
|
||||||
|
if (!folderPath || !folderStableId || !projectId || !isUuidString(projectId)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${resolveAPIBase()}/projects/${projectId}/tree/folders/move`, {
|
||||||
|
method: "PATCH",
|
||||||
|
headers: {
|
||||||
|
Accept: "application/json",
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
folderId: folderPath,
|
||||||
|
folderNodeId: folderStableId,
|
||||||
|
parentFolderId: parentFolderPath,
|
||||||
|
parentNodeId: parentStableId,
|
||||||
|
targetIndex,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const body = (await response.json()) as WorkspaceFoldersResponse;
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(body.message || "Failed to move project tree folder.");
|
||||||
|
}
|
||||||
|
|
||||||
|
setPersistedFolders(readPersistedWorkspaceFolders(body));
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const submitPendingFolderRename = async (): Promise<void> => {
|
const submitPendingFolderRename = async (): Promise<void> => {
|
||||||
const draft = pendingFolderRename();
|
const draft = pendingFolderRename();
|
||||||
const name = pendingFolderRenameName().trim();
|
const name = pendingFolderRenameName().trim();
|
||||||
@@ -675,6 +779,12 @@ export const WorkspaceSidebar = (props: WorkspaceSidebarProps): JSX.Element => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const folderPath = resolveFolderPath(draft.folderId);
|
||||||
|
if (!folderPath) {
|
||||||
|
cancelPendingFolderRename();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`${resolveAPIBase()}/projects/${projectId}/tree/folders`, {
|
const response = await fetch(`${resolveAPIBase()}/projects/${projectId}/tree/folders`, {
|
||||||
method: "PATCH",
|
method: "PATCH",
|
||||||
@@ -683,7 +793,7 @@ export const WorkspaceSidebar = (props: WorkspaceSidebarProps): JSX.Element => {
|
|||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
folderId: draft.folderId,
|
folderId: folderPath,
|
||||||
name,
|
name,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
@@ -697,14 +807,6 @@ export const WorkspaceSidebar = (props: WorkspaceSidebarProps): JSX.Element => {
|
|||||||
setPersistedFolders(readPersistedWorkspaceFolders(body));
|
setPersistedFolders(readPersistedWorkspaceFolders(body));
|
||||||
setPendingFolderRename(null);
|
setPendingFolderRename(null);
|
||||||
setPendingFolderRenameName("");
|
setPendingFolderRenameName("");
|
||||||
|
|
||||||
const previousFolderId = body.data?.previousFolderId;
|
|
||||||
const renamedFolderId = body.data?.renamedFolder?.id;
|
|
||||||
if (previousFolderId && renamedFolderId && previousFolderId !== renamedFolderId) {
|
|
||||||
setCollapsedFolderIds((current) =>
|
|
||||||
current.map((id) => (id === previousFolderId ? renamedFolderId : id)),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(error);
|
console.error(error);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -40,6 +40,8 @@ type AppShellInstallation = {
|
|||||||
protocol: string;
|
protocol: string;
|
||||||
host: string;
|
host: string;
|
||||||
isBootstrapped: boolean;
|
isBootstrapped: boolean;
|
||||||
|
materializationStatus: "not_started" | "pending" | "running" | "succeeded" | "failed" | string;
|
||||||
|
materializationError?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
type AppShellAdmin = {
|
type AppShellAdmin = {
|
||||||
@@ -101,8 +103,29 @@ type AppShellPayload = {
|
|||||||
workspaces: AppShellWorkspace[];
|
workspaces: AppShellWorkspace[];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const normalizeInstallation = (
|
||||||
|
installation: AppShellInstallation | null | undefined,
|
||||||
|
): AppShellInstallation | undefined => {
|
||||||
|
if (!installation) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
const materializationStatus = installation.materializationStatus?.trim()
|
||||||
|
? installation.materializationStatus
|
||||||
|
: installation.isBootstrapped
|
||||||
|
? "succeeded"
|
||||||
|
: "not_started";
|
||||||
|
const materializationError = installation.materializationError?.trim() || undefined;
|
||||||
|
|
||||||
|
return {
|
||||||
|
...installation,
|
||||||
|
materializationStatus,
|
||||||
|
materializationError,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
const normalizeAppShellPayload = (payload: AppShellPayload | null | undefined): AppShellPayload => ({
|
const normalizeAppShellPayload = (payload: AppShellPayload | null | undefined): AppShellPayload => ({
|
||||||
installation: payload?.installation,
|
installation: normalizeInstallation(payload?.installation),
|
||||||
admin: payload?.admin,
|
admin: payload?.admin,
|
||||||
organizations: Array.isArray(payload?.organizations) ? payload.organizations : [],
|
organizations: Array.isArray(payload?.organizations) ? payload.organizations : [],
|
||||||
departments: Array.isArray(payload?.departments) ? payload.departments : [],
|
departments: Array.isArray(payload?.departments) ? payload.departments : [],
|
||||||
|
|||||||
@@ -129,6 +129,7 @@ export type WorkspaceStaticItem = SidebarItem & {
|
|||||||
|
|
||||||
export type WorkspaceFolderNode = {
|
export type WorkspaceFolderNode = {
|
||||||
id: string;
|
id: string;
|
||||||
|
path?: string;
|
||||||
label: string;
|
label: string;
|
||||||
kind: "folder";
|
kind: "folder";
|
||||||
icon: ShellIcon;
|
icon: ShellIcon;
|
||||||
|
|||||||
@@ -92,6 +92,21 @@
|
|||||||
flex-wrap: wrap;
|
flex-wrap: wrap;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.heroStatus {
|
||||||
|
display: grid;
|
||||||
|
gap: var(--space-2);
|
||||||
|
justify-items: start;
|
||||||
|
}
|
||||||
|
|
||||||
|
.heroStatusMessage {
|
||||||
|
max-width: 64ch;
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.heroStatusMessage[data-status="failed"] {
|
||||||
|
color: var(--color-danger-text, var(--color-text));
|
||||||
|
}
|
||||||
|
|
||||||
.title {
|
.title {
|
||||||
@include text-display;
|
@include text-display;
|
||||||
font-family: var(--font-family-display);
|
font-family: var(--font-family-display);
|
||||||
@@ -194,6 +209,19 @@
|
|||||||
background: color-mix(in srgb, var(--color-success-surface, var(--color-surface-secondary)) 80%, transparent);
|
background: color-mix(in srgb, var(--color-success-surface, var(--color-surface-secondary)) 80%, transparent);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.statusBadge[data-status="pending"],
|
||||||
|
.statusBadge[data-status="running"] {
|
||||||
|
color: var(--bootstrap-accent);
|
||||||
|
border-color: color-mix(in srgb, var(--bootstrap-accent) 38%, transparent);
|
||||||
|
background: color-mix(in srgb, var(--bootstrap-accent) 10%, var(--color-surface-secondary));
|
||||||
|
}
|
||||||
|
|
||||||
|
.statusBadge[data-status="failed"] {
|
||||||
|
color: var(--color-danger-text, var(--color-text));
|
||||||
|
border-color: color-mix(in srgb, var(--color-danger-border, var(--color-border)) 68%, transparent);
|
||||||
|
background: color-mix(in srgb, var(--color-danger-surface, var(--color-surface-secondary)) 80%, transparent);
|
||||||
|
}
|
||||||
|
|
||||||
.statusBadge[data-status="error"] {
|
.statusBadge[data-status="error"] {
|
||||||
color: var(--color-danger-text, var(--color-text));
|
color: var(--color-danger-text, var(--color-text));
|
||||||
border-color: color-mix(in srgb, var(--color-danger-border, var(--color-border)) 68%, transparent);
|
border-color: color-mix(in srgb, var(--color-danger-border, var(--color-border)) 68%, transparent);
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
// Path: Frontend/src/components/workspace-home/WorkspaceHome/WorkspaceHome.tsx
|
// Path: Frontend/src/components/workspace-home/WorkspaceHome/WorkspaceHome.tsx
|
||||||
|
|
||||||
import { For, Show, createEffect, createMemo, createSignal, type JSX } from "solid-js";
|
import { For, Show, createEffect, createMemo, createSignal, onCleanup, type JSX } from "solid-js";
|
||||||
import { Portal } from "solid-js/web";
|
import { Portal } from "solid-js/web";
|
||||||
import { createStore } from "solid-js/store";
|
import { createStore } from "solid-js/store";
|
||||||
import { resolveAPIBase } from "../../../lib/api";
|
import { resolveAPIBase } from "../../../lib/api";
|
||||||
@@ -21,6 +21,31 @@ type BootstrapSubmissionState = {
|
|||||||
error: string;
|
error: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
type InstanceForm = {
|
||||||
|
protocol: "http" | "https";
|
||||||
|
access: "local" | "remote";
|
||||||
|
host: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
type ModeForm = {
|
||||||
|
mode: "personal" | "organizational";
|
||||||
|
name: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
type AdminForm = {
|
||||||
|
displayName: string;
|
||||||
|
email: string;
|
||||||
|
password: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
type StructureForm = {
|
||||||
|
departmentName: string;
|
||||||
|
teamName: string;
|
||||||
|
projectName: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
type MaterializationState = "not_started" | "pending" | "running" | "succeeded" | "failed";
|
||||||
|
|
||||||
const bootstrapStepDefinitions: readonly BootstrapStepDefinition[] = [
|
const bootstrapStepDefinitions: readonly BootstrapStepDefinition[] = [
|
||||||
{
|
{
|
||||||
id: "instance",
|
id: "instance",
|
||||||
@@ -44,43 +69,45 @@ const bootstrapStepDefinitions: readonly BootstrapStepDefinition[] = [
|
|||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
const defaultInstanceForm = {
|
const defaultInstanceForm: InstanceForm = {
|
||||||
protocol: "http",
|
protocol: "http",
|
||||||
access: "local",
|
access: "local",
|
||||||
host: "localhost",
|
host: "localhost",
|
||||||
} as const;
|
};
|
||||||
|
|
||||||
const defaultModeForm = {
|
const defaultModeForm: ModeForm = {
|
||||||
mode: "personal",
|
mode: "personal",
|
||||||
name: "",
|
name: "",
|
||||||
} as const;
|
};
|
||||||
|
|
||||||
const defaultAdminForm = {
|
const defaultAdminForm: AdminForm = {
|
||||||
displayName: "Admin",
|
displayName: "Admin",
|
||||||
email: "admin@example.com",
|
email: "admin@example.com",
|
||||||
password: "",
|
password: "",
|
||||||
} as const;
|
};
|
||||||
|
|
||||||
const personalStructureDefaults = {
|
const personalStructureDefaults = {
|
||||||
departmentName: "Default",
|
departmentName: "Default",
|
||||||
teamName: "Personal",
|
teamName: "Personal",
|
||||||
} as const;
|
};
|
||||||
|
|
||||||
const organizationalStructureDefaults = {
|
const organizationalStructureDefaults = {
|
||||||
departmentName: "Department",
|
departmentName: "Department",
|
||||||
teamName: "Team",
|
teamName: "Team",
|
||||||
} as const;
|
};
|
||||||
|
|
||||||
const defaultStructureForm = {
|
const defaultStructureForm: StructureForm = {
|
||||||
...personalStructureDefaults,
|
...personalStructureDefaults,
|
||||||
projectName: "Project",
|
projectName: "Project",
|
||||||
} as const;
|
};
|
||||||
|
|
||||||
const initialSubmissionState = (): BootstrapSubmissionState => ({
|
const initialSubmissionState = (): BootstrapSubmissionState => ({
|
||||||
status: "idle",
|
status: "idle",
|
||||||
error: "",
|
error: "",
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const materializationPollIntervalMs = 2000;
|
||||||
|
|
||||||
const readResponseBody = async (response: Response): Promise<unknown> => {
|
const readResponseBody = async (response: Response): Promise<unknown> => {
|
||||||
const raw = await response.text();
|
const raw = await response.text();
|
||||||
|
|
||||||
@@ -148,10 +175,10 @@ type WorkspaceHomeProps = {
|
|||||||
|
|
||||||
export const WorkspaceHome = (props: WorkspaceHomeProps): JSX.Element => {
|
export const WorkspaceHome = (props: WorkspaceHomeProps): JSX.Element => {
|
||||||
const appShellData = useAppShellData();
|
const appShellData = useAppShellData();
|
||||||
const [instanceForm, setInstanceForm] = createStore({ ...defaultInstanceForm });
|
const [instanceForm, setInstanceForm] = createStore<InstanceForm>({ ...defaultInstanceForm });
|
||||||
const [modeForm, setModeForm] = createStore({ ...defaultModeForm });
|
const [modeForm, setModeForm] = createStore<ModeForm>({ ...defaultModeForm });
|
||||||
const [adminForm, setAdminForm] = createStore({ ...defaultAdminForm });
|
const [adminForm, setAdminForm] = createStore<AdminForm>({ ...defaultAdminForm });
|
||||||
const [structureForm, setStructureForm] = createStore({ ...defaultStructureForm });
|
const [structureForm, setStructureForm] = createStore<StructureForm>({ ...defaultStructureForm });
|
||||||
const [stepState, setStepState] = createStore<Record<BootstrapStepKey, BootstrapSubmissionState>>({
|
const [stepState, setStepState] = createStore<Record<BootstrapStepKey, BootstrapSubmissionState>>({
|
||||||
instance: initialSubmissionState(),
|
instance: initialSubmissionState(),
|
||||||
mode: initialSubmissionState(),
|
mode: initialSubmissionState(),
|
||||||
@@ -162,6 +189,51 @@ export const WorkspaceHome = (props: WorkspaceHomeProps): JSX.Element => {
|
|||||||
const [isBootstrapComplete, setIsBootstrapComplete] = createSignal(false);
|
const [isBootstrapComplete, setIsBootstrapComplete] = createSignal(false);
|
||||||
const [isWizardOpen, setIsWizardOpen] = createSignal(false);
|
const [isWizardOpen, setIsWizardOpen] = createSignal(false);
|
||||||
const [currentStepIndex, setCurrentStepIndex] = createSignal(0);
|
const [currentStepIndex, setCurrentStepIndex] = createSignal(0);
|
||||||
|
const installation = createMemo(() => appShellData.installation());
|
||||||
|
const materializationState = createMemo<MaterializationState>(() => {
|
||||||
|
const status = installation()?.materializationStatus;
|
||||||
|
|
||||||
|
switch (status) {
|
||||||
|
case "pending":
|
||||||
|
case "running":
|
||||||
|
case "failed":
|
||||||
|
case "succeeded":
|
||||||
|
case "not_started":
|
||||||
|
return status;
|
||||||
|
default:
|
||||||
|
return installation()?.isBootstrapped ? "succeeded" : "not_started";
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const isBootstrapPersisted = createMemo(() => installation()?.isBootstrapped ?? false);
|
||||||
|
const isMaterializationInFlight = createMemo(
|
||||||
|
() => materializationState() === "pending" || materializationState() === "running",
|
||||||
|
);
|
||||||
|
const hasMaterializationFailed = createMemo(() => materializationState() === "failed");
|
||||||
|
const materializationStatusLabel = createMemo(() => {
|
||||||
|
switch (materializationState()) {
|
||||||
|
case "pending":
|
||||||
|
return "Materialization queued";
|
||||||
|
case "running":
|
||||||
|
return "Materialization running";
|
||||||
|
case "failed":
|
||||||
|
return "Materialization failed";
|
||||||
|
case "succeeded":
|
||||||
|
return "Ready";
|
||||||
|
default:
|
||||||
|
return "Not started";
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const materializationMessage = createMemo(() => {
|
||||||
|
if (isMaterializationInFlight()) {
|
||||||
|
return "Your bootstrap is saved. The worker is still creating the POSIX skeleton and rebuilding the app shell index.";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (hasMaterializationFailed()) {
|
||||||
|
return installation()?.materializationError || "Bootstrap saved, but background materialization did not finish cleanly.";
|
||||||
|
}
|
||||||
|
|
||||||
|
return "";
|
||||||
|
});
|
||||||
|
|
||||||
createEffect(() => {
|
createEffect(() => {
|
||||||
if (modeForm.mode === "personal") {
|
if (modeForm.mode === "personal") {
|
||||||
@@ -190,19 +262,51 @@ export const WorkspaceHome = (props: WorkspaceHomeProps): JSX.Element => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const installationAccessor = appShellData.installation;
|
if (!isBootstrapPersisted()) {
|
||||||
const installation = typeof installationAccessor === "function" ? installationAccessor() : undefined;
|
|
||||||
const isPersistedBootstrap = installation?.isBootstrapped ?? false;
|
|
||||||
|
|
||||||
if (!isPersistedBootstrap) {
|
|
||||||
resetWizardState();
|
resetWizardState();
|
||||||
}
|
}
|
||||||
|
|
||||||
setIsBootstrapComplete(isPersistedBootstrap);
|
setIsBootstrapComplete(isBootstrapPersisted() && !isMaterializationInFlight());
|
||||||
setIsWizardOpen(!isPersistedBootstrap);
|
setIsWizardOpen(!isBootstrapPersisted());
|
||||||
setIsBootstrapStateResolved(true);
|
setIsBootstrapStateResolved(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
createEffect(() => {
|
||||||
|
if (!isBootstrapPersisted() || !isMaterializationInFlight()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let cancelled = false;
|
||||||
|
let timeoutId: number | undefined;
|
||||||
|
|
||||||
|
const scheduleReload = (): void => {
|
||||||
|
timeoutId = window.setTimeout(async () => {
|
||||||
|
if (cancelled) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The final bootstrap step only persists relational state. Poll while the
|
||||||
|
// worker is materializing the POSIX skeleton so the page can transition from
|
||||||
|
// queued/running to ready/failed without a manual refresh.
|
||||||
|
await appShellData.reload();
|
||||||
|
|
||||||
|
if (!cancelled && isBootstrapPersisted() && isMaterializationInFlight()) {
|
||||||
|
scheduleReload();
|
||||||
|
}
|
||||||
|
}, materializationPollIntervalMs);
|
||||||
|
};
|
||||||
|
|
||||||
|
scheduleReload();
|
||||||
|
|
||||||
|
onCleanup(() => {
|
||||||
|
cancelled = true;
|
||||||
|
|
||||||
|
if (timeoutId !== undefined) {
|
||||||
|
window.clearTimeout(timeoutId);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
const sidebarToggleLabel = (): string =>
|
const sidebarToggleLabel = (): string =>
|
||||||
props.sidebarCollapsed ? "Expand left workspace sidebar" : "Collapse left workspace sidebar";
|
props.sidebarCollapsed ? "Expand left workspace sidebar" : "Collapse left workspace sidebar";
|
||||||
const breadcrumb = (): string => `${appShellData.activeServer().name} / ${appShellData.activeProject().name} / Home`;
|
const breadcrumb = (): string => `${appShellData.activeServer().name} / ${appShellData.activeProject().name} / Home`;
|
||||||
@@ -217,7 +321,7 @@ export const WorkspaceHome = (props: WorkspaceHomeProps): JSX.Element => {
|
|||||||
const currentStepState = createMemo<BootstrapSubmissionState>(() => stepState[currentStep().id]);
|
const currentStepState = createMemo<BootstrapSubmissionState>(() => stepState[currentStep().id]);
|
||||||
const isFirstStep = (): boolean => currentStepIndex() === 0;
|
const isFirstStep = (): boolean => currentStepIndex() === 0;
|
||||||
const isLastStep = (): boolean => currentStepIndex() === bootstrapStepDefinitions.length - 1;
|
const isLastStep = (): boolean => currentStepIndex() === bootstrapStepDefinitions.length - 1;
|
||||||
const canDismissWizard = (): boolean => isBootstrapComplete();
|
const canDismissWizard = (): boolean => isBootstrapPersisted();
|
||||||
|
|
||||||
const resetWizardState = (): void => {
|
const resetWizardState = (): void => {
|
||||||
setInstanceForm({ ...defaultInstanceForm });
|
setInstanceForm({ ...defaultInstanceForm });
|
||||||
@@ -290,12 +394,9 @@ export const WorkspaceHome = (props: WorkspaceHomeProps): JSX.Element => {
|
|||||||
|
|
||||||
if (isLastStep()) {
|
if (isLastStep()) {
|
||||||
await appShellData.reload();
|
await appShellData.reload();
|
||||||
const installationAccessor = appShellData.installation;
|
|
||||||
const installation = typeof installationAccessor === "function" ? installationAccessor() : undefined;
|
|
||||||
const isPersistedBootstrap = installation?.isBootstrapped ?? false;
|
|
||||||
|
|
||||||
setIsBootstrapComplete(isPersistedBootstrap);
|
setIsBootstrapComplete(isBootstrapPersisted() && !isMaterializationInFlight());
|
||||||
setIsWizardOpen(!isPersistedBootstrap);
|
setIsWizardOpen(!isBootstrapPersisted());
|
||||||
setIsBootstrapStateResolved(true);
|
setIsBootstrapStateResolved(true);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -360,11 +461,30 @@ export const WorkspaceHome = (props: WorkspaceHomeProps): JSX.Element => {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<section class={styles.hero} data-slot="workspace-home-hero">
|
<section class={styles.hero} data-slot="workspace-home-hero">
|
||||||
<h1 class={styles.title}>{isBootstrapComplete() ? appShellData.activeServer().name : bootstrapTargetLabel()}</h1>
|
<h1 class={styles.title}>{isBootstrapPersisted() ? appShellData.activeServer().name : bootstrapTargetLabel()}</h1>
|
||||||
|
<Show when={isBootstrapStateResolved() && isBootstrapPersisted() && materializationState() !== "succeeded"}>
|
||||||
|
<div class={styles.heroStatus}>
|
||||||
|
<div class={styles.statusBadge} data-status={materializationState()}>
|
||||||
|
{materializationStatusLabel()}
|
||||||
|
</div>
|
||||||
|
<Show when={materializationMessage()}>
|
||||||
|
<p class={styles.heroStatusMessage} data-status={materializationState()}>
|
||||||
|
{materializationMessage()}
|
||||||
|
</p>
|
||||||
|
</Show>
|
||||||
|
</div>
|
||||||
|
</Show>
|
||||||
<Show when={isBootstrapStateResolved() && !isBootstrapComplete()}>
|
<Show when={isBootstrapStateResolved() && !isBootstrapComplete()}>
|
||||||
<div class={styles.heroActions}>
|
<div class={styles.heroActions}>
|
||||||
<button type="button" class={styles.primaryButton} onClick={(): void => setIsWizardOpen(true)}>
|
<button
|
||||||
Open bootstrap wizard
|
type="button"
|
||||||
|
class={styles.primaryButton}
|
||||||
|
disabled={isBootstrapPersisted()}
|
||||||
|
onClick={(): void => {
|
||||||
|
setIsWizardOpen(true);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{isBootstrapPersisted() ? "Bootstrap saved" : "Open bootstrap wizard"}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</Show>
|
</Show>
|
||||||
@@ -384,7 +504,13 @@ export const WorkspaceHome = (props: WorkspaceHomeProps): JSX.Element => {
|
|||||||
</h2>
|
</h2>
|
||||||
</div>
|
</div>
|
||||||
<Show when={canDismissWizard()}>
|
<Show when={canDismissWizard()}>
|
||||||
<button type="button" class={styles.wizardCloseButton} onClick={(): void => setIsWizardOpen(false)}>
|
<button
|
||||||
|
type="button"
|
||||||
|
class={styles.wizardCloseButton}
|
||||||
|
onClick={(): void => {
|
||||||
|
setIsWizardOpen(false);
|
||||||
|
}}
|
||||||
|
>
|
||||||
Close
|
Close
|
||||||
</button>
|
</button>
|
||||||
</Show>
|
</Show>
|
||||||
@@ -425,7 +551,9 @@ export const WorkspaceHome = (props: WorkspaceHomeProps): JSX.Element => {
|
|||||||
<span class={styles.wizardStepEyebrow}>{`Step ${currentStepIndex() + 1} of ${bootstrapStepDefinitions.length}`}</span>
|
<span class={styles.wizardStepEyebrow}>{`Step ${currentStepIndex() + 1} of ${bootstrapStepDefinitions.length}`}</span>
|
||||||
<h3 class={styles.sectionTitle}>{currentStep().title}</h3>
|
<h3 class={styles.sectionTitle}>{currentStep().title}</h3>
|
||||||
</div>
|
</div>
|
||||||
<div class={styles.statusBadge} data-status={currentStepState().status}>{statusLabel(currentStepState())}</div>
|
<div class={styles.statusBadge} data-status={currentStepState().status}>
|
||||||
|
{statusLabel(currentStepState())}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<form class={styles.form} onSubmit={handleCurrentStepSubmit}>
|
<form class={styles.form} onSubmit={handleCurrentStepSubmit}>
|
||||||
@@ -433,14 +561,24 @@ export const WorkspaceHome = (props: WorkspaceHomeProps): JSX.Element => {
|
|||||||
<>
|
<>
|
||||||
<label class={styles.field}>
|
<label class={styles.field}>
|
||||||
<span class={styles.fieldLabel}>Protocol</span>
|
<span class={styles.fieldLabel}>Protocol</span>
|
||||||
<select value={instanceForm.protocol} onInput={(event): void => setInstanceForm("protocol", event.currentTarget.value)}>
|
<select
|
||||||
|
value={instanceForm.protocol}
|
||||||
|
onInput={(event): void =>
|
||||||
|
setInstanceForm("protocol", event.currentTarget.value as InstanceForm["protocol"])
|
||||||
|
}
|
||||||
|
>
|
||||||
<option value="http">http</option>
|
<option value="http">http</option>
|
||||||
<option value="https">https</option>
|
<option value="https">https</option>
|
||||||
</select>
|
</select>
|
||||||
</label>
|
</label>
|
||||||
<label class={styles.field}>
|
<label class={styles.field}>
|
||||||
<span class={styles.fieldLabel}>Access</span>
|
<span class={styles.fieldLabel}>Access</span>
|
||||||
<select value={instanceForm.access} onInput={(event): void => setInstanceForm("access", event.currentTarget.value)}>
|
<select
|
||||||
|
value={instanceForm.access}
|
||||||
|
onInput={(event): void =>
|
||||||
|
setInstanceForm("access", event.currentTarget.value as InstanceForm["access"])
|
||||||
|
}
|
||||||
|
>
|
||||||
<option value="local">local</option>
|
<option value="local">local</option>
|
||||||
<option value="remote">remote</option>
|
<option value="remote">remote</option>
|
||||||
</select>
|
</select>
|
||||||
@@ -461,7 +599,10 @@ export const WorkspaceHome = (props: WorkspaceHomeProps): JSX.Element => {
|
|||||||
<>
|
<>
|
||||||
<label class={styles.field}>
|
<label class={styles.field}>
|
||||||
<span class={styles.fieldLabel}>Mode</span>
|
<span class={styles.fieldLabel}>Mode</span>
|
||||||
<select value={modeForm.mode} onInput={(event): void => setModeForm("mode", event.currentTarget.value)}>
|
<select
|
||||||
|
value={modeForm.mode}
|
||||||
|
onInput={(event): void => setModeForm("mode", event.currentTarget.value as ModeForm["mode"])}
|
||||||
|
>
|
||||||
<option value="personal">personal</option>
|
<option value="personal">personal</option>
|
||||||
<option value="organizational">organizational</option>
|
<option value="organizational">organizational</option>
|
||||||
</select>
|
</select>
|
||||||
@@ -553,7 +694,9 @@ export const WorkspaceHome = (props: WorkspaceHomeProps): JSX.Element => {
|
|||||||
type="button"
|
type="button"
|
||||||
class={styles.secondaryButton}
|
class={styles.secondaryButton}
|
||||||
disabled={isFirstStep()}
|
disabled={isFirstStep()}
|
||||||
onClick={(): void => setCurrentStepIndex((index) => Math.max(index - 1, 0))}
|
onClick={(): void => {
|
||||||
|
setCurrentStepIndex((index) => Math.max(index - 1, 0));
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
Back
|
Back
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
Reference in New Issue
Block a user