notifications

package
v0.0.0-...-e12325a Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 15, 2026 License: MIT Imports: 28 Imported by: 0

Documentation

Index

Constants

View Source
const (
	PushDeviceStatusActive  = "active"
	PushDeviceStatusRevoked = "revoked"
)
View Source
const (
	TypeReply              = "reply"
	TypeMention            = "mention"
	TypeModerationPending  = "moderation_pending"
	TypeModerationApproved = "moderation_approved"
	TypeModerationRejected = "moderation_rejected"
	TypeAdminTest          = "admin_test"
	// TypeReaction 是点赞通知(engagement 类);站内默认开,邮件/推送默认关。
	TypeReaction = "reaction"
	// TypeBookmarkReminder 是收藏提醒(engagement 类):用户主动设定的计划动作,
	// 站内与邮件默认开、web_push 默认关(与 202611100001_content_bookmarks.sql 一致)。
	TypeBookmarkReminder = "bookmark_reminder"
	// TypeBadgeGranted 是徽章授予通知(engagement 类):站内默认开,邮件/推送默认关。
	// 与 reaction 的关键区别:徽章是**公开荣誉**,不是互动噪音,所以管理员给自己
	// 授予徽章同样要发通知(reaction 会跳过自赞)。不要「顺手统一」掉这个差异。
	TypeBadgeGranted = "badge_granted"

	// 邮件投递状态对齐 outbox 共享词表(F3.1)。
	DeliveryQueued  = outbox.StatusQueued
	DeliverySending = outbox.StatusSending
	DeliverySent    = outbox.StatusSent
	DeliveryFailed  = outbox.StatusFailed
	DeliverySkipped = outbox.StatusSkipped
)
View Source
const (

	// DefaultCelebrationLimit 是一次返回的最大条数(前端一次只展示一张卡,
	// 其余靠 `total` 聚合成「获得 N 枚新徽章」)。
	DefaultCelebrationLimit = 3
)

Variables

View Source
var (
	ErrChannelDeliveryNotFound = errors.New("notifications: channel delivery not found")
	ErrSubscriptionInvalid     = errors.New("notifications: subscription invalid")
	ErrSubscriptionNotFound    = errors.New("notifications: subscription not found")
)
View Source
var (
	ErrPushDeviceInvalid       = errors.New("notifications: push device invalid")
	ErrPushDeviceNotFound      = errors.New("notifications: push device not found")
	ErrPushDeviceTokenTooLong  = errors.New("notifications: push device token too long")
	ErrPushDevicePlatformKnown = errors.New("notifications: push device platform unknown")
)

原生推送设备注册(App / 桌面端)。

Core 只拥有归属与生命周期:设备令牌 ↔ 用户 ↔ App 实例。真正的投递(FCM/APNs) 属于通知通道 provider 插件的职责,Core 只负责把「该发给谁」记录清楚。 令牌本身既不进入 API 响应,也不以明文落库(配置了 Core 密钥时存 AES-GCM 密文)。

View Source
var (
	ErrPreferenceConflict = errors.New("notifications: preference revision conflict")
	ErrPreferenceInvalid  = errors.New("notifications: preference is not configurable")
)
View Source
var (
	ErrRevisionWakeUnavailable = errors.New("notifications: revision wake source unavailable")
	ErrRevisionConnectionLimit = errors.New("notifications: revision connection limit reached")
)
View Source
var (
	ErrRegistryDescriptorInvalid = errors.New("notifications: registry descriptor invalid")
	ErrRegistryOwnerConflict     = errors.New("notifications: registry owner conflict")
	ErrRegistryRevisionConflict  = errors.New("notifications: registry revision conflict")
)
View Source
var ErrNotificationNotFound = errors.New("notifications: notification not found")
View Source
var ErrPolicyConflict = errors.New("notifications: policy revision conflict")

Functions

func AcknowledgeCelebrations

func AcknowledgeCelebrations(ctx context.Context, store CelebrationStore, userID int64, cursorID int64) (int64, error)

AcknowledgeCelebrations 推进庆祝游标(GREATEST 语义:给旧的 cursorId 不会回退)。

为什么不是「置等于」:前端的 ack 是尽力而为的(点击跳转后发、失败不重试), 两条 ack 乱序到达时「置等于」会把已经看过的新通知重新弹一遍。

Types

type AdminPolicyCatalog

type AdminPolicyCatalog struct {
	Revision int64             `json:"revision"`
	Items    []AdminPolicyItem `json:"items"`
}

type AdminPolicyItem

type AdminPolicyItem struct {
	AdminPolicyUpdate
	Category         string `json:"category"`
	OwnerExtensionID string `json:"ownerExtensionId,omitempty"`
	Active           bool   `json:"active"`
	Required         bool   `json:"required"`
}

type AdminPolicyStore

type AdminPolicyStore interface {
	ListAdminPolicy(context.Context) (AdminPolicyCatalog, error)
	ReplaceAdminPolicy(context.Context, int64, []AdminPolicyUpdate) (AdminPolicyCatalog, error)
	RestoreAdminPolicy(context.Context, int64) (AdminPolicyCatalog, error)
}

type AdminPolicyUpdate

type AdminPolicyUpdate struct {
	Type               string `json:"type"`
	Channel            string `json:"channel"`
	Enabled            bool   `json:"enabled"`
	RecommendedEnabled bool   `json:"recommendedEnabled"`
	UserConfigurable   bool   `json:"userConfigurable"`
}

type BadgeGrantedEvent

