feat(knowledge): add scoped activity audit trail
This commit is contained in:
@@ -68,6 +68,15 @@ func (r *auditLogRepository) List(
|
||||
if q.ActorUserID != "" {
|
||||
tx = tx.Where("actor_user_id = ?", q.ActorUserID)
|
||||
}
|
||||
if q.ScopeType != "" {
|
||||
tx = tx.Where("scope_type = ?", q.ScopeType)
|
||||
}
|
||||
if q.ScopeID != "" {
|
||||
tx = tx.Where("scope_id = ?", q.ScopeID)
|
||||
}
|
||||
if q.UnscopedOnly {
|
||||
tx = tx.Where("scope_type = ''")
|
||||
}
|
||||
}
|
||||
|
||||
var entries []*types.AuditLog
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func TestAuditLogRepositoryListFiltersKnowledgeBaseScope(t *testing.T) {
|
||||
db, err := gorm.Open(sqlite.Open("file:audit-log-scope?mode=memory&cache=shared"), &gorm.Config{})
|
||||
if err != nil {
|
||||
t.Fatalf("open sqlite: %v", err)
|
||||
}
|
||||
if err := db.AutoMigrate(&types.AuditLog{}); err != nil {
|
||||
t.Fatalf("migrate audit log: %v", err)
|
||||
}
|
||||
rows := []*types.AuditLog{
|
||||
{TenantID: 7, Action: types.AuditActionMemberAdded},
|
||||
{TenantID: 7, Action: types.AuditActionKBUpdated, ScopeType: "knowledge_base", ScopeID: "kb-a"},
|
||||
{TenantID: 7, Action: types.AuditActionKnowledgeCreated, ScopeType: "knowledge_base", ScopeID: "kb-b"},
|
||||
{TenantID: 8, Action: types.AuditActionKBUpdated, ScopeType: "knowledge_base", ScopeID: "kb-a"},
|
||||
}
|
||||
for _, row := range rows {
|
||||
if err := db.Create(row).Error; err != nil {
|
||||
t.Fatalf("insert audit log: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
repo := NewAuditLogRepository(db)
|
||||
got, err := repo.List(context.Background(), 7, &interfaces.AuditLogQuery{
|
||||
ScopeType: "knowledge_base",
|
||||
ScopeID: "kb-a",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("list audit logs: %v", err)
|
||||
}
|
||||
if len(got) != 1 || got[0].TenantID != 7 || got[0].ScopeID != "kb-a" {
|
||||
t.Fatalf("scope filter returned unexpected rows: %+v", got)
|
||||
}
|
||||
unscoped, err := repo.List(context.Background(), 7, &interfaces.AuditLogQuery{UnscopedOnly: true})
|
||||
if err != nil {
|
||||
t.Fatalf("list unscoped audit logs: %v", err)
|
||||
}
|
||||
if len(unscoped) != 1 || unscoped[0].Action != types.AuditActionMemberAdded {
|
||||
t.Fatalf("unscoped filter returned unexpected rows: %+v", unscoped)
|
||||
}
|
||||
}
|
||||
@@ -32,6 +32,7 @@ type DataSourceService struct {
|
||||
scheduler *datasource.Scheduler
|
||||
tenantRepo interfaces.TenantRepository
|
||||
tagService interfaces.KnowledgeTagService
|
||||
audit interfaces.AuditLogService
|
||||
}
|
||||
|
||||
// NewDataSourceService creates a new data source service
|
||||
@@ -45,6 +46,7 @@ func NewDataSourceService(
|
||||
scheduler *datasource.Scheduler,
|
||||
tenantRepo interfaces.TenantRepository,
|
||||
tagService interfaces.KnowledgeTagService,
|
||||
audit interfaces.AuditLogService,
|
||||
) interfaces.DataSourceService {
|
||||
return &DataSourceService{
|
||||
dsRepo: dsRepo,
|
||||
@@ -56,6 +58,7 @@ func NewDataSourceService(
|
||||
scheduler: scheduler,
|
||||
tenantRepo: tenantRepo,
|
||||
tagService: tagService,
|
||||
audit: audit,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -105,6 +108,9 @@ func (s *DataSourceService) CreateDataSource(ctx context.Context, ds *types.Data
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "data source created: id=%s type=%s kb=%s", ds.ID, ds.Type, ds.KnowledgeBaseID)
|
||||
recordKBActivity(ctx, s.audit, ds.TenantID, ds.KnowledgeBaseID, types.AuditActionDataSourceCreated,
|
||||
"data_source", ds.ID, types.AuditOutcomeSuccess,
|
||||
map[string]any{"name": ds.Name, "type": ds.Type})
|
||||
return ds, nil
|
||||
}
|
||||
|
||||
@@ -218,6 +224,9 @@ func (s *DataSourceService) UpdateDataSource(ctx context.Context, ds *types.Data
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "data source updated: id=%s", ds.ID)
|
||||
recordKBActivity(ctx, s.audit, ds.TenantID, ds.KnowledgeBaseID, types.AuditActionDataSourceUpdated,
|
||||
"data_source", ds.ID, types.AuditOutcomeSuccess,
|
||||
map[string]any{"name": ds.Name, "type": ds.Type, "changed_fields": []string{"settings"}})
|
||||
return ds, nil
|
||||
}
|
||||
|
||||
@@ -261,6 +270,9 @@ func (s *DataSourceService) UpdateDataSourceCredentials(
|
||||
return nil, err
|
||||
}
|
||||
logger.Infof(ctx, "DataSource credentials updated: id=%s", secutils.SanitizeForLog(id))
|
||||
recordKBActivity(ctx, s.audit, existing.TenantID, existing.KnowledgeBaseID, types.AuditActionDataSourceUpdated,
|
||||
"data_source", existing.ID, types.AuditOutcomeSuccess,
|
||||
map[string]any{"name": existing.Name, "type": existing.Type, "changed_fields": []string{"credentials"}})
|
||||
return existing, nil
|
||||
}
|
||||
|
||||
@@ -300,13 +312,16 @@ func (s *DataSourceService) ClearDataSourceCredentials(ctx context.Context, id s
|
||||
return err
|
||||
}
|
||||
logger.Infof(ctx, "DataSource credentials cleared by user: id=%s", secutils.SanitizeForLog(id))
|
||||
recordKBActivity(ctx, s.audit, existing.TenantID, existing.KnowledgeBaseID, types.AuditActionDataSourceUpdated,
|
||||
"data_source", existing.ID, types.AuditOutcomeSuccess,
|
||||
map[string]any{"name": existing.Name, "type": existing.Type, "changed_fields": []string{"credentials"}})
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeleteDataSource deletes a data source (soft delete)
|
||||
func (s *DataSourceService) DeleteDataSource(ctx context.Context, id string) error {
|
||||
// Verify data source exists
|
||||
_, err := s.dsRepo.FindByID(ctx, id)
|
||||
existing, err := s.dsRepo.FindByID(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -325,6 +340,9 @@ func (s *DataSourceService) DeleteDataSource(ctx context.Context, id string) err
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "data source deleted: id=%s", id)
|
||||
recordKBActivity(ctx, s.audit, existing.TenantID, existing.KnowledgeBaseID, types.AuditActionDataSourceDeleted,
|
||||
"data_source", existing.ID, types.AuditOutcomeSuccess,
|
||||
map[string]any{"name": existing.Name, "type": existing.Type})
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -464,6 +482,8 @@ func (s *DataSourceService) ManualSync(ctx context.Context, dsID string) (*types
|
||||
TenantID: ds.TenantID,
|
||||
SyncLogID: syncLog.ID,
|
||||
ForceFull: false,
|
||||
Initiator: types.TaskInitiatorFromContext(ctx),
|
||||
Trigger: "manual",
|
||||
}
|
||||
langfuse.InjectTracing(ctx, payload)
|
||||
|
||||
@@ -471,7 +491,7 @@ func (s *DataSourceService) ManualSync(ctx context.Context, dsID string) (*types
|
||||
task := asynq.NewTask(types.TypeDataSourceSync, payloadJSON,
|
||||
asynq.Queue(types.QueueSync), asynq.MaxRetry(5), asynq.Timeout(2*time.Hour))
|
||||
|
||||
_, err = s.taskEnqueuer.Enqueue(task)
|
||||
info, err := s.taskEnqueuer.Enqueue(task)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "failed to enqueue sync task: %v", err)
|
||||
syncLog.Status = types.SyncLogStatusFailed
|
||||
@@ -483,10 +503,17 @@ func (s *DataSourceService) ManualSync(ctx context.Context, dsID string) (*types
|
||||
}
|
||||
ds.ErrorMessage = fmt.Sprintf("Failed to enqueue sync: %v", err)
|
||||
_ = s.dsRepo.Update(ctx, ds)
|
||||
recordKBActivity(ctx, s.audit, ds.TenantID, ds.KnowledgeBaseID, types.AuditActionDataSourceSyncFailed,
|
||||
"data_source", ds.ID, types.AuditOutcomeFailed,
|
||||
map[string]any{"name": ds.Name, "type": ds.Type, "sync_log_id": syncLog.ID, "trigger": "manual"})
|
||||
return nil, err
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "sync task enqueued: ds=%s syncLog=%s", dsID, syncLog.ID)
|
||||
recordKBActivity(ctx, s.audit, ds.TenantID, ds.KnowledgeBaseID, types.AuditActionDataSourceSyncStarted,
|
||||
"data_source", ds.ID, types.AuditOutcomeAccepted,
|
||||
map[string]any{"name": ds.Name, "type": ds.Type, "sync_log_id": syncLog.ID,
|
||||
"task_id": info.ID, "trigger": "manual", "processing_status": "pending"})
|
||||
return syncLog, nil
|
||||
}
|
||||
|
||||
@@ -507,6 +534,8 @@ func (s *DataSourceService) PauseDataSource(ctx context.Context, id string) erro
|
||||
s.scheduler.Remove(id)
|
||||
|
||||
logger.Infof(ctx, "data source paused: id=%s", id)
|
||||
recordKBActivity(ctx, s.audit, ds.TenantID, ds.KnowledgeBaseID, types.AuditActionDataSourcePaused,
|
||||
"data_source", ds.ID, types.AuditOutcomeSuccess, map[string]any{"name": ds.Name, "type": ds.Type})
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -529,6 +558,8 @@ func (s *DataSourceService) ResumeDataSource(ctx context.Context, id string) err
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "data source resumed: id=%s", id)
|
||||
recordKBActivity(ctx, s.audit, ds.TenantID, ds.KnowledgeBaseID, types.AuditActionDataSourceResumed,
|
||||
"data_source", ds.ID, types.AuditOutcomeSuccess, map[string]any{"name": ds.Name, "type": ds.Type})
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -558,6 +589,9 @@ func (s *DataSourceService) ProcessSync(ctx context.Context, task *asynq.Task) e
|
||||
logger.Errorf(ctx, "failed to unmarshal sync payload: %v", err)
|
||||
return err
|
||||
}
|
||||
ctx = payload.Initiator.Apply(ctx)
|
||||
taskID, _ := asynq.GetTaskID(ctx)
|
||||
ctx = withKBActivityTask(ctx, taskID, payload.Trigger)
|
||||
|
||||
logger.Infof(ctx, "processing data source sync: ds=%s syncLog=%s", payload.DataSourceID, payload.SyncLogID)
|
||||
|
||||
@@ -708,7 +742,7 @@ func (s *DataSourceService) ProcessSync(ctx context.Context, task *asynq.Task) e
|
||||
|
||||
for _, item := range items {
|
||||
item := item
|
||||
s.applyFetchedItem(ctx, ds, &item, autoTagIDs, result)
|
||||
s.applyFetchedItem(withKBActivitySuppressed(ctx), ds, &item, autoTagIDs, result)
|
||||
}
|
||||
|
||||
resultJSON, _ := result.ToJSON()
|
||||
@@ -879,7 +913,7 @@ func (h *streamSyncHandler) Emit(ctx context.Context, item types.FetchedItem) er
|
||||
return err
|
||||
}
|
||||
h.result.Total++
|
||||
h.svc.applyFetchedItem(ctx, h.ds, &item, h.tagIDs, h.result)
|
||||
h.svc.applyFetchedItem(withKBActivitySuppressed(ctx), h.ds, &item, h.tagIDs, h.result)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1028,6 +1062,21 @@ func (s *DataSourceService) updateSyncRunResult(
|
||||
if err := s.dsRepo.UpdateSyncState(ctx, ds); err != nil {
|
||||
logger.Errorf(ctx, "failed to update data source: %v", err)
|
||||
}
|
||||
action := types.AuditActionDataSourceSyncCompleted
|
||||
outcome := types.AuditOutcomeSuccess
|
||||
if status == types.SyncLogStatusFailed {
|
||||
action = types.AuditActionDataSourceSyncFailed
|
||||
outcome = types.AuditOutcomeFailed
|
||||
} else if status == types.SyncLogStatusPartial {
|
||||
outcome = types.AuditOutcomePartial
|
||||
}
|
||||
recordKBActivity(ctx, s.audit, ds.TenantID, ds.KnowledgeBaseID, action,
|
||||
"data_source", ds.ID, outcome,
|
||||
map[string]any{
|
||||
"name": ds.Name, "type": ds.Type, "sync_log_id": syncLog.ID,
|
||||
"total": result.Total, "created": result.Created, "updated": result.Updated,
|
||||
"deleted": result.Deleted, "skipped": result.Skipped, "failed": result.Failed,
|
||||
})
|
||||
}
|
||||
|
||||
func allFetchedItemsFailedError(result *types.SyncResult) error {
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
)
|
||||
|
||||
const auditScopeKnowledgeBase = "knowledge_base"
|
||||
|
||||
type kbActivityTaskMetadata struct {
|
||||
TaskID string
|
||||
Trigger string
|
||||
}
|
||||
|
||||
type kbActivityTaskContextKey struct{}
|
||||
type kbActivitySuppressedContextKey struct{}
|
||||
|
||||
// withKBActivityTask annotates a worker context with stable correlation fields
|
||||
// that recordKBActivity will add to each event produced by that task.
|
||||
func withKBActivityTask(ctx context.Context, taskID, trigger string) context.Context {
|
||||
if taskID == "" && trigger == "" {
|
||||
return ctx
|
||||
}
|
||||
return context.WithValue(ctx, kbActivityTaskContextKey{}, kbActivityTaskMetadata{
|
||||
TaskID: taskID, Trigger: trigger,
|
||||
})
|
||||
}
|
||||
|
||||
func kbActivityTrigger(ctx context.Context) string {
|
||||
if task, ok := ctx.Value(kbActivityTaskContextKey{}).(kbActivityTaskMetadata); ok && task.Trigger != "" {
|
||||
return task.Trigger
|
||||
}
|
||||
if userID, ok := types.UserIDFromContext(ctx); ok && !types.IsSyntheticUserID(userID) {
|
||||
return "user"
|
||||
}
|
||||
return "system"
|
||||
}
|
||||
|
||||
// withKBActivitySuppressed is used for high-volume child mutations inside a
|
||||
// composite task. The task's bounded summary event remains visible, while one
|
||||
// sync run cannot flood the audit table with thousands of per-item rows.
|
||||
func withKBActivitySuppressed(ctx context.Context) context.Context {
|
||||
return context.WithValue(ctx, kbActivitySuppressedContextKey{}, true)
|
||||
}
|
||||
|
||||
// recordKBActivity appends one bounded, non-secret activity summary to the
|
||||
// existing audit stream. It is deliberately best-effort, matching the audit
|
||||
// service's failure semantics: a temporary audit outage must not roll back a
|
||||
// completed business mutation.
|
||||
func recordKBActivity(
|
||||
ctx context.Context,
|
||||
audit interfaces.AuditLogService,
|
||||
tenantID uint64,
|
||||
kbID string,
|
||||
action types.AuditAction,
|
||||
targetType string,
|
||||
targetID string,
|
||||
outcome types.AuditOutcome,
|
||||
details map[string]any,
|
||||
) {
|
||||
if suppressed, _ := ctx.Value(kbActivitySuppressedContextKey{}).(bool); suppressed {
|
||||
return
|
||||
}
|
||||
if audit == nil || kbID == "" || action == "" {
|
||||
return
|
||||
}
|
||||
if tenantID == 0 {
|
||||
tenantID, _ = types.TenantIDFromContext(ctx)
|
||||
}
|
||||
if tenantID == 0 {
|
||||
return
|
||||
}
|
||||
if outcome == "" {
|
||||
outcome = types.AuditOutcomeSuccess
|
||||
}
|
||||
activityDetails := make(map[string]any, len(details)+2)
|
||||
for key, value := range details {
|
||||
activityDetails[key] = value
|
||||
}
|
||||
if task, ok := ctx.Value(kbActivityTaskContextKey{}).(kbActivityTaskMetadata); ok {
|
||||
if task.TaskID != "" {
|
||||
if _, exists := activityDetails["task_id"]; !exists {
|
||||
activityDetails["task_id"] = task.TaskID
|
||||
}
|
||||
}
|
||||
if task.Trigger != "" {
|
||||
if _, exists := activityDetails["trigger"]; !exists {
|
||||
activityDetails["trigger"] = task.Trigger
|
||||
}
|
||||
}
|
||||
if _, exists := activityDetails["processing_status"]; !exists {
|
||||
switch outcome {
|
||||
case types.AuditOutcomeAccepted:
|
||||
activityDetails["processing_status"] = "pending"
|
||||
case types.AuditOutcomeSuccess:
|
||||
activityDetails["processing_status"] = "completed"
|
||||
case types.AuditOutcomePartial:
|
||||
activityDetails["processing_status"] = "partial"
|
||||
case types.AuditOutcomeFailed, types.AuditOutcomeDenied:
|
||||
activityDetails["processing_status"] = "failed"
|
||||
case types.AuditOutcomeCanceled:
|
||||
activityDetails["processing_status"] = "canceled"
|
||||
}
|
||||
}
|
||||
}
|
||||
var detailJSON types.JSON
|
||||
if len(activityDetails) > 0 {
|
||||
if b, err := json.Marshal(activityDetails); err == nil {
|
||||
detailJSON = types.JSON(b)
|
||||
}
|
||||
}
|
||||
actorID := auditActor(ctx)
|
||||
actorRole := ""
|
||||
if actorID != "" {
|
||||
actorRole = auditActorRole(ctx)
|
||||
}
|
||||
_ = audit.Log(ctx, &types.AuditLog{
|
||||
TenantID: tenantID,
|
||||
ActorUserID: actorID,
|
||||
ActorRole: actorRole,
|
||||
Action: action,
|
||||
ScopeType: auditScopeKnowledgeBase,
|
||||
ScopeID: kbID,
|
||||
TargetType: targetType,
|
||||
TargetID: targetID,
|
||||
Outcome: outcome,
|
||||
Details: detailJSON,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type captureKBActivityAudit struct {
|
||||
entry *types.AuditLog
|
||||
}
|
||||
|
||||
func (c *captureKBActivityAudit) Log(_ context.Context, entry *types.AuditLog) error {
|
||||
c.entry = entry
|
||||
return nil
|
||||
}
|
||||
|
||||
func (*captureKBActivityAudit) LogDenied(context.Context, *gin.Context, uint64, string, string, types.TenantRole) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (*captureKBActivityAudit) List(context.Context, uint64, *interfaces.AuditLogQuery) ([]*types.AuditLog, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (*captureKBActivityAudit) Purge(context.Context, int) (int64, error) { return 0, nil }
|
||||
|
||||
func TestRecordKBActivityCarriesInitiatorAndTaskMetadata(t *testing.T) {
|
||||
ctx := types.TaskInitiator{UserID: "user-1", Role: types.TenantRoleAdmin}.Apply(context.Background())
|
||||
ctx = withKBActivityTask(ctx, "task-1", "user")
|
||||
audit := &captureKBActivityAudit{}
|
||||
|
||||
recordKBActivity(ctx, audit, 7, "kb-1", types.AuditActionKnowledgeMoveCompleted,
|
||||
"knowledge_move", "task-1", types.AuditOutcomeSuccess, map[string]any{"count": 2})
|
||||
|
||||
if audit.entry == nil {
|
||||
t.Fatal("expected an activity entry")
|
||||
}
|
||||
if audit.entry.ActorUserID != "user-1" || audit.entry.ActorRole != "admin" {
|
||||
t.Fatalf("actor = %q/%q", audit.entry.ActorUserID, audit.entry.ActorRole)
|
||||
}
|
||||
var details map[string]any
|
||||
if err := json.Unmarshal(audit.entry.Details, &details); err != nil {
|
||||
t.Fatalf("unmarshal details: %v", err)
|
||||
}
|
||||
if details["task_id"] != "task-1" || details["trigger"] != "user" || details["count"] != float64(2) {
|
||||
t.Fatalf("details = %#v", details)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecordKBActivityCanSuppressCompositeTaskChildren(t *testing.T) {
|
||||
audit := &captureKBActivityAudit{}
|
||||
ctx := withKBActivitySuppressed(context.Background())
|
||||
recordKBActivity(ctx, audit, 7, "kb-1", types.AuditActionKnowledgeCreated,
|
||||
"knowledge", "knowledge-1", types.AuditOutcomeAccepted, nil)
|
||||
if audit.entry != nil {
|
||||
t.Fatalf("suppressed child activity was recorded: %#v", audit.entry)
|
||||
}
|
||||
}
|
||||
@@ -27,7 +27,7 @@ var (
|
||||
// in this org, with what role" rather than "is this user". The 3-D cap
|
||||
// inside CheckTenantKBPermission encodes:
|
||||
//
|
||||
// effective = min(share.Permission, tenant_org_role, tenant_role_cap)
|
||||
// effective = min(share.Permission, tenant_org_role, tenant_role_cap)
|
||||
//
|
||||
// where tenant_role_cap pins tenant Viewers to OrgRoleViewer regardless
|
||||
// of what the org-level grant said. That keeps the tenant RBAC promise
|
||||
@@ -39,6 +39,7 @@ type kbShareService struct {
|
||||
kbRepo interfaces.KnowledgeBaseRepository
|
||||
kgRepo interfaces.KnowledgeRepository
|
||||
chunkRepo interfaces.ChunkRepository
|
||||
audit interfaces.AuditLogService
|
||||
}
|
||||
|
||||
// NewKBShareService creates a new knowledge base share service
|
||||
@@ -48,6 +49,7 @@ func NewKBShareService(
|
||||
kbRepo interfaces.KnowledgeBaseRepository,
|
||||
kgRepo interfaces.KnowledgeRepository,
|
||||
chunkRepo interfaces.ChunkRepository,
|
||||
audit interfaces.AuditLogService,
|
||||
) interfaces.KBShareService {
|
||||
return &kbShareService{
|
||||
shareRepo: shareRepo,
|
||||
@@ -55,6 +57,7 @@ func NewKBShareService(
|
||||
kbRepo: kbRepo,
|
||||
kgRepo: kgRepo,
|
||||
chunkRepo: chunkRepo,
|
||||
audit: audit,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -129,12 +132,18 @@ func (s *kbShareService) ShareKnowledgeBase(ctx context.Context, kbID string, or
|
||||
if err := s.shareRepo.Update(ctx, existingShare); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
recordKBActivity(ctx, s.audit, kb.TenantID, kb.ID, types.AuditActionKBSharePermissionChanged,
|
||||
"knowledge_base_share", existingShare.ID, types.AuditOutcomeSuccess,
|
||||
map[string]any{"organization_id": orgID, "permission": permission})
|
||||
return existingShare, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Knowledge base %s shared successfully to organization %s", kbID, orgID)
|
||||
recordKBActivity(ctx, s.audit, kb.TenantID, kb.ID, types.AuditActionKBShareAdded,
|
||||
"knowledge_base_share", share.ID, types.AuditOutcomeSuccess,
|
||||
map[string]any{"organization_id": orgID, "permission": permission})
|
||||
return share, nil
|
||||
}
|
||||
|
||||
@@ -169,7 +178,13 @@ func (s *kbShareService) UpdateSharePermission(ctx context.Context, shareID stri
|
||||
share.Permission = permission
|
||||
share.UpdatedAt = time.Now()
|
||||
|
||||
return s.shareRepo.Update(ctx, share)
|
||||
if err := s.shareRepo.Update(ctx, share); err != nil {
|
||||
return err
|
||||
}
|
||||
recordKBActivity(ctx, s.audit, share.SourceTenantID, share.KnowledgeBaseID, types.AuditActionKBSharePermissionChanged,
|
||||
"knowledge_base_share", share.ID, types.AuditOutcomeSuccess,
|
||||
map[string]any{"organization_id": share.OrganizationID, "permission": permission})
|
||||
return nil
|
||||
}
|
||||
|
||||
// RemoveShare removes a share.
|
||||
@@ -184,7 +199,13 @@ func (s *kbShareService) RemoveShare(ctx context.Context, shareID string, userID
|
||||
}
|
||||
|
||||
if s.callerCanManageShare(ctx, share.SharedByUserID, share.SourceTenantID, share.OrganizationID, userID, tenantID) {
|
||||
return s.shareRepo.Delete(ctx, shareID)
|
||||
if err := s.shareRepo.Delete(ctx, shareID); err != nil {
|
||||
return err
|
||||
}
|
||||
recordKBActivity(ctx, s.audit, share.SourceTenantID, share.KnowledgeBaseID, types.AuditActionKBShareRemoved,
|
||||
"knowledge_base_share", share.ID, types.AuditOutcomeSuccess,
|
||||
map[string]any{"organization_id": share.OrganizationID, "permission": share.Permission})
|
||||
return nil
|
||||
}
|
||||
|
||||
return ErrSharePermissionDenied
|
||||
|
||||
@@ -77,6 +77,7 @@ type knowledgeService struct {
|
||||
// handled because the public surface is the SpanTracker interface,
|
||||
// which has a no-op fallback. See knowledge_span_tracker.go.
|
||||
spanTracker SpanTracker
|
||||
audit interfaces.AuditLogService
|
||||
}
|
||||
|
||||
const (
|
||||
@@ -113,6 +114,7 @@ func NewKnowledgeService(
|
||||
wikiService interfaces.WikiPageService,
|
||||
taskPendingRepo interfaces.TaskPendingOpsRepository,
|
||||
spanTracker SpanTracker,
|
||||
audit interfaces.AuditLogService,
|
||||
) (interfaces.KnowledgeService, error) {
|
||||
return &knowledgeService{
|
||||
config: config,
|
||||
@@ -141,6 +143,7 @@ func NewKnowledgeService(
|
||||
wikiService: wikiService,
|
||||
taskPendingRepo: taskPendingRepo,
|
||||
spanTracker: spanTracker,
|
||||
audit: audit,
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -459,6 +459,8 @@ func (s *knowledgeService) ProcessKBClone(ctx context.Context, t *asynq.Task) er
|
||||
if err := json.Unmarshal(t.Payload(), &payload); err != nil {
|
||||
return fmt.Errorf("failed to unmarshal KB clone payload: %w", err)
|
||||
}
|
||||
ctx = payload.Initiator.Apply(ctx)
|
||||
ctx = withKBActivityTask(ctx, payload.TaskID, "user")
|
||||
|
||||
// Add tenant ID to context
|
||||
ctx = context.WithValue(ctx, types.TenantIDContextKey, payload.TenantID)
|
||||
@@ -487,6 +489,9 @@ func (s *knowledgeService) ProcessKBClone(ctx context.Context, t *asynq.Task) er
|
||||
progress.Message = message
|
||||
progress.UpdatedAt = time.Now().Unix()
|
||||
_ = s.saveKBCloneProgress(ctx, progress)
|
||||
recordKBActivity(ctx, s.audit, payload.TenantID, payload.TargetID, types.AuditActionKBCloneFailed,
|
||||
"knowledge_base", payload.TargetID, types.AuditOutcomeFailed,
|
||||
map[string]any{"source_kb_id": payload.SourceID, "task_id": payload.TaskID})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -511,10 +516,21 @@ func (s *knowledgeService) ProcessKBClone(ctx context.Context, t *asynq.Task) er
|
||||
handleError(progress, err, "Failed to copy knowledge base configuration")
|
||||
return err
|
||||
}
|
||||
if retryCount == 0 {
|
||||
recordKBActivity(ctx, s.audit, payload.TenantID, payload.TargetID, types.AuditActionKBCloneStarted,
|
||||
"knowledge_base", payload.TargetID, types.AuditOutcomeAccepted,
|
||||
map[string]any{"source_kb_id": payload.SourceID, "task_id": payload.TaskID})
|
||||
}
|
||||
|
||||
// Use different sync strategies based on knowledge base type
|
||||
if srcKB.Type == types.KnowledgeBaseTypeFAQ {
|
||||
return s.cloneFAQKnowledgeBase(ctx, srcKB, dstKB, progress, handleError)
|
||||
if err := s.cloneFAQKnowledgeBase(ctx, srcKB, dstKB, progress, handleError); err != nil {
|
||||
return err
|
||||
}
|
||||
recordKBActivity(ctx, s.audit, payload.TenantID, payload.TargetID, types.AuditActionKBCloneCompleted,
|
||||
"knowledge_base", payload.TargetID, types.AuditOutcomeSuccess,
|
||||
map[string]any{"source_kb_id": payload.SourceID, "task_id": payload.TaskID, "total": progress.Total})
|
||||
return nil
|
||||
}
|
||||
|
||||
// Document type: use Knowledge-level diff based on file_hash
|
||||
@@ -616,6 +632,9 @@ func (s *knowledgeService) ProcessKBClone(ctx context.Context, t *asynq.Task) er
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "KB clone task completed: %s", payload.TaskID)
|
||||
recordKBActivity(ctx, s.audit, payload.TenantID, payload.TargetID, types.AuditActionKBCloneCompleted,
|
||||
"knowledge_base", payload.TargetID, types.AuditOutcomeSuccess,
|
||||
map[string]any{"source_kb_id": payload.SourceID, "task_id": payload.TaskID, "total": totalOperations})
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -975,6 +994,8 @@ func (s *knowledgeService) ProcessKnowledgeMove(ctx context.Context, t *asynq.Ta
|
||||
if err := json.Unmarshal(t.Payload(), &payload); err != nil {
|
||||
return fmt.Errorf("failed to unmarshal knowledge move payload: %w", err)
|
||||
}
|
||||
ctx = payload.Initiator.Apply(ctx)
|
||||
ctx = withKBActivityTask(ctx, payload.TaskID, "user")
|
||||
|
||||
// Add tenant ID to context
|
||||
ctx = context.WithValue(ctx, types.TenantIDContextKey, payload.TenantID)
|
||||
@@ -1003,6 +1024,20 @@ func (s *knowledgeService) ProcessKnowledgeMove(ctx context.Context, t *asynq.Ta
|
||||
progress.Message = message
|
||||
progress.UpdatedAt = time.Now().Unix()
|
||||
_ = s.saveKnowledgeMoveProgress(ctx, progress)
|
||||
for _, kbID := range []string{payload.SourceKBID, payload.TargetKBID} {
|
||||
recordKBActivity(ctx, s.audit, payload.TenantID, kbID, types.AuditActionKnowledgeMoveFailed,
|
||||
"knowledge_move", payload.TaskID, types.AuditOutcomeFailed,
|
||||
map[string]any{"source_kb_id": payload.SourceKBID, "target_kb_id": payload.TargetKBID,
|
||||
"task_id": payload.TaskID, "count": len(payload.KnowledgeIDs), "mode": payload.Mode})
|
||||
}
|
||||
}
|
||||
}
|
||||
if retryCount == 0 {
|
||||
for _, kbID := range []string{payload.SourceKBID, payload.TargetKBID} {
|
||||
recordKBActivity(ctx, s.audit, payload.TenantID, kbID, types.AuditActionKnowledgeMoveStarted,
|
||||
"knowledge_move", payload.TaskID, types.AuditOutcomeAccepted,
|
||||
map[string]any{"source_kb_id": payload.SourceKBID, "target_kb_id": payload.TargetKBID,
|
||||
"task_id": payload.TaskID, "count": len(payload.KnowledgeIDs), "mode": payload.Mode})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1072,6 +1107,20 @@ func (s *knowledgeService) ProcessKnowledgeMove(ctx context.Context, t *asynq.Ta
|
||||
_ = s.saveKnowledgeMoveProgress(ctx, progress)
|
||||
|
||||
logger.Infof(ctx, "ProcessKnowledgeMove: task=%s completed, processed=%d, failed=%d", payload.TaskID, progress.Processed, progress.Failed)
|
||||
outcome := types.AuditOutcomeSuccess
|
||||
action := types.AuditActionKnowledgeMoveCompleted
|
||||
if progress.Failed == progress.Total && progress.Total > 0 {
|
||||
outcome = types.AuditOutcomeFailed
|
||||
action = types.AuditActionKnowledgeMoveFailed
|
||||
} else if progress.Failed > 0 {
|
||||
outcome = types.AuditOutcomePartial
|
||||
}
|
||||
for _, kbID := range []string{payload.SourceKBID, payload.TargetKBID} {
|
||||
recordKBActivity(ctx, s.audit, payload.TenantID, kbID, action,
|
||||
"knowledge_move", payload.TaskID, outcome,
|
||||
map[string]any{"source_kb_id": payload.SourceKBID, "target_kb_id": payload.TargetKBID,
|
||||
"task_id": payload.TaskID, "count": progress.Total, "failed": progress.Failed, "mode": payload.Mode})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -232,7 +232,6 @@ func (s *knowledgeService) CreateKnowledgeFromFile(ctx context.Context,
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Set tag relations
|
||||
if err := s.setAndAttachKnowledgeTags(ctx, tenantID, kbID, knowledge, tagIDs); err != nil {
|
||||
logger.Errorf(ctx, "Failed to set knowledge tags, knowledge ID: %s, error: %v", knowledge.ID, err)
|
||||
@@ -267,6 +266,12 @@ func (s *knowledgeService) CreateKnowledgeFromFile(ctx context.Context,
|
||||
payloadBytes, err := json.Marshal(taskPayload)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to marshal document process task payload: %v", err)
|
||||
s.markKnowledgeEnqueueFailed(ctx, knowledge)
|
||||
recordKBActivity(ctx, s.audit, knowledge.TenantID, kbID, types.AuditActionKnowledgeCreated,
|
||||
"knowledge", knowledge.ID, types.AuditOutcomeFailed, map[string]any{
|
||||
"title": knowledge.Title, "source_type": "file", "file_type": knowledge.FileType,
|
||||
"processing_status": "failed", "failure_stage": "enqueue",
|
||||
})
|
||||
// 即使入队失败,也返回knowledge,因为文件已保存
|
||||
return knowledge, nil
|
||||
}
|
||||
@@ -279,9 +284,20 @@ func (s *knowledgeService) CreateKnowledgeFromFile(ctx context.Context,
|
||||
info, err := s.task.Enqueue(task)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to enqueue document process task: %v", err)
|
||||
s.markKnowledgeEnqueueFailed(ctx, knowledge)
|
||||
recordKBActivity(ctx, s.audit, knowledge.TenantID, kbID, types.AuditActionKnowledgeCreated,
|
||||
"knowledge", knowledge.ID, types.AuditOutcomeFailed, map[string]any{
|
||||
"title": knowledge.Title, "source_type": "file", "file_type": knowledge.FileType,
|
||||
"processing_status": "failed", "failure_stage": "enqueue",
|
||||
})
|
||||
// 即使入队失败,也返回knowledge,因为文件已保存
|
||||
return knowledge, nil
|
||||
}
|
||||
recordKBActivity(ctx, s.audit, knowledge.TenantID, kbID, types.AuditActionKnowledgeCreated,
|
||||
"knowledge", knowledge.ID, types.AuditOutcomeAccepted, map[string]any{
|
||||
"title": knowledge.Title, "source_type": "file", "file_type": knowledge.FileType,
|
||||
"processing_status": "pending", "task_id": info.ID, "trigger": kbActivityTrigger(ctx),
|
||||
})
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"Enqueued document process task: id=%s queue=%s knowledge_id=%s",
|
||||
@@ -417,7 +433,6 @@ func (s *knowledgeService) CreateKnowledgeFromURL(ctx context.Context,
|
||||
logger.Errorf(ctx, "Failed to create knowledge record: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Set tag relations
|
||||
if err := s.setAndAttachKnowledgeTags(ctx, tenantID, kbID, knowledge, tagIDs); err != nil {
|
||||
logger.Errorf(ctx, "Failed to set knowledge tags, knowledge ID: %s, error: %v", knowledge.ID, err)
|
||||
@@ -449,6 +464,12 @@ func (s *knowledgeService) CreateKnowledgeFromURL(ctx context.Context,
|
||||
payloadBytes, err := json.Marshal(taskPayload)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to marshal URL process task payload: %v", err)
|
||||
s.markKnowledgeEnqueueFailed(ctx, knowledge)
|
||||
recordKBActivity(ctx, s.audit, tenantID, kbID, types.AuditActionKnowledgeCreated,
|
||||
"knowledge", knowledge.ID, types.AuditOutcomeFailed, map[string]any{
|
||||
"title": knowledge.Title, "source_type": "url", "file_type": knowledge.FileType,
|
||||
"processing_status": "failed", "failure_stage": "enqueue",
|
||||
})
|
||||
return knowledge, nil
|
||||
}
|
||||
|
||||
@@ -460,8 +481,19 @@ func (s *knowledgeService) CreateKnowledgeFromURL(ctx context.Context,
|
||||
info, err := s.task.Enqueue(task)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to enqueue URL process task: %v", err)
|
||||
s.markKnowledgeEnqueueFailed(ctx, knowledge)
|
||||
recordKBActivity(ctx, s.audit, tenantID, kbID, types.AuditActionKnowledgeCreated,
|
||||
"knowledge", knowledge.ID, types.AuditOutcomeFailed, map[string]any{
|
||||
"title": knowledge.Title, "source_type": "url", "file_type": knowledge.FileType,
|
||||
"processing_status": "failed", "failure_stage": "enqueue",
|
||||
})
|
||||
return knowledge, nil
|
||||
}
|
||||
recordKBActivity(ctx, s.audit, tenantID, kbID, types.AuditActionKnowledgeCreated,
|
||||
"knowledge", knowledge.ID, types.AuditOutcomeAccepted, map[string]any{
|
||||
"title": knowledge.Title, "source_type": "url", "file_type": knowledge.FileType,
|
||||
"processing_status": "pending", "task_id": info.ID, "trigger": kbActivityTrigger(ctx),
|
||||
})
|
||||
logger.Infof(ctx, "Enqueued URL process task: id=%s queue=%s knowledge_id=%s", info.ID, info.Queue, knowledge.ID)
|
||||
|
||||
logger.Infof(ctx, "Knowledge from URL created successfully, ID: %s", knowledge.ID)
|
||||
@@ -655,7 +687,6 @@ func (s *knowledgeService) createKnowledgeFromFileURL(
|
||||
logger.Errorf(ctx, "Failed to create knowledge record: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Set tag relations
|
||||
if err := s.setAndAttachKnowledgeTags(ctx, tenantID, kbID, knowledge, tagIDs); err != nil {
|
||||
logger.Errorf(ctx, "Failed to set knowledge tags, knowledge ID: %s, error: %v", knowledge.ID, err)
|
||||
@@ -688,6 +719,12 @@ func (s *knowledgeService) createKnowledgeFromFileURL(
|
||||
payloadBytes, err := json.Marshal(taskPayload)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to marshal file URL process task payload: %v", err)
|
||||
s.markKnowledgeEnqueueFailed(ctx, knowledge)
|
||||
recordKBActivity(ctx, s.audit, tenantID, kbID, types.AuditActionKnowledgeCreated,
|
||||
"knowledge", knowledge.ID, types.AuditOutcomeFailed, map[string]any{
|
||||
"title": knowledge.Title, "source_type": "file_url", "file_type": knowledge.FileType,
|
||||
"processing_status": "failed", "failure_stage": "enqueue",
|
||||
})
|
||||
return knowledge, nil
|
||||
}
|
||||
|
||||
@@ -699,8 +736,19 @@ func (s *knowledgeService) createKnowledgeFromFileURL(
|
||||
info, err := s.task.Enqueue(task)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to enqueue file URL process task: %v", err)
|
||||
s.markKnowledgeEnqueueFailed(ctx, knowledge)
|
||||
recordKBActivity(ctx, s.audit, tenantID, kbID, types.AuditActionKnowledgeCreated,
|
||||
"knowledge", knowledge.ID, types.AuditOutcomeFailed, map[string]any{
|
||||
"title": knowledge.Title, "source_type": "file_url", "file_type": knowledge.FileType,
|
||||
"processing_status": "failed", "failure_stage": "enqueue",
|
||||
})
|
||||
return knowledge, nil
|
||||
}
|
||||
recordKBActivity(ctx, s.audit, tenantID, kbID, types.AuditActionKnowledgeCreated,
|
||||
"knowledge", knowledge.ID, types.AuditOutcomeAccepted, map[string]any{
|
||||
"title": knowledge.Title, "source_type": "file_url", "file_type": knowledge.FileType,
|
||||
"processing_status": "pending", "task_id": info.ID, "trigger": kbActivityTrigger(ctx),
|
||||
})
|
||||
logger.Infof(ctx, "Enqueued file URL process task: id=%s queue=%s knowledge_id=%s", info.ID, info.Queue, knowledge.ID)
|
||||
|
||||
logger.Infof(ctx, "Knowledge from file URL created successfully, ID: %s", knowledge.ID)
|
||||
@@ -808,7 +856,6 @@ func (s *knowledgeService) CreateKnowledgeFromManual(ctx context.Context,
|
||||
logger.Errorf(ctx, "Failed to create manual knowledge record: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Set tag relations
|
||||
if err := s.setAndAttachKnowledgeTags(ctx, tenantID, kbID, knowledge, payload.TagIDs); err != nil {
|
||||
logger.Errorf(ctx, "Failed to set knowledge tags, knowledge ID: %s, error: %v", knowledge.ID, err)
|
||||
@@ -817,13 +864,30 @@ func (s *knowledgeService) CreateKnowledgeFromManual(ctx context.Context,
|
||||
|
||||
if status == types.ManualKnowledgeStatusPublish {
|
||||
logger.Infof(ctx, "Manual knowledge created, enqueuing async processing task, ID: %s", knowledge.ID)
|
||||
if err := s.enqueueManualProcessing(ctx, knowledge, cleanContent, false); err != nil {
|
||||
taskID, err := s.enqueueManualProcessing(ctx, knowledge, cleanContent, false)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to enqueue manual processing task for new knowledge: %v", err)
|
||||
// Non-fatal: mark as failed so user can retry
|
||||
knowledge.ParseStatus = "failed"
|
||||
knowledge.ErrorMessage = "Failed to enqueue processing task"
|
||||
s.repo.UpdateKnowledge(ctx, knowledge)
|
||||
recordKBActivity(ctx, s.audit, tenantID, kbID, types.AuditActionKnowledgeCreated,
|
||||
"knowledge", knowledge.ID, types.AuditOutcomeFailed, map[string]any{
|
||||
"title": knowledge.Title, "source_type": "manual", "status": status,
|
||||
"processing_status": "failed", "failure_stage": "enqueue",
|
||||
})
|
||||
} else {
|
||||
recordKBActivity(ctx, s.audit, tenantID, kbID, types.AuditActionKnowledgeCreated,
|
||||
"knowledge", knowledge.ID, types.AuditOutcomeAccepted, map[string]any{
|
||||
"title": knowledge.Title, "source_type": "manual", "status": status,
|
||||
"processing_status": "pending", "task_id": taskID, "trigger": kbActivityTrigger(ctx),
|
||||
})
|
||||
}
|
||||
} else {
|
||||
recordKBActivity(ctx, s.audit, tenantID, kbID, types.AuditActionKnowledgeCreated,
|
||||
"knowledge", knowledge.ID, types.AuditOutcomeSuccess, map[string]any{
|
||||
"title": knowledge.Title, "source_type": "manual", "status": status,
|
||||
})
|
||||
}
|
||||
|
||||
return knowledge, nil
|
||||
@@ -885,11 +949,14 @@ func (s *knowledgeService) createKnowledgeFromPassageInternal(ctx context.Contex
|
||||
logger.Errorf(ctx, "Failed to create knowledge record: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Process passages
|
||||
if syncMode {
|
||||
logger.Info(ctx, "Processing passage synchronously")
|
||||
s.processDocumentFromPassage(ctx, kb, knowledge, safePassages)
|
||||
recordKBActivity(ctx, s.audit, knowledge.TenantID, kbID, types.AuditActionKnowledgeCreated,
|
||||
"knowledge", knowledge.ID, types.AuditOutcomeSuccess, map[string]any{
|
||||
"title": knowledge.Title, "source_type": "passage", "processing_status": knowledge.ParseStatus,
|
||||
})
|
||||
logger.Infof(ctx, "Knowledge from passage created successfully (sync), ID: %s", knowledge.ID)
|
||||
} else {
|
||||
// Enqueue passage processing task to Asynq
|
||||
@@ -922,6 +989,12 @@ func (s *knowledgeService) createKnowledgeFromPassageInternal(ctx context.Contex
|
||||
payloadBytes, err := json.Marshal(taskPayload)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to marshal passage process task payload: %v", err)
|
||||
s.markKnowledgeEnqueueFailed(ctx, knowledge)
|
||||
recordKBActivity(ctx, s.audit, knowledge.TenantID, kbID, types.AuditActionKnowledgeCreated,
|
||||
"knowledge", knowledge.ID, types.AuditOutcomeFailed, map[string]any{
|
||||
"title": knowledge.Title, "source_type": "passage",
|
||||
"processing_status": "failed", "failure_stage": "enqueue",
|
||||
})
|
||||
// 即使入队失败,也返回knowledge
|
||||
return knowledge, nil
|
||||
}
|
||||
@@ -934,8 +1007,19 @@ func (s *knowledgeService) createKnowledgeFromPassageInternal(ctx context.Contex
|
||||
info, err := s.task.Enqueue(task)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to enqueue passage process task: %v", err)
|
||||
s.markKnowledgeEnqueueFailed(ctx, knowledge)
|
||||
recordKBActivity(ctx, s.audit, knowledge.TenantID, kbID, types.AuditActionKnowledgeCreated,
|
||||
"knowledge", knowledge.ID, types.AuditOutcomeFailed, map[string]any{
|
||||
"title": knowledge.Title, "source_type": "passage",
|
||||
"processing_status": "failed", "failure_stage": "enqueue",
|
||||
})
|
||||
return knowledge, nil
|
||||
}
|
||||
recordKBActivity(ctx, s.audit, knowledge.TenantID, kbID, types.AuditActionKnowledgeCreated,
|
||||
"knowledge", knowledge.ID, types.AuditOutcomeAccepted, map[string]any{
|
||||
"title": knowledge.Title, "source_type": "passage", "processing_status": "pending",
|
||||
"task_id": info.ID, "trigger": kbActivityTrigger(ctx),
|
||||
})
|
||||
logger.Infof(ctx, "Enqueued passage process task: id=%s queue=%s knowledge_id=%s", info.ID, info.Queue, knowledge.ID)
|
||||
logger.Infof(ctx, "Knowledge from passage created successfully, ID: %s", knowledge.ID)
|
||||
}
|
||||
@@ -1025,6 +1109,10 @@ func (s *knowledgeService) UpdateManualKnowledge(ctx context.Context,
|
||||
logger.Errorf(ctx, "Failed to persist manual draft: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
recordKBActivity(ctx, s.audit, tenantID, existing.KnowledgeBaseID, types.AuditActionKnowledgeUpdated,
|
||||
"knowledge", existing.ID, types.AuditOutcomeSuccess, map[string]any{
|
||||
"title": existing.Title, "status": status,
|
||||
})
|
||||
return existing, nil
|
||||
}
|
||||
|
||||
@@ -1043,21 +1131,32 @@ func (s *knowledgeService) UpdateManualKnowledge(ctx context.Context,
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Manual knowledge updated, enqueuing async processing task, ID: %s", existing.ID)
|
||||
if err := s.enqueueManualProcessing(ctx, existing, cleanContent, true); err != nil {
|
||||
taskID, err := s.enqueueManualProcessing(ctx, existing, cleanContent, true)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to enqueue manual processing task: %v", err)
|
||||
// Non-fatal: mark as failed so user can retry
|
||||
existing.ParseStatus = "failed"
|
||||
existing.ErrorMessage = "Failed to enqueue processing task"
|
||||
s.repo.UpdateKnowledge(ctx, existing)
|
||||
recordKBActivity(ctx, s.audit, tenantID, existing.KnowledgeBaseID, types.AuditActionKnowledgeUpdated,
|
||||
"knowledge", existing.ID, types.AuditOutcomeFailed, map[string]any{
|
||||
"title": existing.Title, "status": status,
|
||||
"processing_status": "failed", "failure_stage": "enqueue",
|
||||
})
|
||||
return nil, werrors.NewInternalServerError("Failed to submit processing task")
|
||||
}
|
||||
recordKBActivity(ctx, s.audit, tenantID, existing.KnowledgeBaseID, types.AuditActionKnowledgeUpdated,
|
||||
"knowledge", existing.ID, types.AuditOutcomeAccepted, map[string]any{
|
||||
"title": existing.Title, "status": status, "processing_status": "pending",
|
||||
"task_id": taskID, "trigger": kbActivityTrigger(ctx),
|
||||
})
|
||||
return existing, nil
|
||||
}
|
||||
|
||||
// enqueueManualProcessing enqueues a manual:process Asynq task for async cleanup + re-indexing.
|
||||
func (s *knowledgeService) enqueueManualProcessing(ctx context.Context,
|
||||
knowledge *types.Knowledge, content string, needCleanup bool,
|
||||
) error {
|
||||
) (string, error) {
|
||||
requestID, _ := types.RequestIDFromContext(ctx)
|
||||
payload := types.ManualProcessPayload{
|
||||
RequestId: requestID,
|
||||
@@ -1070,17 +1169,31 @@ func (s *knowledgeService) enqueueManualProcessing(ctx context.Context,
|
||||
langfuse.InjectTracing(ctx, &payload)
|
||||
payloadBytes, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to marshal manual process payload: %w", err)
|
||||
return "", fmt.Errorf("failed to marshal manual process payload: %w", err)
|
||||
}
|
||||
|
||||
task := asynq.NewTask(types.TypeManualProcess, payloadBytes,
|
||||
asynq.Queue(types.QueueDefault), asynq.MaxRetry(3), asynq.Timeout(30*time.Minute))
|
||||
info, err := s.task.Enqueue(task)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to enqueue manual process task: %w", err)
|
||||
return "", fmt.Errorf("failed to enqueue manual process task: %w", err)
|
||||
}
|
||||
logger.Infof(ctx, "Enqueued manual process task: knowledge_id=%s, asynq_id=%s", knowledge.ID, info.ID)
|
||||
return nil
|
||||
return info.ID, nil
|
||||
}
|
||||
|
||||
// markKnowledgeEnqueueFailed prevents a durable knowledge row from remaining
|
||||
// indefinitely "pending" when its background processing task was never
|
||||
// created. The API may still return the row so callers can retry it.
|
||||
func (s *knowledgeService) markKnowledgeEnqueueFailed(ctx context.Context, knowledge *types.Knowledge) {
|
||||
if knowledge == nil {
|
||||
return
|
||||
}
|
||||
knowledge.ParseStatus = "failed"
|
||||
knowledge.ErrorMessage = "Failed to enqueue processing task"
|
||||
if err := s.repo.UpdateKnowledge(ctx, knowledge); err != nil {
|
||||
logger.Errorf(ctx, "Failed to mark knowledge as failed after enqueue error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func ensureManualFileName(title string) string {
|
||||
|
||||
@@ -197,6 +197,9 @@ func (s *knowledgeService) DeleteKnowledge(ctx context.Context, id string) error
|
||||
if err := s.tenantRepo.AdjustStorageUsed(ctx, tenantInfo.ID, -knowledge.StorageSize); err != nil {
|
||||
logger.GetLogger(ctx).WithField("error", err).Errorf("DeleteKnowledge update tenant storage used failed")
|
||||
}
|
||||
recordKBActivity(ctx, s.audit, tenantID, knowledge.KnowledgeBaseID, types.AuditActionKnowledgeDeleted,
|
||||
"knowledge", knowledge.ID, types.AuditOutcomeSuccess,
|
||||
map[string]any{"title": knowledge.Title, "type": knowledge.Type})
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -626,6 +629,18 @@ func (s *knowledgeService) DeleteKnowledgeList(ctx context.Context, ids []string
|
||||
if err := s.tenantRepo.AdjustStorageUsed(ctx, tenantInfo.ID, storageAdjust); err != nil {
|
||||
logger.GetLogger(ctx).WithField("error", err).Errorf("DeleteKnowledge update tenant storage used failed")
|
||||
}
|
||||
byKB := make(map[string][]string)
|
||||
for _, knowledge := range knowledgeList {
|
||||
byKB[knowledge.KnowledgeBaseID] = append(byKB[knowledge.KnowledgeBaseID], knowledge.ID)
|
||||
}
|
||||
for kbID, knowledgeIDs := range byKB {
|
||||
details := map[string]any{"count": len(knowledgeIDs)}
|
||||
if len(knowledgeIDs) <= 20 {
|
||||
details["knowledge_ids"] = knowledgeIDs
|
||||
}
|
||||
recordKBActivity(ctx, s.audit, tenantInfo.ID, kbID, types.AuditActionKnowledgeBatchDeleted,
|
||||
"knowledge", "", types.AuditOutcomeSuccess, details)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -723,6 +738,9 @@ func (s *knowledgeService) ProcessKnowledgeListDelete(ctx context.Context, t *as
|
||||
logger.Errorf(ctx, "Failed to unmarshal knowledge list delete payload: %v", err)
|
||||
return err
|
||||
}
|
||||
ctx = payload.Initiator.Apply(ctx)
|
||||
taskID, _ := asynq.GetTaskID(ctx)
|
||||
ctx = withKBActivityTask(ctx, taskID, "user")
|
||||
|
||||
logger.Infof(ctx, "Processing knowledge list delete task for %d knowledge items", len(payload.KnowledgeIDs))
|
||||
|
||||
|
||||
@@ -245,6 +245,9 @@ func (s *knowledgeService) CreateFAQEntry(ctx context.Context,
|
||||
entry.TagName = tag.Name
|
||||
}
|
||||
}
|
||||
recordKBActivity(ctx, s.audit, tenantID, kb.ID, types.AuditActionKnowledgeCreated,
|
||||
"faq_entry", chunk.ID, types.AuditOutcomeSuccess,
|
||||
map[string]any{"entry_id": chunk.SeqID, "source_type": "faq"})
|
||||
|
||||
return entry, nil
|
||||
}
|
||||
@@ -303,7 +306,6 @@ func (s *knowledgeService) GetFAQEntry(ctx context.Context,
|
||||
entry.TagName = tag.Name
|
||||
}
|
||||
}
|
||||
|
||||
return entry, nil
|
||||
}
|
||||
|
||||
@@ -466,6 +468,9 @@ func (s *knowledgeService) UpdateFAQEntry(ctx context.Context,
|
||||
entry.TagName = tag.Name
|
||||
}
|
||||
}
|
||||
recordKBActivity(ctx, s.audit, tenantID, kb.ID, types.AuditActionKnowledgeUpdated,
|
||||
"faq_entry", chunk.ID, types.AuditOutcomeSuccess,
|
||||
map[string]any{"entry_id": chunk.SeqID, "source_type": "faq"})
|
||||
|
||||
return entry, nil
|
||||
}
|
||||
@@ -655,6 +660,9 @@ func (s *knowledgeService) UpdateFAQEntryStatus(ctx context.Context,
|
||||
if err := retrieveEngine.BatchUpdateChunkEnabledStatus(ctx, chunkStatusMap); err != nil {
|
||||
return err
|
||||
}
|
||||
recordKBActivity(ctx, s.audit, tenantID, kb.ID, types.AuditActionKnowledgeUpdated,
|
||||
"faq_entry", chunk.ID, types.AuditOutcomeSuccess,
|
||||
map[string]any{"entry_id": chunk.SeqID, "changed_fields": []string{"enabled"}})
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -857,6 +865,9 @@ func (s *knowledgeService) UpdateFAQEntryFieldsBatch(ctx context.Context,
|
||||
}
|
||||
}
|
||||
}
|
||||
recordKBActivity(ctx, s.audit, tenantID, kb.ID, types.AuditActionKnowledgeUpdated,
|
||||
"faq_entry", "", types.AuditOutcomeSuccess,
|
||||
map[string]any{"count": len(req.ByID), "tag_groups": len(req.ByTag), "batch": true})
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1387,6 +1398,9 @@ func (s *knowledgeService) DeleteFAQEntries(ctx context.Context,
|
||||
return err
|
||||
}
|
||||
}
|
||||
recordKBActivity(ctx, s.audit, tenantID, kb.ID, types.AuditActionKnowledgeBatchDeleted,
|
||||
"faq_entry", "", types.AuditOutcomeSuccess,
|
||||
map[string]any{"count": len(chunksToRemove), "source_type": "faq"})
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -903,7 +903,6 @@ func (s *knowledgeService) ProcessSummaryGeneration(ctx context.Context, t *asyn
|
||||
logger.Errorf(ctx, "Failed to unmarshal summary generation payload: %v", err)
|
||||
return nil // Don't retry on unmarshal error
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Processing summary generation for knowledge: %s", payload.KnowledgeID)
|
||||
|
||||
// Set tenant and language context
|
||||
@@ -2030,6 +2029,11 @@ func (s *knowledgeService) ReparseKnowledge(
|
||||
if kb != nil && kb.IsWikiEnabled() {
|
||||
s.prepareWikiForReparse(ctx, existing)
|
||||
}
|
||||
recordReparseStarted := func() {
|
||||
recordKBActivity(ctx, s.audit, tenantID, existing.KnowledgeBaseID, types.AuditActionKnowledgeReparseStarted,
|
||||
"knowledge", existing.ID, types.AuditOutcomeAccepted,
|
||||
map[string]any{"title": existing.Title, "type": existing.Type, "attempt": reparseAttempt})
|
||||
}
|
||||
|
||||
// For manual knowledge, use async manual processing (cleanup + re-indexing in worker)
|
||||
if existing.IsManual() {
|
||||
@@ -2061,11 +2065,13 @@ func (s *knowledgeService) ReparseKnowledge(
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := s.enqueueManualProcessing(ctx, existing, meta.Content, true); err != nil {
|
||||
if _, err := s.enqueueManualProcessing(ctx, existing, meta.Content, true); err != nil {
|
||||
logger.Errorf(ctx, "Failed to enqueue manual reparse task: %v", err)
|
||||
existing.ParseStatus = "failed"
|
||||
existing.ErrorMessage = "Failed to enqueue processing task"
|
||||
s.repo.UpdateKnowledge(ctx, existing)
|
||||
} else {
|
||||
recordReparseStarted()
|
||||
}
|
||||
return existing, nil
|
||||
}
|
||||
@@ -2148,6 +2154,7 @@ func (s *knowledgeService) ReparseKnowledge(
|
||||
return existing, nil
|
||||
}
|
||||
logger.Infof(ctx, "Enqueued reparse task: id=%s queue=%s knowledge_id=%s", info.ID, info.Queue, existing.ID)
|
||||
recordReparseStarted()
|
||||
|
||||
// For data tables (csv, xlsx, xls), also enqueue summary task
|
||||
if slices.Contains([]string{"csv", "xlsx", "xls"}, getFileType(existing.FileName)) {
|
||||
@@ -2201,6 +2208,7 @@ func (s *knowledgeService) ReparseKnowledge(
|
||||
return existing, nil
|
||||
}
|
||||
logger.Infof(ctx, "Enqueued file URL reparse task: id=%s queue=%s knowledge_id=%s", info.ID, info.Queue, existing.ID)
|
||||
recordReparseStarted()
|
||||
|
||||
return existing, nil
|
||||
}
|
||||
@@ -2247,6 +2255,7 @@ func (s *knowledgeService) ReparseKnowledge(
|
||||
return existing, nil
|
||||
}
|
||||
logger.Infof(ctx, "Enqueued URL reparse task: id=%s queue=%s knowledge_id=%s", info.ID, info.Queue, existing.ID)
|
||||
recordReparseStarted()
|
||||
|
||||
return existing, nil
|
||||
}
|
||||
@@ -2351,6 +2360,9 @@ func (s *knowledgeService) CancelKnowledgeParse(
|
||||
// at isWikiKnowledgeAborted anyway, but scrubbing avoids waking the
|
||||
// batch in the first place.
|
||||
s.scrubWikiPendingIngest(ctx, existing.KnowledgeBaseID, knowledgeID, "cancel")
|
||||
recordKBActivity(ctx, s.audit, tenantID, existing.KnowledgeBaseID, types.AuditActionKnowledgeParseCanceled,
|
||||
"knowledge", existing.ID, types.AuditOutcomeCanceled,
|
||||
map[string]any{"title": existing.Title, "type": existing.Type})
|
||||
return existing, nil
|
||||
}
|
||||
|
||||
@@ -3405,6 +3417,9 @@ func (s *knowledgeService) ProcessKnowledgeListReparse(ctx context.Context, t *a
|
||||
logger.Errorf(ctx, "Failed to unmarshal knowledge list reparse payload: %v", err)
|
||||
return err
|
||||
}
|
||||
ctx = payload.Initiator.Apply(ctx)
|
||||
taskID, _ := asynq.GetTaskID(ctx)
|
||||
ctx = withKBActivityTask(ctx, taskID, "user")
|
||||
|
||||
logger.Infof(ctx, "Processing knowledge list reparse task for %d knowledge items", len(payload.KnowledgeIDs))
|
||||
|
||||
|
||||
@@ -43,6 +43,7 @@ type knowledgeBaseService struct {
|
||||
dsRepo interfaces.DataSourceRepository
|
||||
syncLogRepo interfaces.SyncLogRepository
|
||||
dsScheduler *datasource.Scheduler
|
||||
audit interfaces.AuditLogService
|
||||
}
|
||||
|
||||
// NewKnowledgeBaseService creates a new knowledge base service
|
||||
@@ -62,6 +63,7 @@ func NewKnowledgeBaseService(repo interfaces.KnowledgeBaseRepository,
|
||||
dsRepo interfaces.DataSourceRepository,
|
||||
syncLogRepo interfaces.SyncLogRepository,
|
||||
dsScheduler *datasource.Scheduler,
|
||||
audit interfaces.AuditLogService,
|
||||
) interfaces.KnowledgeBaseService {
|
||||
return &knowledgeBaseService{
|
||||
repo: repo,
|
||||
@@ -80,6 +82,7 @@ func NewKnowledgeBaseService(repo interfaces.KnowledgeBaseRepository,
|
||||
dsRepo: dsRepo,
|
||||
syncLogRepo: syncLogRepo,
|
||||
dsScheduler: dsScheduler,
|
||||
audit: audit,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -151,6 +154,10 @@ func (s *knowledgeBaseService) CreateKnowledgeBase(ctx context.Context,
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
recordKBActivity(ctx, s.audit, kb.TenantID, kb.ID, types.AuditActionKBCreated,
|
||||
"knowledge_base", kb.ID, types.AuditOutcomeSuccess, map[string]any{
|
||||
"name": kb.Name, "type": kb.Type,
|
||||
})
|
||||
|
||||
logger.Infof(ctx, "Knowledge base created successfully, ID: %s, name: %s", kb.ID, kb.Name)
|
||||
return kb, nil
|
||||
@@ -485,6 +492,17 @@ func (s *knowledgeBaseService) UpdateKnowledgeBase(ctx context.Context,
|
||||
return nil, err
|
||||
}
|
||||
|
||||
changedFields := make([]string, 0, 3)
|
||||
if kb.Name != name {
|
||||
changedFields = append(changedFields, "name")
|
||||
}
|
||||
if kb.Description != description {
|
||||
changedFields = append(changedFields, "description")
|
||||
}
|
||||
if config != nil {
|
||||
changedFields = append(changedFields, "config")
|
||||
}
|
||||
|
||||
// Update the knowledge base properties
|
||||
kb.Name = name
|
||||
kb.Description = description
|
||||
@@ -526,6 +544,10 @@ func (s *knowledgeBaseService) UpdateKnowledgeBase(ctx context.Context,
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
recordKBActivity(ctx, s.audit, kb.TenantID, kb.ID, types.AuditActionKBUpdated,
|
||||
"knowledge_base", kb.ID, types.AuditOutcomeSuccess, map[string]any{
|
||||
"name": kb.Name, "changed_fields": changedFields,
|
||||
})
|
||||
|
||||
logger.Infof(ctx, "Knowledge base updated successfully, ID: %s, name: %s", kb.ID, kb.Name)
|
||||
return kb, nil
|
||||
@@ -691,6 +713,12 @@ func (s *knowledgeBaseService) DeleteKnowledgeBase(ctx context.Context, id strin
|
||||
})
|
||||
return err
|
||||
}
|
||||
deletedName := ""
|
||||
if kb != nil {
|
||||
deletedName = kb.Name
|
||||
}
|
||||
recordKBActivity(ctx, s.audit, tenantID, id, types.AuditActionKBDeleted,
|
||||
"knowledge_base", id, types.AuditOutcomeSuccess, map[string]any{"name": deletedName})
|
||||
|
||||
// Step 1b: Remove all organization shares for this KB so org settings no longer show them
|
||||
if s.shareRepo != nil {
|
||||
@@ -1127,6 +1155,10 @@ func (s *knowledgeBaseService) DuplicateKnowledgeBase(
|
||||
if err := s.repo.CreateKnowledgeBase(ctx, targetKB); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
recordKBActivity(ctx, s.audit, tenantID, targetKB.ID, types.AuditActionKBDuplicated,
|
||||
"knowledge_base", targetKB.ID, types.AuditOutcomeSuccess, map[string]any{
|
||||
"source_kb_id": sourceKB.ID, "name": targetKB.Name,
|
||||
})
|
||||
return targetKB, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -29,6 +29,7 @@ type knowledgeTagService struct {
|
||||
modelService interfaces.ModelService
|
||||
task interfaces.TaskEnqueuer
|
||||
kbShareService interfaces.KBShareService
|
||||
audit interfaces.AuditLogService
|
||||
}
|
||||
|
||||
// NewKnowledgeTagService creates a new tag service.
|
||||
@@ -42,6 +43,7 @@ func NewKnowledgeTagService(
|
||||
modelService interfaces.ModelService,
|
||||
task interfaces.TaskEnqueuer,
|
||||
kbShareService interfaces.KBShareService,
|
||||
audit interfaces.AuditLogService,
|
||||
) (interfaces.KnowledgeTagService, error) {
|
||||
return &knowledgeTagService{
|
||||
kbService: kbService,
|
||||
@@ -53,6 +55,7 @@ func NewKnowledgeTagService(
|
||||
modelService: modelService,
|
||||
task: task,
|
||||
kbShareService: kbShareService,
|
||||
audit: audit,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -183,6 +186,8 @@ func (s *knowledgeTagService) CreateTag(
|
||||
if err := s.repo.Create(ctx, tag); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
recordKBActivity(ctx, s.audit, tag.TenantID, tag.KnowledgeBaseID, types.AuditActionTagCreated,
|
||||
"knowledge_tag", tag.ID, types.AuditOutcomeSuccess, map[string]any{"name": tag.Name})
|
||||
return tag, nil
|
||||
}
|
||||
|
||||
@@ -220,6 +225,8 @@ func (s *knowledgeTagService) UpdateTag(
|
||||
if err := s.repo.Update(ctx, tag); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
recordKBActivity(ctx, s.audit, tag.TenantID, tag.KnowledgeBaseID, types.AuditActionTagUpdated,
|
||||
"knowledge_tag", tag.ID, types.AuditOutcomeSuccess, map[string]any{"name": tag.Name})
|
||||
return tag, nil
|
||||
}
|
||||
|
||||
@@ -286,6 +293,7 @@ func (s *knowledgeTagService) DeleteTag(ctx context.Context, id string, force bo
|
||||
payload := types.KnowledgeListDeletePayload{
|
||||
TenantID: tenantID,
|
||||
KnowledgeIDs: knowledgeIDs,
|
||||
Initiator: types.TaskInitiatorFromContext(ctx),
|
||||
}
|
||||
langfuse.InjectTracing(ctx, &payload)
|
||||
payloadBytes, err := json.Marshal(payload)
|
||||
@@ -317,6 +325,9 @@ func (s *knowledgeTagService) DeleteTag(ctx context.Context, id string, force bo
|
||||
return err
|
||||
}
|
||||
}
|
||||
recordKBActivity(ctx, s.audit, tenantID, tag.KnowledgeBaseID, types.AuditActionTagUpdated,
|
||||
"knowledge_tag", tag.ID, types.AuditOutcomeSuccess,
|
||||
map[string]any{"name": tag.Name, "content_cleared": true, "excluded_count": len(excludeIDs)})
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -341,9 +352,18 @@ func (s *knowledgeTagService) DeleteTag(ctx context.Context, id string, force bo
|
||||
|
||||
// If there are excludeIDs, we cannot delete the tag itself as it still has content
|
||||
if len(excludeIDs) > 0 {
|
||||
recordKBActivity(ctx, s.audit, tenantID, tag.KnowledgeBaseID, types.AuditActionTagUpdated,
|
||||
"knowledge_tag", tag.ID, types.AuditOutcomeSuccess,
|
||||
map[string]any{"name": tag.Name, "content_cleared": true, "excluded_count": len(excludeIDs)})
|
||||
return nil
|
||||
}
|
||||
return s.repo.Delete(ctx, tenantID, id)
|
||||
if err := s.repo.Delete(ctx, tenantID, id); err != nil {
|
||||
return err
|
||||
}
|
||||
recordKBActivity(ctx, s.audit, tenantID, tag.KnowledgeBaseID, types.AuditActionTagDeleted,
|
||||
"knowledge_tag", tag.ID, types.AuditOutcomeSuccess,
|
||||
map[string]any{"name": tag.Name, "force": force})
|
||||
return nil
|
||||
}
|
||||
|
||||
// enqueueIndexDeleteTask enqueues an async task for index deletion (low priority).
|
||||
|
||||
@@ -7,24 +7,52 @@ import (
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
)
|
||||
|
||||
// wikiLogEntryService is a thin wrapper over WikiLogEntryRepository. The
|
||||
// event layer carries no business rules today, so the service just
|
||||
// forwards to the repo — the indirection exists so handlers / ingest
|
||||
// batch code depend on an interface rather than a concrete repo type.
|
||||
// wikiLogEntryService persists the detailed Wiki feed and projects a bounded
|
||||
// summary into the generic per-KB activity timeline.
|
||||
type wikiLogEntryService struct {
|
||||
repo interfaces.WikiLogEntryRepository
|
||||
repo interfaces.WikiLogEntryRepository
|
||||
audit interfaces.AuditLogService
|
||||
}
|
||||
|
||||
// NewWikiLogEntryService constructs a WikiLogEntryService backed by the
|
||||
// given repository.
|
||||
func NewWikiLogEntryService(repo interfaces.WikiLogEntryRepository) interfaces.WikiLogEntryService {
|
||||
return &wikiLogEntryService{repo: repo}
|
||||
func NewWikiLogEntryService(
|
||||
repo interfaces.WikiLogEntryRepository,
|
||||
audit interfaces.AuditLogService,
|
||||
) interfaces.WikiLogEntryService {
|
||||
return &wikiLogEntryService{repo: repo, audit: audit}
|
||||
}
|
||||
|
||||
// AppendBatch records the given events in one database round trip. Empty
|
||||
// batches are a no-op (the repo handles that).
|
||||
func (s *wikiLogEntryService) AppendBatch(ctx context.Context, entries []*types.WikiLogEntry) error {
|
||||
return s.repo.AppendBatch(ctx, entries)
|
||||
if err := s.repo.AppendBatch(ctx, entries); err != nil {
|
||||
return err
|
||||
}
|
||||
type summary struct {
|
||||
tenantID uint64
|
||||
count int
|
||||
actions map[string]int
|
||||
}
|
||||
byKB := make(map[string]*summary)
|
||||
for _, entry := range entries {
|
||||
if entry == nil || entry.KnowledgeBaseID == "" {
|
||||
continue
|
||||
}
|
||||
item := byKB[entry.KnowledgeBaseID]
|
||||
if item == nil {
|
||||
item = &summary{tenantID: entry.TenantID, actions: make(map[string]int)}
|
||||
byKB[entry.KnowledgeBaseID] = item
|
||||
}
|
||||
item.count++
|
||||
item.actions[entry.Action]++
|
||||
}
|
||||
for kbID, item := range byKB {
|
||||
recordKBActivity(ctx, s.audit, item.tenantID, kbID, types.AuditActionWikiContentChanged,
|
||||
"wiki", kbID, types.AuditOutcomeSuccess,
|
||||
map[string]any{"count": item.count, "actions": item.actions})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// List paginates the per-KB event feed. See repo.List for cursor semantics.
|
||||
|
||||
@@ -168,6 +168,7 @@ func (s *Scheduler) triggerSync(dataSourceID string, tenantID uint64) {
|
||||
TenantID: tenantID,
|
||||
SyncLogID: syncLog.ID,
|
||||
ForceFull: false,
|
||||
Trigger: "schedule",
|
||||
}
|
||||
langfuse.InjectTracing(ctx, payload)
|
||||
payloadJSON, _ := json.Marshal(payload)
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/errors"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/middleware"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -76,11 +77,12 @@ func (h *AuditLogHandler) ListTenantAuditLog(c *gin.Context) {
|
||||
}
|
||||
|
||||
q := &interfaces.AuditLogQuery{
|
||||
AfterID: afterID,
|
||||
Limit: limit,
|
||||
Action: types.AuditAction(c.Query("action")),
|
||||
Outcome: types.AuditOutcome(c.Query("outcome")),
|
||||
ActorUserID: c.Query("actor"),
|
||||
AfterID: afterID,
|
||||
Limit: limit,
|
||||
Action: types.AuditAction(c.Query("action")),
|
||||
Outcome: types.AuditOutcome(c.Query("outcome")),
|
||||
ActorUserID: c.Query("actor"),
|
||||
UnscopedOnly: true,
|
||||
}
|
||||
|
||||
entries, err := h.auditService.List(ctx, tenantID, q)
|
||||
@@ -105,6 +107,85 @@ func (h *AuditLogHandler) ListTenantAuditLog(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
// ListKnowledgeBaseActivity returns the durable activity projection for one
|
||||
// knowledge base. The route has already resolved KB access; this handler adds
|
||||
// an owner-tenant check so organization-shared consumers cannot inspect source
|
||||
// workspace actors or configuration history.
|
||||
// @Summary 获取知识库活动记录
|
||||
// @Description 返回知识库的重要变更与后台任务入口。仅知识库创建者或所属空间管理员可读,共享空间不可读。
|
||||
// @Tags 知识库
|
||||
// @Produce json
|
||||
// @Param id path string true "知识库ID"
|
||||
// @Param after_id query int false "游标:返回 id 小于此值的记录"
|
||||
// @Param limit query int false "页大小,1-100,默认 50"
|
||||
// @Param action query string false "按 action 精确过滤"
|
||||
// @Param outcome query string false "按 outcome 精确过滤"
|
||||
// @Param actor query string false "按 actor_user_id 精确过滤"
|
||||
// @Success 200 {object} auditLogListResponse
|
||||
// @Failure 403 {object} errors.AppError
|
||||
// @Security Bearer
|
||||
// @Router /knowledge-bases/{id}/activity [get]
|
||||
func (h *AuditLogHandler) ListKnowledgeBaseActivity(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
kbID := c.Param("id")
|
||||
access, ok := middleware.KBAccessFromContext(c)
|
||||
if !ok || access == nil || access.KnowledgeBase == nil || access.KnowledgeBase.ID != kbID {
|
||||
c.Error(errors.NewNotFoundError("knowledge base not found"))
|
||||
return
|
||||
}
|
||||
callerTenantID := c.GetUint64(types.TenantIDContextKey.String())
|
||||
if callerTenantID == 0 || access.KnowledgeBase.TenantID != callerTenantID {
|
||||
c.Error(errors.NewForbiddenError("knowledge base activity is only available in the owner workspace"))
|
||||
return
|
||||
}
|
||||
actorID, _ := types.UserIDFromContext(ctx)
|
||||
role := types.TenantRoleFromContext(ctx)
|
||||
if access.KnowledgeBase.CreatorID != actorID && !role.HasPermission(types.TenantRoleAdmin) {
|
||||
c.Error(errors.NewForbiddenError("knowledge base activity requires creator or admin access"))
|
||||
return
|
||||
}
|
||||
|
||||
afterID, limit := parseAuditCursor(c)
|
||||
q := &interfaces.AuditLogQuery{
|
||||
AfterID: afterID,
|
||||
Limit: limit,
|
||||
Action: types.AuditAction(c.Query("action")),
|
||||
Outcome: types.AuditOutcome(c.Query("outcome")),
|
||||
ActorUserID: c.Query("actor"),
|
||||
ScopeType: "knowledge_base",
|
||||
ScopeID: kbID,
|
||||
}
|
||||
entries, err := h.auditService.List(ctx, access.KnowledgeBase.TenantID, q)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{"knowledge_base_id": kbID})
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
return
|
||||
}
|
||||
var nextCursor uint64
|
||||
if n := len(entries); n > 0 {
|
||||
nextCursor = entries[n-1].ID
|
||||
}
|
||||
c.JSON(http.StatusOK, auditLogListResponse{
|
||||
Success: true, Data: entries, NextCursor: nextCursor,
|
||||
})
|
||||
}
|
||||
|
||||
func parseAuditCursor(c *gin.Context) (uint64, int) {
|
||||
var afterID uint64
|
||||
if raw := c.Query("after_id"); raw != "" {
|
||||
if v, err := strconv.ParseUint(raw, 10, 64); err == nil {
|
||||
afterID = v
|
||||
}
|
||||
}
|
||||
limit := 0
|
||||
if raw := c.Query("limit"); raw != "" {
|
||||
if v, err := strconv.Atoi(raw); err == nil && v > 0 {
|
||||
limit = v
|
||||
}
|
||||
}
|
||||
return afterID, limit
|
||||
}
|
||||
|
||||
// ListSystemAuditLog godoc
|
||||
// @Summary 获取平台审计日志
|
||||
// @Description 返回 system-scope(tenant_id=0)的审计事件,覆盖 system.setting_changed / system.admin_promoted / system.admin_revoked 等 SystemAdmin 操作。按 id 倒序的游标分页。
|
||||
|
||||
@@ -100,6 +100,9 @@ func TestAuditLogHandler_PassesQueryFiltersThrough(t *testing.T) {
|
||||
if q.ActorUserID != "u-probing" {
|
||||
t.Fatalf("expected actor=u-probing, got %q", q.ActorUserID)
|
||||
}
|
||||
if !q.UnscopedOnly {
|
||||
t.Fatalf("tenant audit feed must exclude resource-scoped activity rows")
|
||||
}
|
||||
return nil, nil
|
||||
},
|
||||
}
|
||||
@@ -154,6 +157,81 @@ func TestAuditLogHandler_InvalidTenantIDReturns400(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func newKBActivityHandlerTestRouter(
|
||||
t *testing.T,
|
||||
svc interfaces.AuditLogService,
|
||||
callerTenantID uint64,
|
||||
kb *types.KnowledgeBase,
|
||||
userID string,
|
||||
role types.TenantRole,
|
||||
) *gin.Engine {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
r := gin.New()
|
||||
r.Use(middleware.ErrorHandler())
|
||||
r.Use(func(c *gin.Context) {
|
||||
c.Set(types.TenantIDContextKey.String(), callerTenantID)
|
||||
c.Set(middleware.KBAccessContextKey, &middleware.KBAccess{KnowledgeBase: kb})
|
||||
ctx := context.WithValue(c.Request.Context(), types.UserIDContextKey, userID)
|
||||
ctx = context.WithValue(ctx, types.TenantRoleContextKey, role)
|
||||
c.Request = c.Request.WithContext(ctx)
|
||||
c.Next()
|
||||
})
|
||||
h := NewAuditLogHandler(svc)
|
||||
r.GET("/knowledge-bases/:id/activity", h.ListKnowledgeBaseActivity)
|
||||
return r
|
||||
}
|
||||
|
||||
func TestKnowledgeBaseActivityHandler_UsesKBScope(t *testing.T) {
|
||||
svc := &stubAuditService{list: func(_ context.Context, tenantID uint64, q *interfaces.AuditLogQuery) ([]*types.AuditLog, error) {
|
||||
if tenantID != 7 || q.ScopeType != "knowledge_base" || q.ScopeID != "kb-1" {
|
||||
t.Fatalf("unexpected scope: tenant=%d type=%q id=%q", tenantID, q.ScopeType, q.ScopeID)
|
||||
}
|
||||
if q.AfterID != 30 || q.Limit != 10 || q.Outcome != types.AuditOutcomePartial {
|
||||
t.Fatalf("unexpected filters: %+v", q)
|
||||
}
|
||||
return []*types.AuditLog{{ID: 21, TenantID: 7, ScopeType: q.ScopeType, ScopeID: q.ScopeID}}, nil
|
||||
}}
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, "/knowledge-bases/kb-1/activity?after_id=30&limit=10&outcome=partial", nil)
|
||||
newKBActivityHandlerTestRouter(t, svc, 7,
|
||||
&types.KnowledgeBase{ID: "kb-1", TenantID: 7, CreatorID: "creator"},
|
||||
"creator", types.TenantRoleViewer).ServeHTTP(w, req)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestKnowledgeBaseActivityHandler_BlocksSharedWorkspace(t *testing.T) {
|
||||
svc := &stubAuditService{list: func(_ context.Context, _ uint64, _ *interfaces.AuditLogQuery) ([]*types.AuditLog, error) {
|
||||
t.Fatal("audit list must not be called for a shared workspace")
|
||||
return nil, nil
|
||||
}}
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, "/knowledge-bases/kb-1/activity", nil)
|
||||
newKBActivityHandlerTestRouter(t, svc, 8,
|
||||
&types.KnowledgeBase{ID: "kb-1", TenantID: 7, CreatorID: "creator"},
|
||||
"creator", types.TenantRoleOwner).ServeHTTP(w, req)
|
||||
if w.Code != http.StatusForbidden {
|
||||
t.Fatalf("expected 403, got %d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestKnowledgeBaseActivityHandler_RequiresCreatorOrAdmin(t *testing.T) {
|
||||
svc := &stubAuditService{list: func(_ context.Context, _ uint64, _ *interfaces.AuditLogQuery) ([]*types.AuditLog, error) {
|
||||
t.Fatal("audit list must not be called for ordinary members")
|
||||
return nil, nil
|
||||
}}
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, "/knowledge-bases/kb-1/activity", nil)
|
||||
newKBActivityHandlerTestRouter(t, svc, 7,
|
||||
&types.KnowledgeBase{ID: "kb-1", TenantID: 7, CreatorID: "creator"},
|
||||
"other", types.TenantRoleContributor).ServeHTTP(w, req)
|
||||
if w.Code != http.StatusForbidden {
|
||||
t.Fatalf("expected 403, got %d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// ---- ListSystemAuditLog (platform / system-scope feed) ----------------
|
||||
//
|
||||
// Mirrors the per-tenant suite above but covers the new
|
||||
|
||||
@@ -249,6 +249,7 @@ func (h *KnowledgeHandler) enqueueKnowledgeListDelete(
|
||||
payload := types.KnowledgeListDeletePayload{
|
||||
TenantID: tenantID,
|
||||
KnowledgeIDs: ids,
|
||||
Initiator: types.TaskInitiatorFromContext(ctx),
|
||||
}
|
||||
langfuse.InjectTracing(ctx, &payload)
|
||||
payloadBytes, err := json.Marshal(payload)
|
||||
@@ -273,6 +274,7 @@ func (h *KnowledgeHandler) enqueueKnowledgeListReparse(
|
||||
TenantID: tenantID,
|
||||
KnowledgeIDs: ids,
|
||||
ProcessConfig: processConfig,
|
||||
Initiator: types.TaskInitiatorFromContext(ctx),
|
||||
}
|
||||
langfuse.InjectTracing(ctx, &payload)
|
||||
payloadBytes, err := json.Marshal(payload)
|
||||
@@ -2219,6 +2221,7 @@ func (h *KnowledgeHandler) MoveKnowledge(c *gin.Context) {
|
||||
SourceKBID: req.SourceKBID,
|
||||
TargetKBID: req.TargetKBID,
|
||||
Mode: req.Mode,
|
||||
Initiator: types.TaskInitiatorFromContext(ctx),
|
||||
}
|
||||
langfuse.InjectTracing(ctx, &payload)
|
||||
|
||||
|
||||
@@ -1081,10 +1081,11 @@ func (h *KnowledgeBaseHandler) CopyKnowledgeBase(c *gin.Context) {
|
||||
|
||||
// Create KB clone payload
|
||||
payload := types.KBClonePayload{
|
||||
TenantID: tenantID.(uint64),
|
||||
TaskID: taskID,
|
||||
SourceID: req.SourceID,
|
||||
TargetID: req.TargetID,
|
||||
TenantID: tenantID.(uint64),
|
||||
TaskID: taskID,
|
||||
SourceID: req.SourceID,
|
||||
TargetID: req.TargetID,
|
||||
Initiator: types.TaskInitiatorFromContext(ctx),
|
||||
}
|
||||
langfuse.InjectTracing(ctx, &payload)
|
||||
|
||||
|
||||
@@ -230,6 +230,7 @@ func NewRouter(params RouterParams) *gin.Engine {
|
||||
RegisterTenantRoutes(v1, params.TenantHandler, params.TenantMemberHandler, params.TenantInvitationHandler, params.AuditLogHandler, rbacGuards)
|
||||
RegisterMyInvitationRoutes(v1, params.TenantInvitationHandler)
|
||||
RegisterKnowledgeBaseRoutes(v1, params.KBHandler, rbacGuards)
|
||||
RegisterKnowledgeBaseActivityRoutes(v1, params.AuditLogHandler, rbacGuards)
|
||||
// KB-scoped image proxy: lets tenants render images embedded in
|
||||
// org-shared / agent-visible KB content, which the tenant-scoped
|
||||
// /files route cannot serve because it enforces same-tenant paths.
|
||||
@@ -502,6 +503,17 @@ func RegisterKnowledgeBaseRoutes(r *gin.RouterGroup, handler *handler.KnowledgeB
|
||||
}
|
||||
}
|
||||
|
||||
// RegisterKnowledgeBaseActivityRoutes exposes the read-only per-KB activity
|
||||
// feed. It intentionally stays JWT-only: audit history is a sensitive owner
|
||||
// surface and no existing workspace API-key capability grants audit access.
|
||||
func RegisterKnowledgeBaseActivityRoutes(r *gin.RouterGroup, auditHandler *handler.AuditLogHandler, g *rbacGuards) {
|
||||
if auditHandler == nil {
|
||||
return
|
||||
}
|
||||
r.GET("/knowledge-bases/:id/activity",
|
||||
g.OwnedKBOrAdmin(), g.KBAccessRead("id"), auditHandler.ListKnowledgeBaseActivity)
|
||||
}
|
||||
|
||||
// RegisterKnowledgeTagRoutes 注册知识库标签相关路由。
|
||||
//
|
||||
// Tags are KB metadata: Viewer reads, Contributor writes. Per-KB
|
||||
|
||||
@@ -131,32 +131,81 @@ const (
|
||||
AuditActionSystemQueueTaskDeleted AuditAction = "system.queue_task_deleted"
|
||||
AuditActionSystemQueueTaskRunNow AuditAction = "system.queue_task_run_now"
|
||||
AuditActionSystemQueueTaskCancelled AuditAction = "system.queue_task_cancelled"
|
||||
|
||||
// Knowledge-base activity actions. These rows use scope_type=knowledge_base
|
||||
// and scope_id=<kb id>; TargetType/TargetID identify the concrete child
|
||||
// resource when the operation is about a document, tag, data source, or share.
|
||||
AuditActionKBCreated AuditAction = "kb.created"
|
||||
AuditActionKBUpdated AuditAction = "kb.updated"
|
||||
AuditActionKBDeleted AuditAction = "kb.deleted"
|
||||
AuditActionKBDuplicated AuditAction = "kb.duplicated"
|
||||
AuditActionKBCloneStarted AuditAction = "kb.clone_started"
|
||||
AuditActionKBCloneCompleted AuditAction = "kb.clone_completed"
|
||||
AuditActionKBCloneFailed AuditAction = "kb.clone_failed"
|
||||
|
||||
AuditActionKnowledgeCreated AuditAction = "knowledge.created"
|
||||
AuditActionKnowledgeUpdated AuditAction = "knowledge.updated"
|
||||
AuditActionKnowledgeDeleted AuditAction = "knowledge.deleted"
|
||||
AuditActionKnowledgeBatchDeleted AuditAction = "knowledge.batch_deleted"
|
||||
AuditActionKnowledgeReparseStarted AuditAction = "knowledge.reparse_started"
|
||||
AuditActionKnowledgeParseCanceled AuditAction = "knowledge.parse_canceled"
|
||||
AuditActionKnowledgeMoveStarted AuditAction = "knowledge.move_started"
|
||||
AuditActionKnowledgeMoveCompleted AuditAction = "knowledge.move_completed"
|
||||
AuditActionKnowledgeMoveFailed AuditAction = "knowledge.move_failed"
|
||||
|
||||
AuditActionTagCreated AuditAction = "tag.created"
|
||||
AuditActionTagUpdated AuditAction = "tag.updated"
|
||||
AuditActionTagDeleted AuditAction = "tag.deleted"
|
||||
|
||||
AuditActionDataSourceCreated AuditAction = "datasource.created"
|
||||
AuditActionDataSourceUpdated AuditAction = "datasource.updated"
|
||||
AuditActionDataSourceDeleted AuditAction = "datasource.deleted"
|
||||
AuditActionDataSourceSyncStarted AuditAction = "datasource.sync_started"
|
||||
AuditActionDataSourceSyncCompleted AuditAction = "datasource.sync_completed"
|
||||
AuditActionDataSourceSyncFailed AuditAction = "datasource.sync_failed"
|
||||
AuditActionDataSourcePaused AuditAction = "datasource.paused"
|
||||
AuditActionDataSourceResumed AuditAction = "datasource.resumed"
|
||||
|
||||
AuditActionKBShareAdded AuditAction = "kb.share_added"
|
||||
AuditActionKBSharePermissionChanged AuditAction = "kb.share_permission_changed"
|
||||
AuditActionKBShareRemoved AuditAction = "kb.share_removed"
|
||||
AuditActionWikiContentChanged AuditAction = "wiki.content_changed"
|
||||
)
|
||||
|
||||
// AuditOutcome distinguishes successful mutations from middleware-level
|
||||
// rejections. The split lets the audit-log UI highlight denials in red
|
||||
// without needing to enumerate every action class.
|
||||
// AuditOutcome separates asynchronous acceptance from terminal business
|
||||
// results and middleware-level rejections. The UI can therefore avoid
|
||||
// presenting a queued operation as already completed.
|
||||
type AuditOutcome string
|
||||
|
||||
const (
|
||||
AuditOutcomeSuccess AuditOutcome = "success"
|
||||
AuditOutcomeDenied AuditOutcome = "denied"
|
||||
// Accepted means the durable request was created and asynchronous work was
|
||||
// submitted, but the background operation has not reached a terminal state.
|
||||
AuditOutcomeAccepted AuditOutcome = "accepted"
|
||||
AuditOutcomeDenied AuditOutcome = "denied"
|
||||
AuditOutcomeFailed AuditOutcome = "failed"
|
||||
AuditOutcomePartial AuditOutcome = "partial"
|
||||
AuditOutcomeCanceled AuditOutcome = "canceled"
|
||||
)
|
||||
|
||||
// AuditLog is a single immutable audit event. The schema is intentionally
|
||||
// generic: PR 6 wires only RBAC events, but TargetType / TargetID /
|
||||
// Details are set up to absorb KB / agent / datasource events in
|
||||
// follow-up PRs without another migration.
|
||||
// follow-up PRs without another migration. Knowledge-base task events use a
|
||||
// bounded convention inside Details: task_id, trigger, processing_status,
|
||||
// source/target ids, aggregate counts, and operation-specific mode/attempt.
|
||||
//
|
||||
// Rows are append-only — no UpdatedAt, no soft-delete column. The
|
||||
// monotonic ID acts as both primary key and pagination cursor (newest-
|
||||
// first is `WHERE id < AfterID ORDER BY id DESC`).
|
||||
type AuditLog struct {
|
||||
ID uint64 `json:"id" gorm:"primaryKey;autoIncrement"`
|
||||
TenantID uint64 `json:"tenant_id" gorm:"not null;index:idx_audit_logs_tenant_id_desc,priority:1;index:idx_audit_logs_tenant_action,priority:1"`
|
||||
ID uint64 `json:"id" gorm:"primaryKey;autoIncrement;index:idx_audit_logs_tenant_scope_desc,priority:4,sort:desc"`
|
||||
TenantID uint64 `json:"tenant_id" gorm:"not null;index:idx_audit_logs_tenant_id_desc,priority:1;index:idx_audit_logs_tenant_action,priority:1;index:idx_audit_logs_tenant_scope_desc,priority:1"`
|
||||
ActorUserID string `json:"actor_user_id" gorm:"type:varchar(36);default:'';index:idx_audit_logs_actor"`
|
||||
ActorRole string `json:"actor_role" gorm:"type:varchar(32);default:''"`
|
||||
Action AuditAction `json:"action" gorm:"type:varchar(64);not null;index:idx_audit_logs_tenant_action,priority:2"`
|
||||
ScopeType string `json:"scope_type" gorm:"type:varchar(32);default:'';index:idx_audit_logs_tenant_scope_desc,priority:2"`
|
||||
ScopeID string `json:"scope_id" gorm:"type:varchar(64);default:'';index:idx_audit_logs_tenant_scope_desc,priority:3"`
|
||||
TargetType string `json:"target_type" gorm:"type:varchar(32);default:''"`
|
||||
TargetID string `json:"target_id" gorm:"type:varchar(64);default:''"`
|
||||
TargetUserID string `json:"target_user_id" gorm:"type:varchar(36);default:''"`
|
||||
|
||||
@@ -54,6 +54,39 @@ func UserIDFromContext(ctx context.Context) (string, bool) {
|
||||
return v, ok && v != ""
|
||||
}
|
||||
|
||||
// TaskInitiator is the authenticated caller that submitted an asynchronous
|
||||
// task. Workers restore it into their context so audit entries describe who
|
||||
// initiated the operation, while tasks created by schedulers remain
|
||||
// attributable to the system.
|
||||
type TaskInitiator struct {
|
||||
UserID string `json:"user_id,omitempty"`
|
||||
Role TenantRole `json:"role,omitempty"`
|
||||
}
|
||||
|
||||
// TaskInitiatorFromContext snapshots the real caller identity for a task
|
||||
// payload. Synthetic API-key users are service identities, not people, and are
|
||||
// intentionally left empty so the activity feed presents them as system work.
|
||||
func TaskInitiatorFromContext(ctx context.Context) TaskInitiator {
|
||||
userID, ok := UserIDFromContext(ctx)
|
||||
if !ok || IsSyntheticUserID(userID) {
|
||||
return TaskInitiator{}
|
||||
}
|
||||
return TaskInitiator{UserID: userID, Role: TenantRoleFromContext(ctx)}
|
||||
}
|
||||
|
||||
// Apply restores a captured task initiator onto a worker context. Empty or
|
||||
// legacy payloads are a no-op and therefore retain the system-task fallback.
|
||||
func (i TaskInitiator) Apply(ctx context.Context) context.Context {
|
||||
if i.UserID == "" {
|
||||
return ctx
|
||||
}
|
||||
ctx = context.WithValue(ctx, UserIDContextKey, i.UserID)
|
||||
if i.Role.IsValid() {
|
||||
ctx = context.WithValue(ctx, TenantRoleContextKey, i.Role)
|
||||
}
|
||||
return ctx
|
||||
}
|
||||
|
||||
// IsSyntheticUserID reports whether id refers to the synthetic system
|
||||
// user that the X-API-Key auth path attaches to each tenant
|
||||
// (User.ID = "system-<tenantID>"). These users have no real human
|
||||
|
||||
@@ -415,6 +415,9 @@ func (e *SyncItemError) UnmarshalJSON(b []byte) error {
|
||||
// DataSourceSyncPayload represents the asynq task payload for data source sync
|
||||
type DataSourceSyncPayload struct {
|
||||
TracingContext
|
||||
Initiator TaskInitiator `json:"initiator,omitempty"`
|
||||
// Trigger distinguishes a user-requested run from a scheduler-created run.
|
||||
Trigger string `json:"trigger,omitempty"`
|
||||
|
||||
// Data source ID to sync
|
||||
DataSourceID string `json:"data_source_id"`
|
||||
|
||||
@@ -14,11 +14,14 @@ import (
|
||||
// Limit is capped at 100 inside the repository regardless of caller
|
||||
// input — keeps unbounded scans off the table.
|
||||
type AuditLogQuery struct {
|
||||
AfterID uint64
|
||||
Limit int
|
||||
Action types.AuditAction
|
||||
Outcome types.AuditOutcome
|
||||
ActorUserID string
|
||||
AfterID uint64
|
||||
Limit int
|
||||
Action types.AuditAction
|
||||
Outcome types.AuditOutcome
|
||||
ActorUserID string
|
||||
ScopeType string
|
||||
ScopeID string
|
||||
UnscopedOnly bool
|
||||
}
|
||||
|
||||
// AuditLogRepository is the storage primitive for the audit table.
|
||||
|
||||
+24
-20
@@ -29,19 +29,19 @@ const (
|
||||
// name "low" so tasks enqueued by older releases remain consumable during a
|
||||
// rolling deployment. New code uses the business-semantic constant.
|
||||
const (
|
||||
QueueDefault = "default"
|
||||
QueueDefault = "default"
|
||||
// QueueChatAttachment carries session-scoped chat attachment parsing. It
|
||||
// lives in the core pool but with a higher weight than QueueDefault so
|
||||
// interactive chat uploads are not starved by knowledge-base batch imports.
|
||||
QueueChatAttachment = "chat_attachment"
|
||||
QueuePostProcess = "postprocess"
|
||||
QueueSummary = "summary"
|
||||
QueueMultimodal = "multimodal"
|
||||
QueueGraph = "graph"
|
||||
QueueQuestion = "question"
|
||||
QueueSync = "sync"
|
||||
QueueMaintenance = "low"
|
||||
QueueWiki = "wiki"
|
||||
QueueSummary = "summary"
|
||||
QueueMultimodal = "multimodal"
|
||||
QueueGraph = "graph"
|
||||
QueueQuestion = "question"
|
||||
QueueSync = "sync"
|
||||
QueueMaintenance = "low"
|
||||
QueueWiki = "wiki"
|
||||
)
|
||||
|
||||
// QueueDefinition is the single source of truth for queue topology. Worker
|
||||
@@ -367,10 +367,11 @@ type SummaryGenerationPayload struct {
|
||||
// KBClonePayload represents the knowledge base clone task payload
|
||||
type KBClonePayload struct {
|
||||
TracingContext
|
||||
TenantID uint64 `json:"tenant_id"`
|
||||
TaskID string `json:"task_id"`
|
||||
SourceID string `json:"source_id"`
|
||||
TargetID string `json:"target_id"`
|
||||
TenantID uint64 `json:"tenant_id"`
|
||||
TaskID string `json:"task_id"`
|
||||
SourceID string `json:"source_id"`
|
||||
TargetID string `json:"target_id"`
|
||||
Initiator TaskInitiator `json:"initiator,omitempty"`
|
||||
}
|
||||
|
||||
// IndexDeletePayload represents the index delete task payload
|
||||
@@ -403,8 +404,9 @@ type KBDeletePayload struct {
|
||||
// KnowledgeListDeletePayload represents the batch knowledge delete task payload
|
||||
type KnowledgeListDeletePayload struct {
|
||||
TracingContext
|
||||
TenantID uint64 `json:"tenant_id"`
|
||||
KnowledgeIDs []string `json:"knowledge_ids"`
|
||||
TenantID uint64 `json:"tenant_id"`
|
||||
KnowledgeIDs []string `json:"knowledge_ids"`
|
||||
Initiator TaskInitiator `json:"initiator,omitempty"`
|
||||
}
|
||||
|
||||
// KnowledgeListReparsePayload represents the batch knowledge reparse task payload
|
||||
@@ -413,17 +415,19 @@ type KnowledgeListReparsePayload struct {
|
||||
TenantID uint64 `json:"tenant_id"`
|
||||
KnowledgeIDs []string `json:"knowledge_ids"`
|
||||
ProcessConfig *KnowledgeProcessOverrides `json:"process_config,omitempty"`
|
||||
Initiator TaskInitiator `json:"initiator,omitempty"`
|
||||
}
|
||||
|
||||
// KnowledgeMovePayload represents the knowledge move task payload
|
||||
type KnowledgeMovePayload struct {
|
||||
TracingContext
|
||||
TenantID uint64 `json:"tenant_id"`
|
||||
TaskID string `json:"task_id"`
|
||||
KnowledgeIDs []string `json:"knowledge_ids"`
|
||||
SourceKBID string `json:"source_kb_id"`
|
||||
TargetKBID string `json:"target_kb_id"`
|
||||
Mode string `json:"mode"` // "reuse_vectors" or "reparse"
|
||||
TenantID uint64 `json:"tenant_id"`
|
||||
TaskID string `json:"task_id"`
|
||||
KnowledgeIDs []string `json:"knowledge_ids"`
|
||||
SourceKBID string `json:"source_kb_id"`
|
||||
TargetKBID string `json:"target_kb_id"`
|
||||
Mode string `json:"mode"` // "reuse_vectors" or "reparse"
|
||||
Initiator TaskInitiator `json:"initiator,omitempty"`
|
||||
}
|
||||
|
||||
// KnowledgeMoveProgress represents the progress of a knowledge move task
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestTaskInitiatorRoundTrip(t *testing.T) {
|
||||
requestCtx := context.WithValue(context.Background(), UserIDContextKey, "user-1")
|
||||
requestCtx = context.WithValue(requestCtx, TenantRoleContextKey, TenantRoleAdmin)
|
||||
|
||||
initiator := TaskInitiatorFromContext(requestCtx)
|
||||
if initiator.UserID != "user-1" || initiator.Role != TenantRoleAdmin {
|
||||
t.Fatalf("TaskInitiatorFromContext() = %#v", initiator)
|
||||
}
|
||||
|
||||
workerCtx := initiator.Apply(context.Background())
|
||||
if userID, ok := UserIDFromContext(workerCtx); !ok || userID != "user-1" {
|
||||
t.Fatalf("restored user = %q, %v", userID, ok)
|
||||
}
|
||||
if role := TenantRoleFromContext(workerCtx); role != TenantRoleAdmin {
|
||||
t.Fatalf("restored role = %q", role)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskInitiatorOmitsSyntheticAndLegacyActors(t *testing.T) {
|
||||
synthetic := context.WithValue(context.Background(), UserIDContextKey, "system-42")
|
||||
if got := TaskInitiatorFromContext(synthetic); got.UserID != "" {
|
||||
t.Fatalf("synthetic initiator = %#v", got)
|
||||
}
|
||||
|
||||
legacyCtx := (TaskInitiator{}).Apply(context.Background())
|
||||
if userID, ok := UserIDFromContext(legacyCtx); ok || userID != "" {
|
||||
t.Fatalf("legacy user = %q, %v", userID, ok)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user