2024-05-14 22:34:41 +02:00
|
|
|
// Copyright 2024, Command Line Inc.
|
|
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
|
|
|
|
|
|
package blockservice
|
|
|
|
|
|
|
|
import (
|
2024-05-22 06:15:11 +02:00
|
|
|
"context"
|
2024-05-14 22:34:41 +02:00
|
|
|
"fmt"
|
2024-05-17 03:01:52 +02:00
|
|
|
"strings"
|
2024-05-22 06:15:11 +02:00
|
|
|
"time"
|
2024-05-14 22:34:41 +02:00
|
|
|
|
|
|
|
"github.com/wavetermdev/thenextwave/pkg/blockcontroller"
|
2024-05-16 09:29:58 +02:00
|
|
|
"github.com/wavetermdev/thenextwave/pkg/util/utilfn"
|
2024-05-21 00:57:15 +02:00
|
|
|
"github.com/wavetermdev/thenextwave/pkg/wstore"
|
2024-05-14 22:34:41 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
type BlockService struct{}
|
|
|
|
|
2024-05-22 18:23:16 +02:00
|
|
|
func (bs *BlockService) CreateBlock(bdefMap map[string]any, rtOptsMap map[string]any) (*wstore.Block, error) {
|
2024-05-21 00:57:15 +02:00
|
|
|
var bdef wstore.BlockDef
|
2024-05-16 09:29:58 +02:00
|
|
|
err := utilfn.JsonMapToStruct(bdefMap, &bdef)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("error unmarshalling BlockDef: %w", err)
|
|
|
|
}
|
2024-05-21 00:57:15 +02:00
|
|
|
var rtOpts wstore.RuntimeOpts
|
2024-05-16 09:29:58 +02:00
|
|
|
err = utilfn.JsonMapToStruct(rtOptsMap, &rtOpts)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("error unmarshalling RuntimeOpts: %w", err)
|
|
|
|
}
|
|
|
|
blockData, err := blockcontroller.CreateBlock(&bdef, &rtOpts)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("error creating block: %w", err)
|
|
|
|
}
|
2024-05-22 18:23:16 +02:00
|
|
|
return blockData, nil
|
2024-05-16 09:29:58 +02:00
|
|
|
}
|
|
|
|
|
2024-05-16 22:40:23 +02:00
|
|
|
func (bs *BlockService) CloseBlock(blockId string) {
|
|
|
|
blockcontroller.CloseBlock(blockId)
|
|
|
|
}
|
|
|
|
|
2024-05-22 18:23:16 +02:00
|
|
|
func (bs *BlockService) GetBlockData(blockId string) (*wstore.Block, error) {
|
2024-05-22 06:15:11 +02:00
|
|
|
ctx, cancelFn := context.WithTimeout(context.Background(), 2*time.Second)
|
|
|
|
defer cancelFn()
|
|
|
|
blockData, err := wstore.BlockGet(ctx, blockId)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("error getting block data: %w", err)
|
|
|
|
}
|
2024-05-22 18:23:16 +02:00
|
|
|
return blockData, nil
|
2024-05-15 01:53:03 +02:00
|
|
|
}
|
|
|
|
|
2024-05-14 22:34:41 +02:00
|
|
|
func (bs *BlockService) SendCommand(blockId string, cmdMap map[string]any) error {
|
|
|
|
cmd, err := blockcontroller.ParseCmdMap(cmdMap)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("error parsing command map: %w", err)
|
|
|
|
}
|
2024-05-17 03:01:52 +02:00
|
|
|
if strings.HasPrefix(cmd.GetCommand(), "controller:") {
|
|
|
|
bc := blockcontroller.GetBlockController(blockId)
|
|
|
|
if bc == nil {
|
|
|
|
return fmt.Errorf("block controller not found for block %q", blockId)
|
|
|
|
}
|
|
|
|
bc.InputCh <- cmd
|
|
|
|
} else {
|
|
|
|
blockcontroller.ProcessStaticCommand(blockId, cmd)
|
|
|
|
}
|
2024-05-14 22:34:41 +02:00
|
|
|
return nil
|
|
|
|
}
|