type BadgeGrantedEvent struct {
	RecipientUserID int64
	// BadgeID 是通知的可点击目标(TargetType="badge")。
	//
	// 0 表示调用方拿不到 id(历史数据/测试夹具):此时不写目标,
	// 收件箱渲染成「无链接的纯文本通知」而不是指向 /badges/0 的死链。
	BadgeID   int64
	BadgeSlug string
	BadgeName string
	// GrantedByUserID 为 0 表示系统自动授予(规则命中)。
	GrantedByUserID int64
}

BadgeGrantedEvent 是一次徽章授予(自动或手动)。

刻意没有「自己给自己」的抑制:徽章是公开荣誉,不是互动噪音。 与 ReactionEvent 的语义相反——那边自赞要静默,这边自授要通知。

type BookmarkReminderEvent

type BookmarkReminderEvent struct {
	BookmarkID      int64
	RecipientUserID int64
	TargetType      string
	TargetID        int64
	TopicID         int64
}

ReactionEvent 是一次点赞的收件人视角:目标作者收到「X 赞了你的内容」。 RecipientUserID 为 0 或等于 ActorUserID 时不写投影(自赞不打扰)。 BookmarkReminderEvent 是一次到期的收藏提醒。

与 reaction 的差别:收件人就是收藏行主(没有 actor),去重键锚在收藏行 ID 上, 因此同一行只会产生一条提醒投影,即使 job 被重试。

type Bundle

type Bundle struct {
	Notification Notification
	Delivery     MailDelivery
}

type CelebrationFeed

type CelebrationFeed struct {
	Initialized bool              `json:"initialized"`
	CursorID    int64             `json:"cursorId"`
	Total       int64             `json:"total"`
	Items       []CelebrationItem `json:"items"`
}

CelebrationFeed 是 GET /notifications/celebrations 的响应。

`CursorID` 恒有值:initialized=false 时它是「种子游标」(当前最大通知 id), 前端据此发第一次 ack;initialized=true 时它是当前离线游标。

**`items` 可能少于 `total`**:`total` 是 SQL 候选数(封顶 99),`items` 是过了 目标可见性之后的子集(徽章被收回/停用会让条目整条消失)。前端约定: **`items` 为空时不渲染任何庆祝 DOM**——不要用 `total` 去决定是否弹卡。

func ListCelebrations

func ListCelebrations(ctx context.Context, store CelebrationStore, targets TargetVisibilityResolver, userID int64, limit int) (CelebrationFeed, error)

ListCelebrations 组装庆祝读面。

返回顺序是 id 升序(最早的先展示):庆祝卡一次只显示一张,先来的先看, 与收件箱的倒序不同——收件箱是「最新最相关」,庆祝是「一次讲一件事」。

失败语义:解析目标失败只丢那一条(见 ResolveSafeTargets),存储错误才上抛。

type CelebrationItem

type CelebrationItem struct {
	ID         int64             `json:"id"`
	Type       string            `json:"type"`
	Icon       string            `json:"icon"`
	Label      CelebrationText   `json:"label"`
	Body       CelebrationText   `json:"body"`
	TitleKey   *string           `json:"titleKey"`
	BodyKey    *string           `json:"bodyKey"`
	Params     map[string]string `json:"params"`
	TargetPath *string           `json:"targetPath"`
	CreatedAt  time.Time         `json:"createdAt"`
}

CelebrationItem 是庆祝卡的数据。

`titleKey`/`bodyKey` 是 Core 类型的 i18n 键,插件类型为 null(前端回落 `label`/`body`)。三者同时存在不是冗余:Core 的文案由前端 i18n 拥有, 插件文案由插件清单拥有,服务端只负责选路,不生成句子。

type CelebrationRow

type CelebrationRow struct {
	ID           int64
	Type         string
	TargetType   string
	TargetID     int64
	Payload      json.RawMessage
	Presentation json.RawMessage
	CreatedAt    time.Time
}

CelebrationRow 是读面的原始一行(通知 + 描述符展示字段)。

type CelebrationStore

type CelebrationStore interface {
	// CelebrationCursor 返回 (游标, 是否存在游标行)。
	// 存在游标行 = 用户已经「初始化」过庆祝层(首访或个人设置里 ack 过)。
	CelebrationCursor(ctx context.Context, userID int64) (int64, bool, error)
	// LatestNotificationID 是该用户当前最大通知 id(无通知为 0)。
	LatestNotificationID(ctx context.Context, userID int64) (int64, error)
	// ListCelebrationRows 返回 id > afterID 的庆祝候选(按 id 升序,最多 limit 条)
	// 与同条件的总数(封顶 celebrationTotalCap)。
	ListCelebrationRows(ctx context.Context, userID int64, afterID int64, limit int) ([]CelebrationRow, int64, error)
	// AcknowledgeCelebrationCursor 用 GREATEST 语义推进游标(不倒退),返回落库值。
	AcknowledgeCelebrationCursor(ctx context.Context, userID int64, cursorID int64) (int64, error)
}

CelebrationStore 是庆祝读面的持久化能力(PostgresStore 实现;测试可替换)。

type CelebrationText

type CelebrationText struct {
	Zh string `json:"zh"`
	En string `json:"en"`
}

CelebrationText 是 wire 上的双语言文本(键固定 zh/en)。

与 `extensionmanifest.LocalizedText` 分开:后者是**输入**形状(可写纯字符串或 locale map),wire 需要的是两个稳定键,让前端不必再猜语言解析规则。

type ChannelDelivery

type ChannelDelivery struct {
	ID                     int64           `json:"id"`
	NotificationID         *int64          `json:"notificationId,omitempty"`
	RecipientUserID        int64           `json:"-"`
	Type                   string          `json:"type"`
	Channel                string          `json:"channel"`
	ProviderExtensionID    string          `json:"providerExtensionId,omitempty"`
	ProviderArtifactDigest string          `json:"providerArtifactDigest,omitempty"`
	PayloadVersion         int             `json:"payloadVersion"`
	Payload                json.RawMessage `json:"-"`
	TargetMeta             json.RawMessage `json:"-"`
	IdempotencyKey         string          `json:"-"`
	Status                 string          `json:"status"`
	AttemptCount           int             `json:"attemptCount"`
	Reason                 string          `json:"reason,omitempty"`
	ErrorSummary           string          `json:"errorSummary,omitempty"`
	CreatedAt              time.Time       `json:"createdAt"`
	UpdatedAt              time.Time       `json:"updatedAt"`
	CompletedAt            *time.Time      `json:"completedAt,omitempty"`
}

type ChannelDeliveryUpdate

type ChannelDeliveryUpdate struct {
	ID                     int64
	Status                 string
	ProviderExtensionID    string
	ProviderArtifactDigest string
	AttemptCount           int
	Reason                 string
	ErrorSummary           string
}

type CommentEvent

type CommentEvent struct {
	CommentID, TopicID, ActorUserID       int64
	TopicAuthorUserID, ParentAuthorUserID int64
	MentionedUsernames                    []string
}

type CorePolicyStore

type CorePolicyStore interface {
	NotificationPolicy(context.Context) (options.NotificationPolicy, error)
	UpdateCoreNotificationPolicy(context.Context, options.NotificationPolicy) error
	RestoreCoreNotificationPolicy(context.Context) error
}

CorePolicyStore is the compatibility projection used while /admin/mail/policy remains in API LTS. The V2 tables are still the authority.

type CreateBundleInput

type CreateBundleInput struct {
	Notification CreateInput
	Delivery     CreateDeliveryInput
	// Channels is the validated type declaration. Empty preserves the legacy
	// Core bundle contract (in_app + email).
	Channels []string
}

type CreateChannelDeliveryInput

type CreateChannelDeliveryInput struct {
	NotificationID  *int64
	RecipientUserID int64
	Type            string
	Channel         string
	PayloadVersion  int
	Payload         json.RawMessage
	TargetMeta      json.RawMessage
	IdempotencyKey  string
}

type CreateDeliveryInput

type CreateDeliveryInput struct {
	Recipient      string
	TemplateKey    string
	TemplateData   json.RawMessage
	IdempotencyKey string
	CorrelationID  string
}

type CreateInput

type CreateInput struct {
	RecipientUserID int64
	Type            string
	Category        string
	TypeVersion     int
	PayloadVersion  int
	ActorUserID     *int64
	TargetType      string
	TargetID        int64
	Payload         json.RawMessage
	DedupeKey       string
}

type CreateWebPushSubscriptionInput

type CreateWebPushSubscriptionInput struct {
	UserID             int64
	Endpoint           string
	P256DHKey, AuthKey []byte
	ContentEncoding    string
}

type DeliveryPolicyResolver

type DeliveryPolicyResolver interface {
	DeliveryEnabled(context.Context, int64, string, string) (bool, error)
}

type DeliveryUpdate

type DeliveryUpdate struct {
	ID           int64
	Status       string
	ExtensionID  string
	AttemptCount int
	Reason       string
	ErrorSummary string
}

type DescriptorOwner

type DescriptorOwner struct {
	ExtensionID    string `json:"extensionId,omitempty"`
	Version        string `json:"version,omitempty"`
	ArtifactDigest string `json:"artifactDigest,omitempty"`
}

type DetailStore

type DetailStore interface {
	GetNotification(context.Context, int64, int64) (Notification, error)
}

DetailStore 单独承载收件人自有通知点查,避免列表/投递 worker 的窄接口被详情能力污染。

type ListInput

type ListInput struct {
	RecipientUserID int64
	Limit           int
	BeforeID        int64
	Category        string
	Type            string
	Unread          *bool
}

type MailBrand

type MailBrand = mail.Brand

func DefaultMailBrand

func DefaultMailBrand(siteName, siteURL string) MailBrand

func MailBrandFromSettings

func MailBrandFromSettings(siteName, siteURL, logoURL, iconURL, appearanceTheme string) MailBrand

type MailBrandResolver

type MailBrandResolver = mail.BrandResolver

type MailDelivery

type MailDelivery struct {
	ID             int64           `json:"id"`
	Recipient      string          `json:"recipient"`
	TemplateKey    string          `json:"templateKey"`
	TemplateData   json.RawMessage `json:"templateData,omitempty"`
	IdempotencyKey string          `json:"-"`
	CorrelationID  string          `json:"correlationId"`
	Status         string          `json:"status"`
	ExtensionID    string          `json:"extensionId,omitempty"`
	AttemptCount   int             `json:"attemptCount"`
	Reason         string          `json:"reason,omitempty"`
	ErrorSummary   string          `json:"errorSummary,omitempty"`
	CreatedAt      time.Time       `json:"createdAt"`
	UpdatedAt      time.Time       `json:"updatedAt"`
	CompletedAt    *time.Time      `json:"completedAt,omitempty"`
}

type MailLocaleResolver

type MailLocaleResolver interface {
	DefaultMailLocale(context.Context) (string, error)
}

MailLocaleResolver supplies the live site fallback before notification data becomes immutable delivery data.

type ModerationEvent

type ModerationEvent struct {
	DecisionID               int64
	TargetType               string
	TargetID, ReviewerUserID int64
	Approved                 bool
	ReviewNote               string
}

type Notification

type Notification struct {
	ID              int64              `json:"id"`
	RecipientUserID int64              `json:"-"`
	Type            string             `json:"type"`
	Category        string             `json:"category,omitempty"`
	TypeVersion     int                `json:"typeVersion,omitempty"`
	PayloadVersion  int                `json:"payloadVersion,omitempty"`
	ActorUserID     *int64             `json:"actorUserId,omitempty"`
	Actor           *NotificationActor `json:"actor,omitempty"`
	TargetType      string             `json:"targetType"`
	TargetID        int64              `json:"targetId"`
	TargetAvailable bool               `json:"targetAvailable"`
	TargetPath      string             `json:"targetPath,omitempty"`
	Payload         json.RawMessage    `json:"payload"`
	DedupeKey       string             `json:"-"`
	ReadAt          *time.Time         `json:"readAt,omitempty"`
	CreatedAt       time.Time          `json:"createdAt"`
}

type NotificationActor

type NotificationActor struct {
	ID          int64       `json:"id"`
	Username    string      `json:"username"`
	DisplayName string      `json:"displayName"`
	Avatar      avatar.View `json:"avatar"`
}

type NotificationDetail

type NotificationDetail struct {
	Notification
	Preview *TargetPreview `json:"preview,omitempty"`
}

func ResolveNotificationDetail

func ResolveNotificationDetail(ctx context.Context, visibility TargetVisibilityResolver, previews TargetPreviewResolver, userID int64, item Notification) (NotificationDetail, error)

type Outbox

type Outbox struct {
	// contains filtered or unexported fields
}

func NewOutbox

func NewOutbox(pool interface {
	Begin(context.Context) (pgx.Tx, error)
}, store *PostgresStore, jobs TxEnqueuer, localeResolvers ...MailLocaleResolver) *Outbox

func (*Outbox) CreateBundleTx

func (o *Outbox) CreateBundleTx(ctx context.Context, tx pgx.Tx, input CreateBundleInput) (Bundle, error)

func (*Outbox) CreateProjectionsResultTx

func (o *Outbox) CreateProjectionsResultTx(ctx context.Context, tx pgx.Tx, input CreateBundleInput) (ProjectionResult, error)

func (*Outbox) CreateProjectionsTx

func (o *Outbox) CreateProjectionsTx(ctx context.Context, tx pgx.Tx, input CreateBundleInput) error

func (*Outbox) NotifyBadgeGranted

func (o *Outbox) NotifyBadgeGranted(ctx context.Context, event BadgeGrantedEvent) error

NotifyBadgeGranted 在 job 里调用(没有现成事务):自己开一个。

func (*Outbox) NotifyBadgeGrantedTx

func (o *Outbox) NotifyBadgeGrantedTx(ctx context.Context, tx pgx.Tx, event BadgeGrantedEvent) error

NotifyBadgeGrantedTx 写一条徽章授予投影。

幂等靠 dedupeKey = badge:{recipientUserID}:{slug}:**键必须自证收件人**。 `notifications.dedupe_key` 是全局唯一约束(见 202607110016 的 DDL 与 postgres_store.go 的 `ON CONFLICT (dedupe_key) DO NOTHING`),早期写成 `badge:{slug}` 时全站第一个拿到该徽章的人会占住这个键,之后所有人的投影 都被静默吞掉——「授予成功、收件箱空着」且零报错。其余通知类型一直自带收件人 身份(`moderation-pending:…:{reviewerID}`、`comment:…:reply:{id}`、 `topic:…:mention:{id}`),只有徽章这一处漏了。

语义不变:同一用户同一徽章只会有一条通知,重复评估不会刷屏,授予被收回后 再授予也不会重复(徽章是终局荣誉)。

func (*Outbox) NotifyBookmarkReminderTx

func (o *Outbox) NotifyBookmarkReminderTx(ctx context.Context, tx pgx.Tx, event BookmarkReminderEvent) error

NotifyBookmarkReminderTx writes the reminder projection for a claimed bookmark.

调用方(Forum 的到期扫描)已经在同一事务里把 reminded_at 写掉,所以这里失败 会让整条提醒回滚、下一轮重扫——不会出现「标了已提醒但没发」。

func (*Outbox) NotifyCommentTx

func (o *Outbox) NotifyCommentTx(ctx context.Context, tx pgx.Tx, event CommentEvent) error

func (*Outbox) NotifyModerationTx

func (o *Outbox) NotifyModerationTx(ctx context.Context, tx pgx.Tx, event ModerationEvent) error

func (*Outbox) NotifyPendingReviewTx

func (o *Outbox) NotifyPendingReviewTx(ctx context.Context, tx pgx.Tx, event PendingReviewEvent) error

func (*Outbox) NotifyReactionTx

func (o *Outbox) NotifyReactionTx(ctx context.Context, tx pgx.Tx, event ReactionEvent) error

NotifyReactionTx writes the like notification projection for the target author.

与 reply/mention 同一套投影与偏好规则:in_app 默认开,email/web_push 默认关。 去重键包含 actor,因此「取消后再赞」不会产生第二条通知。

func (*Outbox) NotifyTopicTx

func (o *Outbox) NotifyTopicTx(ctx context.Context, tx pgx.Tx, event TopicEvent) error

NotifyTopicTx mirrors comment mention fanout for an active topic creation. Topic authors are not notified about their own new topic; only explicit active mentions become projections.

func (*Outbox) QueueChannel

func (o *Outbox) QueueChannel(ctx context.Context, input CreateInput, channel string) (ChannelDelivery, error)

func (*Outbox) QueueEmailVerification

func (o *Outbox) QueueEmailVerification(ctx context.Context, input QueueEmailVerificationInput) (MailDelivery, error)

func (*Outbox) QueueMail

func (o *Outbox) QueueMail(ctx context.Context, input QueueMailInput) (MailDelivery, error)

func (*Outbox) QueuePasswordReset

func (o *Outbox) QueuePasswordReset(ctx context.Context, input QueuePasswordResetInput) (MailDelivery, error)

func (*Outbox) WithDeliveryPolicyResolver

func (o *Outbox) WithDeliveryPolicyResolver(resolver DeliveryPolicyResolver) *Outbox

func (*Outbox) WithPermissionRecipients

func (o *Outbox) WithPermissionRecipients(resolver PermissionRecipientResolver) *Outbox

type Page

type Page struct {
	Items   []Notification `json:"items"`
	HasMore bool           `json:"hasMore"`
}

func ResolveSafeTargets

func ResolveSafeTargets(ctx context.Context, resolver TargetVisibilityResolver, userID int64, page Page) (Page, error)

ResolveSafeTargets 在通知进入任一呈现层前重新核验目标。解析失败按不可见 处理,避免临时授权/数据错误退化成 payload 或路由泄漏。

type PendingReviewEvent

type PendingReviewEvent struct {
	TargetType, Title               string
	TargetID, TopicID, AuthorUserID int64
	Revision                        int64
}

type PermissionRecipientResolver

type PermissionRecipientResolver interface {
	ListActiveUserIDsWithPermissionTx(context.Context, pgx.Tx, string) ([]int64, error)
}

type PostgresStore

type PostgresStore struct {
	// contains filtered or unexported fields
}

func NewPostgresStore

func NewPostgresStore(pool *pgxpool.Pool) *PostgresStore

func NewPostgresStoreWithAvatar

func NewPostgresStoreWithAvatar(pool *pgxpool.Pool, avatarOptions avatar.OptionResolver) *PostgresStore

func (*PostgresStore) AcknowledgeCelebrationCursor

func (s *PostgresStore) AcknowledgeCelebrationCursor(ctx context.Context, userID int64, cursorID int64) (int64, error)

AcknowledgeCelebrationCursor 用 GREATEST 语义推进游标。

ON CONFLICT DO UPDATE + GREATEST:两条 ack 乱序到达时游标不会倒退, 也就不会把已经看过的通知重新弹一遍。

func (*PostgresStore) AdoptLegacyMail

func (s *PostgresStore) AdoptLegacyMail(ctx context.Context, legacy map[string]string) error

func (*PostgresStore) CelebrationCursor

func (s *PostgresStore) CelebrationCursor(ctx context.Context, userID int64) (int64, bool, error)

CelebrationCursor 读游标行;没有行表示用户还没「初始化」庆祝层。

func (*PostgresStore) Close

func (s *PostgresStore) Close()

Close stops process-owned background listeners. The caller still owns pool.

func (*PostgresStore) Create

func (s *PostgresStore) Create(ctx context.Context, input CreateInput) (Notification, error)

func (*PostgresStore) CreateBundleTx

func (s *PostgresStore) CreateBundleTx(ctx context.Context, tx queryRunner, input CreateBundleInput) (Bundle, error)

func (*PostgresStore) CreateChannelDeliveryTx

func (s *PostgresStore) CreateChannelDeliveryTx(ctx context.Context, tx queryRunner, input CreateChannelDeliveryInput) (ChannelDelivery, error)

func (*PostgresStore) CreateDeliveryTx

func (s *PostgresStore) CreateDeliveryTx(ctx context.Context, tx queryRunner, input CreateDeliveryInput) (MailDelivery, error)

func (*PostgresStore) CreateNotificationTx

func (s *PostgresStore) CreateNotificationTx(ctx context.Context, tx queryRunner, input CreateInput) (Notification, error)

func (*PostgresStore) CreateWebPushSubscription

func (s *PostgresStore) CreateWebPushSubscription(ctx context.Context, input CreateWebPushSubscriptionInput) (WebPushSubscription, error)

func (*PostgresStore) DeliveryEnabled

func (s *PostgresStore) DeliveryEnabled(ctx context.Context, userID int64, typ, channel string) (bool, error)

DeliveryEnabled applies the V2 hard-limit, required, inherit and explicit user override rules. Provider availability is deliberately not folded into this decision: a missing external provider must not suppress the inbox.

func (*PostgresStore) DeliveryEnabledTx

func (s *PostgresStore) DeliveryEnabledTx(ctx context.Context, tx pgx.Tx, userID int64, typ, channel string) (bool, error)

DeliveryEnabledTx keeps policy and projection on the caller's transaction snapshot. Host commands must not resolve preferences through a second pool connection while their receipt and notification rows are still uncommitted.

func (*PostgresStore) GetChannelDelivery

func (s *PostgresStore) GetChannelDelivery(ctx context.Context, id int64) (ChannelDelivery, error)

func (*PostgresStore) GetDelivery

func (s *PostgresStore) GetDelivery(ctx context.Context, id int64) (MailDelivery, error)

func (*PostgresStore) GetNotification

func (s *PostgresStore) GetNotification(ctx context.Context, userID, id int64) (Notification, error)

func (*PostgresStore) GetWebPushDeliveryAttempt

func (s *PostgresStore) GetWebPushDeliveryAttempt(ctx context.Context, deliveryID, subscriptionID int64) (WebPushDeliveryAttempt, error)

func (*PostgresStore) LatestNotificationID

func (s *PostgresStore) LatestNotificationID(ctx context.Context, userID int64) (int64, error)

LatestNotificationID 是该用户当前最大通知 id(无通知为 0)。

首访时它被当作「种子游标」返回给前端,前端 ack 之后庆祝层就有了起点, 老用户因此不会被历史徽章刷屏。

func (*PostgresStore) List

func (s *PostgresStore) List(ctx context.Context, input ListInput) (Page, error)

func (*PostgresStore) ListAdminPolicy

func (s *PostgresStore) ListAdminPolicy(ctx context.Context) (AdminPolicyCatalog, error)

func (*PostgresStore) ListCelebrationRows

func (s *PostgresStore) ListCelebrationRows(ctx context.Context, userID int64, afterID int64, limit int) ([]CelebrationRow, int64, error)

ListCelebrationRows 按 id 升序返回庆祝候选,并给出同条件总数(封顶)。

`celebrationWindow` 用 `now() - interval` 而不是 Go 传时间:这里比的是时间戳 (不是「哪一天」的日历界),时间戳比较允许在 SQL 里取 now()——与「按日取界必须 Go 传参」那条纪律不冲突(见 knowledge/modules/badges.md 陷阱 2)。

func (*PostgresStore) ListChannelDeliveries

func (s *PostgresStore) ListChannelDeliveries(ctx context.Context, limit int) ([]ChannelDelivery, error)

func (*PostgresStore) ListDeliveries

func (s *PostgresStore) ListDeliveries(ctx context.Context, limit int) ([]MailDelivery, error)

func (*PostgresStore) ListPreferences

func (s *PostgresStore) ListPreferences(ctx context.Context, userID int64) (PreferenceCatalog, error)

func (*PostgresStore) ListPushDevices

func (s *PostgresStore) ListPushDevices(ctx context.Context, userID int64, includeRevoked bool) ([]PushDevice, error)

ListPushDevices 返回当前用户的设备;默认只列活跃设备。

func (*PostgresStore) ListWebPushSubscriptions

func (s *PostgresStore) ListWebPushSubscriptions(ctx context.Context, userID int64, activeOnly bool) ([]WebPushSubscription, error)

func (*PostgresStore) MarkAllRead

func (s *PostgresStore) MarkAllRead(ctx context.Context, userID int64) (int64, error)

func (*PostgresStore) MarkRead

func (s *PostgresStore) MarkRead(ctx context.Context, userID, id int64) error

func (*PostgresStore) MarkWebPushSubscriptionFailed

func (s *PostgresStore) MarkWebPushSubscriptionFailed(ctx context.Context, id int64, reason string) error

func (*PostgresStore) NotificationPolicy

func (s *PostgresStore) NotificationPolicy(ctx context.Context) (options.NotificationPolicy, error)

NotificationPolicy resolves the legacy Core projection view from the V2 type/channel authority. It deliberately has the same shape as the temporary Mail compatibility API so callers cannot create a second policy source.

func (*PostgresStore) RecipientRevision

func (s *PostgresStore) RecipientRevision(ctx context.Context, userID int64) (int64, error)

func (*PostgresStore) RegisterPushDevice

func (s *PostgresStore) RegisterPushDevice(ctx context.Context, input RegisterPushDeviceInput) (PushDevice, error)

RegisterPushDevice 幂等注册/刷新设备。

语义:同一 (platform, token_hash) 只保留一行,重新注册会改绑到当前用户并清除撤销态 (换账号登录、令牌轮换、卸载重装都走这条路径);同一用户同一 device_id 的旧令牌行 会被标记撤销,避免向已失效令牌投递。

func (*PostgresStore) ReplaceAdminPolicy

func (s *PostgresStore) ReplaceAdminPolicy(ctx context.Context, expectedRevision int64, updates []AdminPolicyUpdate) (AdminPolicyCatalog, error)

func (*PostgresStore) ReplacePreferences

func (s *PostgresStore) ReplacePreferences(ctx context.Context, userID, expectedRevision int64, inputs []PreferenceInput) (PreferenceCatalog, error)

func (*PostgresStore) RestoreAdminPolicy

func (s *PostgresStore) RestoreAdminPolicy(ctx context.Context, expectedRevision int64) (AdminPolicyCatalog, error)

func (*PostgresStore) RestoreCoreNotificationPolicy

func (s *PostgresStore) RestoreCoreNotificationPolicy(ctx context.Context) error

func (*PostgresStore) RestorePreferences

func (s *PostgresStore) RestorePreferences(ctx context.Context, userID, expectedRevision int64) (PreferenceCatalog, error)

func (*PostgresStore) RevokePushDevice

func (s *PostgresStore) RevokePushDevice(ctx context.Context, userID int64, deviceID string) error

RevokePushDevice 按客户端已知的稳定 deviceId 撤销,所有权由 user_id 过滤保证。

func (*PostgresStore) RevokeWebPushSubscription

func (s *PostgresStore) RevokeWebPushSubscription(ctx context.Context, userID, id int64) error

func (*PostgresStore) SubscribeRevision

func (s *PostgresStore) SubscribeRevision(userID int64) (<-chan struct{}, func(), error)

func (*PostgresStore) UnreadCount

func (s *PostgresStore) UnreadCount(ctx context.Context, userID int64) (int64, error)

func (*PostgresStore) UpdateChannelDelivery

func (s *PostgresStore) UpdateChannelDelivery(ctx context.Context, update ChannelDeliveryUpdate) error

func (*PostgresStore) UpdateCoreNotificationPolicy

func (s *PostgresStore) UpdateCoreNotificationPolicy(ctx context.Context, policy options.NotificationPolicy) error

UpdateCoreNotificationPolicy updates only the legacy Core type projection. Plugin policy remains separately owned by its descriptor lifecycle and the dedicated notification settings surface.

func (*PostgresStore) UpdateDelivery

func (s *PostgresStore) UpdateDelivery(ctx context.Context, input DeliveryUpdate) error

func (*PostgresStore) UpdateWebPushDeliveryAttempt

func (s *PostgresStore) UpdateWebPushDeliveryAttempt(ctx context.Context, item WebPushDeliveryAttempt) error

func (*PostgresStore) WithPushDeviceCipher

func (s *PostgresStore) WithPushDeviceCipher(cipher PushDeviceCipher) *PostgresStore

WithPushDeviceCipher 在装配阶段注入 Core 密钥(nil 保持明文,开发环境兼容)。

func (*PostgresStore) WithPushDeviceClock

func (s *PostgresStore) WithPushDeviceClock(now func() time.Time) *PostgresStore

WithPushDeviceClock 便于测试注入时间源。

func (*PostgresStore) WithRevisionWakeups

func (s *PostgresStore) WithRevisionWakeups(ctx context.Context) *PostgresStore

WithRevisionWakeups starts the process-wide LISTEN connection used by SSE. Durable revisions remain authoritative when this hint connection is down.

type PreferenceCatalog

type PreferenceCatalog struct {
	Revision int64            `json:"revision"`
	Items    []PreferenceItem `json:"items"`
}

type PreferenceInput

type PreferenceInput struct {
	Type    string `json:"type"`
	Channel string `json:"channel"`
	State   string `json:"state"`
}

type PreferenceItem

type PreferenceItem struct {
	Type             string `json:"type"`
	Category         string `json:"category"`
	Channel          string `json:"channel"`
	Active           bool   `json:"active"`
	Enabled          bool   `json:"enabled"`
	Recommended      bool   `json:"recommendedEnabled"`
	UserConfigurable bool   `json:"userConfigurable"`
	Required         bool   `json:"required"`
	State            string `json:"state"`
	Effective        bool   `json:"effective"`
}

type PreferenceStore

type PreferenceStore interface {
	ListPreferences(context.Context, int64) (PreferenceCatalog, error)
	ReplacePreferences(context.Context, int64, int64, []PreferenceInput) (PreferenceCatalog, error)
	RestorePreferences(context.Context, int64, int64) (PreferenceCatalog, error)
}

type ProjectionResult

type ProjectionResult struct {
	InApp, Email, WebPush bool
}

CreateProjectionsTx is the shared policy and channel projection boundary for Core fanout and exact-artifact Host commands. The caller owns the transaction.

type PushDevice

type PushDevice struct {
	ID         int64      `json:"id"`
	DeviceID   string     `json:"deviceId"`
	Platform   string     `json:"platform"`
	AppVersion string     `json:"appVersion,omitempty"`
	Locale     string     `json:"locale,omitempty"`
	DeviceName string     `json:"deviceName,omitempty"`
	Status     string     `json:"status"`
	CreatedAt  time.Time  `json:"createdAt"`
	UpdatedAt  time.Time  `json:"updatedAt"`
	LastSeenAt time.Time  `json:"lastSeenAt"`
	RevokedAt  *time.Time `json:"revokedAt,omitempty"`
}

PushDevice 是设备注册的公开视图:永不含令牌或令牌指纹。

type PushDeviceCipher

type PushDeviceCipher interface {
	Encrypt(string) (string, error)
}

PushDeviceCipher 由 Core 密钥实现(app/Support/Crypto.OptionCipher)。 为 nil 时按开发环境约定真存明文;生产装配必须有密钥。

type PushDeviceStore

type PushDeviceStore interface {
	RegisterPushDevice(context.Context, RegisterPushDeviceInput) (PushDevice, error)
	ListPushDevices(context.Context, int64, bool) ([]PushDevice, error)
	RevokePushDevice(context.Context, int64, string) error
}

PushDeviceStore 是控制器依赖的最小能力面。

type QueueEmailVerificationInput

type QueueEmailVerificationInput struct {
	UserID        int64
	Email         string
	TokenHash     string
	ExpiresAt     time.Time
	RequestIPHash string
	Mail          QueueMailInput
}

type QueueMailInput

type QueueMailInput struct {
	Recipient, TemplateKey, IdempotencyKey, CorrelationID string
	TemplateData                                          json.RawMessage
}

type QueuePasswordResetInput

type QueuePasswordResetInput struct {
	UserID        int64
	TokenHash     string
	ExpiresAt     time.Time
	RequestIPHash string
	Mail          QueueMailInput
}

type ReactionEvent

type ReactionEvent struct {
	TargetType      string
	TargetID        int64
	TopicID         int64
	ActorUserID     int64
	RecipientUserID int64
}

type RecipientRevisionStore

type RecipientRevisionStore interface {
	RecipientRevision(context.Context, int64) (int64, error)
}

type RecipientRevisionWakeStore

type RecipientRevisionWakeStore interface {
	SubscribeRevision(int64) (<-chan struct{}, func(), error)
}

type RegisterPushDeviceInput

type RegisterPushDeviceInput struct {
	UserID     int64
	DeviceID   string
	Platform   string
	Token      string
	AppVersion string
	Locale     string
	DeviceName string
}

func NormalizePushDeviceInput

func NormalizePushDeviceInput(input RegisterPushDeviceInput) (RegisterPushDeviceInput, error)

NormalizePushDeviceInput 是设备注册的领域输入校验:控制器在调用 store 前必须先过这里, store 内再调用一次做纵深防御(同一实现,不是两套规则)。

type Registry

type Registry struct {
	// contains filtered or unexported fields
}

func NewPersistentRegistry

func NewPersistentRegistry(pool *pgxpool.Pool, initialSafeMode ...bool) *Registry

func NewRegistry

func NewRegistry() *Registry

func (*Registry) Deactivate

func (r *Registry) Deactivate(ctx context.Context, owner DescriptorOwner, expected uint64) (RegistrySnapshot, error)

func (*Registry) Publish

Publish replaces one plugin's complete exact-artifact declaration set. An expected revision provides CAS for concurrent lifecycle publications.

func (*Registry) Resolve

func (r *Registry) Resolve(typeID string) TypeDescriptor

func (*Registry) Restore

func (r *Registry) Restore(ctx context.Context, publications []RegistryPublication, safeMode bool) (RegistrySnapshot, error)

Restore replaces every plugin publication from the enabled exact-artifact inventory. It prevents stale disabled or uninstalled owners from surviving process restart and publishes the complete graph only after validation.

func (*Registry) SetSafeMode

func (r *Registry) SetSafeMode(ctx context.Context, enabled bool) (RegistrySnapshot, error)

func (*Registry) Snapshot

func (r *Registry) Snapshot() RegistrySnapshot

func (*Registry) ValidatePublish

func (r *Registry) ValidatePublish(owner DescriptorOwner, declarations []extensionmanifest.ManifestNotificationType) error

type RegistryPublication

type RegistryPublication struct {
	Owner        DescriptorOwner
	Declarations []extensionmanifest.ManifestNotificationType
}

RegistryPublication is one plugin's complete declaration set for an exact artifact. Startup restore replaces the whole plugin graph with these items.

type RegistrySnapshot

type RegistrySnapshot struct {
	Revision    uint64
	SafeMode    bool
	Descriptors map[string]TypeDescriptor
}

type RevisionHub

type RevisionHub struct {
	// contains filtered or unexported fields
}

RevisionHub uses one reconnecting PostgreSQL LISTEN connection per API process. NOTIFY only wakes subscribers; every subscriber re-reads its durable revision before sending an SSE signal.

func NewRevisionHub

func NewRevisionHub(ctx context.Context, pool *pgxpool.Pool) *RevisionHub

func (*RevisionHub) Close

func (h *RevisionHub) Close()

Close releases the dedicated LISTEN connection before its shared pool closes.

func (*RevisionHub) Subscribe

func (h *RevisionHub) Subscribe(userID int64) (<-chan struct{}, func(), error)

type Store

type Store interface {
	List(context.Context, ListInput) (Page, error)
	UnreadCount(context.Context, int64) (int64, error)
	MarkRead(context.Context, int64, int64) error
	MarkAllRead(context.Context, int64) (int64, error)
	GetDelivery(context.Context, int64) (MailDelivery, error)
	UpdateDelivery(context.Context, DeliveryUpdate) error
	ListDeliveries(context.Context, int) ([]MailDelivery, error)
}

type TargetPreview

type TargetPreview struct {
	TopicID    int64                 `json:"topicId"`
	TopicTitle string                `json:"topicTitle"`
	Content    TargetPreviewContent  `json:"content"`
	Context    *TargetPreviewContent `json:"context,omitempty"`
}

type TargetPreviewAuthor

type TargetPreviewAuthor = NotificationActor

type TargetPreviewContent

type TargetPreviewContent struct {
	Type    string               `json:"type"`
	ID      int64                `json:"id"`
	Excerpt string               `json:"excerpt"`
	Author  *TargetPreviewAuthor `json:"author,omitempty"`
}

type TargetPreviewResolver

type TargetPreviewResolver interface {
	ResolveNotificationTargetPreview(context.Context, int64, string, int64) (TargetPreview, bool, error)
}

type TargetVisibilityResolver

type TargetVisibilityResolver interface {
	ResolveNotificationTarget(context.Context, int64, string, int64) (available bool, path string, err error)
}

type TopicEvent

type TopicEvent struct {
	TopicID, ActorUserID int64
	MentionedUsernames   []string
}

type TxEnqueuer

type TxEnqueuer interface {
	EnqueueTx(context.Context, pgx.Tx, river.JobArgs, supportjobs.EnqueueOptions) (*rivertype.JobInsertResult, error)
}

type TypeDescriptor

type TypeDescriptor struct {
	Type                string                          `json:"type"`
	ContractVersion     int                             `json:"contractVersion"`
	PayloadVersion      int                             `json:"payloadVersion"`
	Owner               DescriptorOwner                 `json:"owner"`
	Category            string                          `json:"category"`
	PayloadSchema       string                          `json:"payloadSchema,omitempty"`
	Label               extensionmanifest.LocalizedText `json:"label"`
	Body                extensionmanifest.LocalizedText `json:"body"`
	Icon                string                          `json:"icon,omitempty"`
	TargetKind          string                          `json:"targetKind"`
	TargetID            string                          `json:"targetId,omitempty"`
	Channels            []string                        `json:"channels"`
	RecommendedChannels []string                        `json:"recommendedChannels,omitempty"`
	Required            bool                            `json:"required"`
	Active              bool                            `json:"active"`
	// Celebration 表示该类型参与「庆祝展示层」(presentation.celebration)。
	//
	// 它只影响读面(GET /notifications/celebrations 的候选集),不影响授予、
	// 去重、渠道或偏好:庆祝是通知平台的展示层,不是新的通知类型。
	Celebration bool `json:"celebration,omitempty"`
}

type WebPushDeliveryAttempt

type WebPushDeliveryAttempt struct {
	DeliveryID, SubscriptionID int64
	Status                     string
	AttemptCount               int
	Reason                     string
}

type WebPushSubscription

type WebPushSubscription struct {
	ID                int64      `json:"id"`
	UserID            int64      `json:"-"`
	EndpointOrigin    string     `json:"endpointOrigin"`
	Endpoint          string     `json:"-"`
	P256DHKey         []byte     `json:"-"`
	AuthKey           []byte     `json:"-"`
	ContentEncoding   string     `json:"contentEncoding"`
	Status            string     `json:"status"`
	LastFailureReason string     `json:"lastFailureReason,omitempty"`
	CreatedAt         time.Time  `json:"createdAt"`
	UpdatedAt         time.Time  `json:"updatedAt"`
	RevokedAt         *time.Time `json:"revokedAt,omitempty"`
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL