@mastra/factory 0.18.0-alpha.9 → 0.18.1-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/factory.d.ts.map +1 -1
- package/dist/factory.js +5 -2
- package/dist/factory.js.map +1 -1
- package/dist/integrations/github/default-rules.d.ts.map +1 -1
- package/dist/integrations/github/default-rules.js +3 -3
- package/dist/integrations/github/default-rules.js.map +1 -1
- package/dist/integrations/github/reconcile-worker.d.ts.map +1 -1
- package/dist/integrations/github/reconcile-worker.js +1 -2
- package/dist/integrations/github/reconcile-worker.js.map +1 -1
- package/dist/integrations/github/routes.d.ts.map +1 -1
- package/dist/integrations/github/routes.js +1 -14
- package/dist/integrations/github/routes.js.map +1 -1
- package/dist/integrations/gitlab/version-control.d.ts.map +1 -1
- package/dist/integrations/gitlab/version-control.js +4 -5
- package/dist/integrations/gitlab/version-control.js.map +1 -1
- package/dist/integrations/gitlab/webhook.d.ts.map +1 -1
- package/dist/integrations/gitlab/webhook.js +2 -2
- package/dist/integrations/gitlab/webhook.js.map +1 -1
- package/dist/integrations/issue-reconcile-worker.d.ts.map +1 -1
- package/dist/integrations/issue-reconcile-worker.js +1 -2
- package/dist/integrations/issue-reconcile-worker.js.map +1 -1
- package/dist/integrations/linear/integration.d.ts.map +1 -1
- package/dist/integrations/linear/integration.js +10 -30
- package/dist/integrations/linear/integration.js.map +1 -1
- package/dist/integrations/platform/github/event-worker.d.ts.map +1 -1
- package/dist/integrations/platform/github/event-worker.js +1 -2
- package/dist/integrations/platform/github/event-worker.js.map +1 -1
- package/dist/integrations/platform/gitlab/event-worker.d.ts.map +1 -1
- package/dist/integrations/platform/gitlab/event-worker.js +1 -2
- package/dist/integrations/platform/gitlab/event-worker.js.map +1 -1
- package/dist/integrations/platform/linear/event-worker.d.ts.map +1 -1
- package/dist/integrations/platform/linear/event-worker.js +1 -2
- package/dist/integrations/platform/linear/event-worker.js.map +1 -1
- package/dist/integrations/platform/linear/integration.d.ts.map +1 -1
- package/dist/integrations/platform/linear/integration.js +9 -9
- package/dist/integrations/platform/linear/integration.js.map +1 -1
- package/dist/integrations/slack/slack.d.ts.map +1 -1
- package/dist/integrations/slack/slack.js +137 -19
- package/dist/integrations/slack/slack.js.map +1 -1
- package/dist/integrations/subscription-session.d.ts +3 -1
- package/dist/integrations/subscription-session.d.ts.map +1 -1
- package/dist/integrations/subscription-session.js +4 -2
- package/dist/integrations/subscription-session.js.map +1 -1
- package/dist/review-verdict.d.ts +6 -0
- package/dist/review-verdict.d.ts.map +1 -0
- package/dist/review-verdict.js +14 -0
- package/dist/review-verdict.js.map +1 -0
- package/dist/routes/contracts.d.ts +23 -0
- package/dist/routes/contracts.d.ts.map +1 -1
- package/dist/routes/contracts.js +21 -0
- package/dist/routes/contracts.js.map +1 -1
- package/dist/routes/oauth.d.ts.map +1 -1
- package/dist/routes/oauth.js +3 -3
- package/dist/routes/oauth.js.map +1 -1
- package/dist/routes/projects.d.ts +22 -2
- package/dist/routes/projects.d.ts.map +1 -1
- package/dist/routes/projects.js +101 -0
- package/dist/routes/projects.js.map +1 -1
- package/dist/routes/source-control-sessions.d.ts.map +1 -1
- package/dist/routes/source-control-sessions.js +1 -2
- package/dist/routes/source-control-sessions.js.map +1 -1
- package/dist/rules/dispatcher.d.ts.map +1 -1
- package/dist/rules/dispatcher.js +1 -2
- package/dist/rules/dispatcher.js.map +1 -1
- package/dist/rules/processor.d.ts.map +1 -1
- package/dist/rules/processor.js +5 -5
- package/dist/rules/processor.js.map +1 -1
- package/dist/rules/transition-service.d.ts.map +1 -1
- package/dist/rules/transition-service.js +1 -2
- package/dist/rules/transition-service.js.map +1 -1
- package/dist/sandbox/materialization.d.ts +5 -1
- package/dist/sandbox/materialization.d.ts.map +1 -1
- package/dist/sandbox/materialization.js.map +1 -1
- package/dist/sandbox/session-sandbox.d.ts +13 -1
- package/dist/sandbox/session-sandbox.d.ts.map +1 -1
- package/dist/sandbox/session-sandbox.js.map +1 -1
- package/dist/secret-encryption.js +2 -2
- package/dist/secret-encryption.js.map +1 -1
- package/dist/session/factory-session.d.ts.map +1 -1
- package/dist/session/factory-session.js +26 -9
- package/dist/session/factory-session.js.map +1 -1
- package/dist/session/source-control-tools.d.ts +9 -0
- package/dist/session/source-control-tools.d.ts.map +1 -1
- package/dist/session/source-control-tools.js +51 -2
- package/dist/session/source-control-tools.js.map +1 -1
- package/dist/state-signing.js +3 -3
- package/dist/state-signing.js.map +1 -1
- package/dist/storage/domains/audit/base.d.ts.map +1 -1
- package/dist/storage/domains/audit/base.js +2 -3
- package/dist/storage/domains/audit/base.js.map +1 -1
- package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -1
- package/dist/storage/domains/source-control/inmemory.js +5 -6
- package/dist/storage/domains/source-control/inmemory.js.map +1 -1
- package/dist/storage/domains/work-items/base.d.ts +2 -0
- package/dist/storage/domains/work-items/base.d.ts.map +1 -1
- package/dist/storage/domains/work-items/base.js +9 -1
- package/dist/storage/domains/work-items/base.js.map +1 -1
- package/dist/workspace.d.ts.map +1 -1
- package/dist/workspace.js +8 -7
- package/dist/workspace.js.map +1 -1
- package/factory-skills/factory-gitlab-rereview/SKILL.md +1 -1
- package/factory-skills/factory-gitlab-review/SKILL.md +1 -1
- package/factory-skills/factory-rereview/SKILL.md +12 -3
- package/factory-skills/factory-review/SKILL.md +12 -3
- package/package.json +10 -10
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"event-worker.js","names":["#client","#controller","#gitlab","#storage","#listConnections","#ingestFactoryEvent","#intervalMs","#now","#process","#leaseOwner","#leaseTtlMs","#leaseProvider","#running","#startedAt","#settings","#schedule","#timer","#stopLeaseRenewal","#inFlight","#hasLease","#leaseKey","#tick","#ensureLease","#poll","#startLeaseRenewal","#leaseRenewalTimer","#pollConnection","#saveSettings","#processEvent"],"sources":["../../../../src/integrations/platform/gitlab/event-worker.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\n\nimport type { MountedMastraCode } from '@mastra/code-sdk';\nimport { isLeaseProvider, NoopLeaseProvider } from '@mastra/core/events';\nimport type { LeaseProvider, PubSub } from '@mastra/core/events';\nimport { MastraWorker } from '@mastra/core/worker';\nimport type { WorkerDeps } from '@mastra/core/worker';\n\nimport type { IntegrationStorageHandle } from '../../../storage/domains/integrations/base.js';\nimport type { GitLabWebhookDispatchIntegration } from '../../gitlab/webhook-dispatch.js';\nimport { parseGitLabWebhookBody, processGitLabWebhook } from '../../gitlab/webhook.js';\nimport type { ParsedGitLabWebhook } from '../../gitlab/webhook.js';\nimport type { PlatformApiClient } from '../api-client.js';\nimport { PlatformApiError } from '../api-client.js';\n\nconst DEFAULT_POLL_INTERVAL_MS = 20_000;\nconst EVENT_PAGE_SIZE = 500;\n/**\n * Pages drained per connection per cycle. A connection that never runs dry\n * (a busy group webhook, or a backlog after downtime) hands over to the next\n * connection after this many pages and resumes from its saved cursor next tick.\n */\nconst MAX_PAGES_PER_CONNECTION_PER_CYCLE = 10;\nconst MIN_LEASE_TTL_MS = 30_000;\nconst CURSOR_ORG_ID = '__platform_gitlab_event_worker__';\nconst CURSOR_USER_ID = 'worker';\nconst DELIVERY_ID_PREFIX = 'platform';\n\ntype PlatformGitLabEventWorkerSettings = {\n version: 1;\n connections: Record<string, { afterEventId: string }>;\n};\n\nexport type PlatformGitLabEventStorage = IntegrationStorageHandle<\n Record<string, unknown>,\n PlatformGitLabEventWorkerSettings,\n Record<string, unknown>\n>;\n\n/** One row of the Platform integration event log. */\nexport interface IntegrationEventEntry {\n id: string;\n timestamp: number;\n integrationId: string;\n eventType: string;\n sourceEventId: string | null;\n payload: unknown;\n}\n\nexport interface PlatformGitLabEventConnection {\n id: string;\n status: 'active' | 'needs_reauth';\n}\n\nexport type PlatformGitLabEventDispatchIntegration = GitLabWebhookDispatchIntegration;\n\nexport interface PlatformGitLabEventWorkerConfig {\n client: PlatformApiClient;\n controller: MountedMastraCode['controller'];\n gitlab: PlatformGitLabEventDispatchIntegration;\n storage: PlatformGitLabEventStorage;\n /** Platform connections to tail; only `active` ones are polled. */\n listConnections: () => Promise<PlatformGitLabEventConnection[]>;\n ingestFactoryEvent?: (event: ParsedGitLabWebhook) => Promise<unknown>;\n intervalMs?: number;\n now?: () => number;\n process?: typeof processGitLabWebhook;\n}\n\n/**\n * Tails the Platform event log for every active GitLab connection and feeds\n * each stored webhook body through the same ingress the direct\n * `/web/gitlab/webhook` route uses. A Platform-managed connection has no\n * project webhook pointing at Factory, so this is how issue, note, merge\n * request and push events reach the rules engine and subscribed sessions.\n *\n * One replica polls at a time (lease). Each connection keeps its own cursor,\n * persisted only after a whole page has been processed, so a crash mid-page\n * replays the page rather than losing it; replay handling in the rules ingress\n * and the delivery-id dedupe keys make that safe.\n */\nexport class PlatformGitLabEventWorker extends MastraWorker {\n readonly name = 'platform-gitlab-events';\n\n readonly #client: PlatformApiClient;\n readonly #controller: MountedMastraCode['controller'];\n readonly #gitlab: PlatformGitLabEventDispatchIntegration;\n readonly #storage: PlatformGitLabEventStorage;\n readonly #listConnections: () => Promise<PlatformGitLabEventConnection[]>;\n readonly #ingestFactoryEvent: ((event: ParsedGitLabWebhook) => Promise<unknown>) | undefined;\n readonly #intervalMs: number;\n readonly #now: () => number;\n readonly #process: typeof processGitLabWebhook;\n readonly #leaseOwner = randomUUID();\n\n #running = false;\n #timer: ReturnType<typeof setTimeout> | undefined;\n #leaseRenewalTimer: ReturnType<typeof setInterval> | undefined;\n #inFlight: Promise<void> | undefined;\n #leaseProvider: LeaseProvider = NoopLeaseProvider;\n #leaseTtlMs: number;\n #hasLease = false;\n #startedAt = 0;\n #settings: PlatformGitLabEventWorkerSettings = { version: 1, connections: {} };\n\n constructor(config: PlatformGitLabEventWorkerConfig) {\n super();\n this.#client = config.client;\n this.#controller = config.controller;\n this.#gitlab = config.gitlab;\n this.#storage = config.storage;\n this.#listConnections = config.listConnections;\n this.#ingestFactoryEvent = config.ingestFactoryEvent;\n this.#intervalMs = config.intervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n if (!Number.isFinite(this.#intervalMs) || this.#intervalMs <= 0) {\n throw new Error('Platform GitLab event polling interval must be a positive number.');\n }\n this.#leaseTtlMs = Math.max(MIN_LEASE_TTL_MS, this.#intervalMs * 3);\n this.#now = config.now ?? Date.now;\n this.#process = config.process ?? processGitLabWebhook;\n }\n\n async init(deps: WorkerDeps): Promise<void> {\n await super.init(deps);\n this.#leaseProvider = getLeaseProvider(deps.pubsub);\n }\n\n async start(): Promise<void> {\n if (this.#running) return;\n if (!this.deps) throw new Error('PlatformGitLabEventWorker: call init() before start()');\n\n this.#startedAt = this.#now() - 1;\n this.#settings = normalizeSettings(await this.#storage.settings.get(CURSOR_ORG_ID, CURSOR_USER_ID));\n this.#running = true;\n this.deps.logger.info('Platform GitLab event polling started', {\n intervalMs: this.#intervalMs,\n leaseTtlMs: this.#leaseTtlMs,\n });\n this.#schedule(0);\n }\n\n async stop(): Promise<void> {\n if (!this.#running) return;\n this.#running = false;\n if (this.#timer) clearTimeout(this.#timer);\n this.#timer = undefined;\n this.#stopLeaseRenewal();\n await this.#inFlight;\n if (this.#hasLease) {\n await this.#leaseProvider.releaseLease(this.#leaseKey(), this.#leaseOwner).catch(() => undefined);\n this.#hasLease = false;\n }\n }\n\n get isRunning(): boolean {\n return this.#running;\n }\n\n #schedule(delayMs: number): void {\n if (!this.#running) return;\n this.#timer = setTimeout(() => {\n this.#timer = undefined;\n const run = this.#tick();\n this.#inFlight = run;\n void run.finally(() => {\n if (this.#inFlight === run) this.#inFlight = undefined;\n });\n }, delayMs);\n this.#timer.unref?.();\n }\n\n async #tick(): Promise<void> {\n let nextDelay = this.#intervalMs;\n try {\n if (!(await this.#ensureLease())) return;\n nextDelay = await this.#poll();\n } catch (error) {\n nextDelay = retryDelay(error, this.#intervalMs);\n this.deps?.logger.error('Platform GitLab event polling cycle failed', {\n error: error instanceof Error ? error.message : String(error),\n retryInMs: nextDelay,\n });\n } finally {\n this.#schedule(nextDelay);\n }\n }\n\n async #ensureLease(): Promise<boolean> {\n if (this.#hasLease) return true;\n const result = await this.#leaseProvider.acquireLease(this.#leaseKey(), this.#leaseOwner, this.#leaseTtlMs);\n this.#hasLease = result.acquired;\n if (this.#hasLease) this.#startLeaseRenewal();\n return this.#hasLease;\n }\n\n #startLeaseRenewal(): void {\n if (this.#leaseRenewalTimer) return;\n this.#leaseRenewalTimer = setInterval(\n () => {\n void this.#leaseProvider\n .renewLease(this.#leaseKey(), this.#leaseOwner, this.#leaseTtlMs)\n .then(renewed => {\n if (!renewed) {\n this.#hasLease = false;\n this.#stopLeaseRenewal();\n }\n })\n .catch(error => {\n this.#hasLease = false;\n this.#stopLeaseRenewal();\n this.deps?.logger.warn('Platform GitLab event polling lease renewal failed', {\n error: error instanceof Error ? error.message : String(error),\n });\n });\n },\n Math.floor(this.#leaseTtlMs / 3),\n );\n this.#leaseRenewalTimer.unref?.();\n }\n\n #stopLeaseRenewal(): void {\n if (this.#leaseRenewalTimer) clearInterval(this.#leaseRenewalTimer);\n this.#leaseRenewalTimer = undefined;\n }\n\n async #poll(): Promise<number> {\n const connections = (await this.#listConnections()).filter(connection => connection.status === 'active');\n let retryInMs = this.#intervalMs;\n\n for (const connection of connections) {\n if (!this.#running || !this.#hasLease) break;\n try {\n await this.#pollConnection(connection.id);\n } catch (error) {\n if (error instanceof PlatformApiError && (error.status === 401 || error.status === 404)) {\n // Platform no longer serves this connection (revoked, expired or\n // deleted). Its status will read needs_reauth on the next listing;\n // nothing to retry here, so the other connections keep flowing.\n this.deps?.logger.warn('Platform GitLab connection needs reauthorization; skipped this cycle', {\n connectionId: connection.id,\n status: error.status,\n });\n continue;\n }\n const delay = retryDelay(error, this.#intervalMs);\n retryInMs = Math.max(retryInMs, delay);\n this.deps?.logger.error('Platform GitLab connection event polling failed', {\n connectionId: connection.id,\n error: error instanceof Error ? error.message : String(error),\n retryInMs: delay,\n });\n if (error instanceof PlatformApiError && error.status === 429) break;\n }\n }\n return retryInMs;\n }\n\n async #pollConnection(connectionId: string): Promise<void> {\n if (!this.#settings.connections[connectionId]) {\n // Event ids are Redis stream ids (`<unix ms>-<sequence>`), so a\n // synthesized id at start time skips history the same way the GitHub\n // worker's start timestamp does. Events that arrived before Factory was\n // deployed are not work Factory was asked to do.\n this.#settings.connections[connectionId] = { afterEventId: `${this.#startedAt}-0` };\n await this.#saveSettings();\n }\n\n for (let pageIndex = 0; this.#running && this.#hasLease; pageIndex += 1) {\n if (pageIndex >= MAX_PAGES_PER_CONNECTION_PER_CYCLE) {\n this.deps?.logger.debug('Platform GitLab connection page budget reached; resuming next cycle', {\n connectionId,\n pages: pageIndex,\n });\n return;\n }\n const cursor: { afterEventId: string } = this.#settings.connections[connectionId]!;\n const query = new URLSearchParams({ afterEventId: cursor.afterEventId, limit: String(EVENT_PAGE_SIZE) });\n const pollStartedAt = performance.now();\n const page = await this.#client.request<{ events: IntegrationEventEntry[]; nextCursor: string | null }>(\n 'GET',\n `/v2/connections/${encodeURIComponent(connectionId)}/events?${query}`,\n );\n this.deps?.logger.debug('Platform GitLab connection event poll completed', {\n connectionId,\n eventCount: page.events.length,\n latencyMs: Math.round(performance.now() - pollStartedAt),\n });\n if (page.events.length === 0 || !page.nextCursor) return;\n\n for (const event of page.events) {\n if (!this.#running || !this.#hasLease) return;\n await this.#processEvent(connectionId, event);\n }\n\n if (page.nextCursor === cursor.afterEventId) return;\n // A replica that lost its lease while processing this page must not\n // write a cursor over one the new holder has already advanced. The\n // page is replayed there; delivery is deduplicated by delivery id.\n if (!this.#hasLease) return;\n this.#settings.connections[connectionId] = { afterEventId: page.nextCursor };\n await this.#saveSettings();\n }\n }\n\n async #processEvent(connectionId: string, event: IntegrationEventEntry): Promise<void> {\n if (!event.id) {\n this.deps?.logger.warn('Platform GitLab event log returned an event without an id', { connectionId });\n return;\n }\n const deliveryId = `${DELIVERY_ID_PREFIX}:${connectionId}:${event.id}`;\n const parsed = parseGitLabWebhookBody(event.payload, deliveryId);\n if (!parsed) {\n // Pipelines, deployments, wiki edits and the like: acknowledged and\n // dropped, exactly as the direct route treats an unsupported event header.\n this.deps?.logger.debug('Platform GitLab event ignored: unsupported or malformed body', {\n connectionId,\n eventId: event.id,\n eventType: event.eventType,\n });\n return;\n }\n\n const result = await this.#process(parsed, {\n ingestFactoryEvent: this.#ingestFactoryEvent,\n controller: this.#controller,\n // The integration supplies subscription storage and the project-member\n // trust check, so the dispatcher's default author gate applies unchanged.\n gitlab: this.#gitlab,\n sourceConnectionId: connectionId,\n onConnectionMismatch: subscription => {\n // Expected whenever two connections reach the same project: the\n // event is delivered by the connection that created the subscription.\n this.deps?.logger.debug('Platform GitLab event skipped: subscription belongs to another connection', {\n deliveryId,\n subscriptionId: subscription.id,\n subscriptionConnectionId: subscription.data.installationExternalId,\n });\n },\n onTargetSkipped: subscription => {\n // Routine when a subscription's thread belongs to another deployment,\n // so this stays at debug rather than warning on a loop.\n this.deps?.logger.debug('Platform GitLab event skipped: thread is not held here', {\n deliveryId,\n subscriptionId: subscription.id,\n threadId: subscription.threadId,\n });\n },\n onSenderRejected: notification => {\n this.deps?.logger.debug('Platform GitLab event dropped: sender not authorized', {\n deliveryId,\n repository: notification.metadata.projectPath,\n sender: notification.metadata.sender,\n kind: notification.kind,\n });\n },\n onTargetError: (subscription, error) => {\n this.deps?.logger.error('Platform GitLab event delivery failed for a subscription', {\n deliveryId,\n subscriptionId: subscription.id,\n resourceId: subscription.resourceId,\n threadId: subscription.threadId,\n error: error instanceof Error ? error.message : String(error),\n });\n },\n });\n if (result.status !== 202) {\n this.deps?.logger.warn('Platform GitLab event was not accepted by the webhook processor', {\n connectionId,\n deliveryId,\n status: result.status,\n });\n }\n }\n\n async #saveSettings(): Promise<void> {\n await this.#storage.settings.save(CURSOR_ORG_ID, CURSOR_USER_ID, this.#settings);\n }\n\n #leaseKey(): string {\n return `${this.name}:${this.#storage.integrationId}`;\n }\n}\n\nfunction getLeaseProvider(pubsub: PubSub): LeaseProvider {\n const getProvider = (pubsub as PubSub & { getLeaseProvider?: () => LeaseProvider | undefined }).getLeaseProvider;\n if (typeof getProvider === 'function') return getProvider.call(pubsub) ?? NoopLeaseProvider;\n return isLeaseProvider(pubsub) ? pubsub : NoopLeaseProvider;\n}\n\nfunction normalizeSettings(value: PlatformGitLabEventWorkerSettings | null): PlatformGitLabEventWorkerSettings {\n if (!value || value.version !== 1 || !value.connections || typeof value.connections !== 'object') {\n return { version: 1, connections: {} };\n }\n const connections: PlatformGitLabEventWorkerSettings['connections'] = {};\n for (const [connectionId, cursor] of Object.entries(value.connections)) {\n if (typeof cursor?.afterEventId === 'string' && cursor.afterEventId.length > 0) {\n connections[connectionId] = { afterEventId: cursor.afterEventId };\n }\n }\n return { version: 1, connections };\n}\n\nfunction retryDelay(error: unknown, fallbackMs: number): number {\n if (error instanceof PlatformApiError && error.status === 429 && error.retryAfterSeconds !== null) {\n return Math.max(fallbackMs, error.retryAfterSeconds * 1_000);\n }\n return fallbackMs;\n}\n"],"mappings":";;;;;;AAeA,MAAM,2BAA2B;AACjC,MAAM,kBAAkB;;;;;;AAMxB,MAAM,qCAAqC;AAC3C,MAAM,mBAAmB;AACzB,MAAM,gBAAgB;AACtB,MAAM,iBAAiB;AACvB,MAAM,qBAAqB;;;;;;;;;;;;;AAuD3B,IAAa,4BAAb,cAA+C,aAAa;CAC1D,OAAgB;CAEhB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA,cAAuB,WAAW;CAElC,WAAW;CACX;CACA;CACA;CACA,iBAAgC;CAChC;CACA,YAAY;CACZ,aAAa;CACb,YAA+C;EAAE,SAAS;EAAG,aAAa,CAAC;CAAE;CAE7E,YAAY,QAAyC;EACnD,MAAM;EACN,KAAKA,UAAU,OAAO;EACtB,KAAKC,cAAc,OAAO;EAC1B,KAAKC,UAAU,OAAO;EACtB,KAAKC,WAAW,OAAO;EACvB,KAAKC,mBAAmB,OAAO;EAC/B,KAAKC,sBAAsB,OAAO;EAClC,KAAKC,cAAc,OAAO,cAAc;EACxC,IAAI,CAAC,OAAO,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AAS,GAC3E,YAAY,gBAAgB,EAAE,cAAc,OAAO,aAAa;CAGpE,OAAO;EAAE,SAAS;EAAG;CAAY;AACnC;AAEA,SAAS,WAAW,OAAgB,YAA4B;CAC9D,IAAI,iBAAiB,oBAAoB,MAAM,WAAW,OAAO,MAAM,sBAAsB,MAC3F,OAAO,KAAK,IAAI,YAAY,MAAM,oBAAoB,GAAK;CAE7D,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"event-worker.js","names":["#client","#controller","#gitlab","#storage","#listConnections","#ingestFactoryEvent","#intervalMs","#now","#process","#leaseOwner","#leaseTtlMs","#leaseProvider","#running","#startedAt","#settings","#schedule","#timer","#stopLeaseRenewal","#inFlight","#hasLease","#leaseKey","#tick","#ensureLease","#poll","#startLeaseRenewal","#leaseRenewalTimer","#pollConnection","#saveSettings","#processEvent"],"sources":["../../../../src/integrations/platform/gitlab/event-worker.ts"],"sourcesContent":["import type { MountedMastraCode } from '@mastra/code-sdk';\nimport { isLeaseProvider, NoopLeaseProvider } from '@mastra/core/events';\nimport type { LeaseProvider, PubSub } from '@mastra/core/events';\nimport { MastraWorker } from '@mastra/core/worker';\nimport type { WorkerDeps } from '@mastra/core/worker';\n\nimport type { IntegrationStorageHandle } from '../../../storage/domains/integrations/base.js';\nimport type { GitLabWebhookDispatchIntegration } from '../../gitlab/webhook-dispatch.js';\nimport { parseGitLabWebhookBody, processGitLabWebhook } from '../../gitlab/webhook.js';\nimport type { ParsedGitLabWebhook } from '../../gitlab/webhook.js';\nimport type { PlatformApiClient } from '../api-client.js';\nimport { PlatformApiError } from '../api-client.js';\n\nconst DEFAULT_POLL_INTERVAL_MS = 20_000;\nconst EVENT_PAGE_SIZE = 500;\n/**\n * Pages drained per connection per cycle. A connection that never runs dry\n * (a busy group webhook, or a backlog after downtime) hands over to the next\n * connection after this many pages and resumes from its saved cursor next tick.\n */\nconst MAX_PAGES_PER_CONNECTION_PER_CYCLE = 10;\nconst MIN_LEASE_TTL_MS = 30_000;\nconst CURSOR_ORG_ID = '__platform_gitlab_event_worker__';\nconst CURSOR_USER_ID = 'worker';\nconst DELIVERY_ID_PREFIX = 'platform';\n\ntype PlatformGitLabEventWorkerSettings = {\n version: 1;\n connections: Record<string, { afterEventId: string }>;\n};\n\nexport type PlatformGitLabEventStorage = IntegrationStorageHandle<\n Record<string, unknown>,\n PlatformGitLabEventWorkerSettings,\n Record<string, unknown>\n>;\n\n/** One row of the Platform integration event log. */\nexport interface IntegrationEventEntry {\n id: string;\n timestamp: number;\n integrationId: string;\n eventType: string;\n sourceEventId: string | null;\n payload: unknown;\n}\n\nexport interface PlatformGitLabEventConnection {\n id: string;\n status: 'active' | 'needs_reauth';\n}\n\nexport type PlatformGitLabEventDispatchIntegration = GitLabWebhookDispatchIntegration;\n\nexport interface PlatformGitLabEventWorkerConfig {\n client: PlatformApiClient;\n controller: MountedMastraCode['controller'];\n gitlab: PlatformGitLabEventDispatchIntegration;\n storage: PlatformGitLabEventStorage;\n /** Platform connections to tail; only `active` ones are polled. */\n listConnections: () => Promise<PlatformGitLabEventConnection[]>;\n ingestFactoryEvent?: (event: ParsedGitLabWebhook) => Promise<unknown>;\n intervalMs?: number;\n now?: () => number;\n process?: typeof processGitLabWebhook;\n}\n\n/**\n * Tails the Platform event log for every active GitLab connection and feeds\n * each stored webhook body through the same ingress the direct\n * `/web/gitlab/webhook` route uses. A Platform-managed connection has no\n * project webhook pointing at Factory, so this is how issue, note, merge\n * request and push events reach the rules engine and subscribed sessions.\n *\n * One replica polls at a time (lease). Each connection keeps its own cursor,\n * persisted only after a whole page has been processed, so a crash mid-page\n * replays the page rather than losing it; replay handling in the rules ingress\n * and the delivery-id dedupe keys make that safe.\n */\nexport class PlatformGitLabEventWorker extends MastraWorker {\n readonly name = 'platform-gitlab-events';\n\n readonly #client: PlatformApiClient;\n readonly #controller: MountedMastraCode['controller'];\n readonly #gitlab: PlatformGitLabEventDispatchIntegration;\n readonly #storage: PlatformGitLabEventStorage;\n readonly #listConnections: () => Promise<PlatformGitLabEventConnection[]>;\n readonly #ingestFactoryEvent: ((event: ParsedGitLabWebhook) => Promise<unknown>) | undefined;\n readonly #intervalMs: number;\n readonly #now: () => number;\n readonly #process: typeof processGitLabWebhook;\n readonly #leaseOwner = globalThis.crypto.randomUUID();\n\n #running = false;\n #timer: ReturnType<typeof setTimeout> | undefined;\n #leaseRenewalTimer: ReturnType<typeof setInterval> | undefined;\n #inFlight: Promise<void> | undefined;\n #leaseProvider: LeaseProvider = NoopLeaseProvider;\n #leaseTtlMs: number;\n #hasLease = false;\n #startedAt = 0;\n #settings: PlatformGitLabEventWorkerSettings = { version: 1, connections: {} };\n\n constructor(config: PlatformGitLabEventWorkerConfig) {\n super();\n this.#client = config.client;\n this.#controller = config.controller;\n this.#gitlab = config.gitlab;\n this.#storage = config.storage;\n this.#listConnections = config.listConnections;\n this.#ingestFactoryEvent = config.ingestFactoryEvent;\n this.#intervalMs = config.intervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n if (!Number.isFinite(this.#intervalMs) || this.#intervalMs <= 0) {\n throw new Error('Platform GitLab event polling interval must be a positive number.');\n }\n this.#leaseTtlMs = Math.max(MIN_LEASE_TTL_MS, this.#intervalMs * 3);\n this.#now = config.now ?? Date.now;\n this.#process = config.process ?? processGitLabWebhook;\n }\n\n async init(deps: WorkerDeps): Promise<void> {\n await super.init(deps);\n this.#leaseProvider = getLeaseProvider(deps.pubsub);\n }\n\n async start(): Promise<void> {\n if (this.#running) return;\n if (!this.deps) throw new Error('PlatformGitLabEventWorker: call init() before start()');\n\n this.#startedAt = this.#now() - 1;\n this.#settings = normalizeSettings(await this.#storage.settings.get(CURSOR_ORG_ID, CURSOR_USER_ID));\n this.#running = true;\n this.deps.logger.info('Platform GitLab event polling started', {\n intervalMs: this.#intervalMs,\n leaseTtlMs: this.#leaseTtlMs,\n });\n this.#schedule(0);\n }\n\n async stop(): Promise<void> {\n if (!this.#running) return;\n this.#running = false;\n if (this.#timer) clearTimeout(this.#timer);\n this.#timer = undefined;\n this.#stopLeaseRenewal();\n await this.#inFlight;\n if (this.#hasLease) {\n await this.#leaseProvider.releaseLease(this.#leaseKey(), this.#leaseOwner).catch(() => undefined);\n this.#hasLease = false;\n }\n }\n\n get isRunning(): boolean {\n return this.#running;\n }\n\n #schedule(delayMs: number): void {\n if (!this.#running) return;\n this.#timer = setTimeout(() => {\n this.#timer = undefined;\n const run = this.#tick();\n this.#inFlight = run;\n void run.finally(() => {\n if (this.#inFlight === run) this.#inFlight = undefined;\n });\n }, delayMs);\n this.#timer.unref?.();\n }\n\n async #tick(): Promise<void> {\n let nextDelay = this.#intervalMs;\n try {\n if (!(await this.#ensureLease())) return;\n nextDelay = await this.#poll();\n } catch (error) {\n nextDelay = retryDelay(error, this.#intervalMs);\n this.deps?.logger.error('Platform GitLab event polling cycle failed', {\n error: error instanceof Error ? error.message : String(error),\n retryInMs: nextDelay,\n });\n } finally {\n this.#schedule(nextDelay);\n }\n }\n\n async #ensureLease(): Promise<boolean> {\n if (this.#hasLease) return true;\n const result = await this.#leaseProvider.acquireLease(this.#leaseKey(), this.#leaseOwner, this.#leaseTtlMs);\n this.#hasLease = result.acquired;\n if (this.#hasLease) this.#startLeaseRenewal();\n return this.#hasLease;\n }\n\n #startLeaseRenewal(): void {\n if (this.#leaseRenewalTimer) return;\n this.#leaseRenewalTimer = setInterval(\n () => {\n void this.#leaseProvider\n .renewLease(this.#leaseKey(), this.#leaseOwner, this.#leaseTtlMs)\n .then(renewed => {\n if (!renewed) {\n this.#hasLease = false;\n this.#stopLeaseRenewal();\n }\n })\n .catch(error => {\n this.#hasLease = false;\n this.#stopLeaseRenewal();\n this.deps?.logger.warn('Platform GitLab event polling lease renewal failed', {\n error: error instanceof Error ? error.message : String(error),\n });\n });\n },\n Math.floor(this.#leaseTtlMs / 3),\n );\n this.#leaseRenewalTimer.unref?.();\n }\n\n #stopLeaseRenewal(): void {\n if (this.#leaseRenewalTimer) clearInterval(this.#leaseRenewalTimer);\n this.#leaseRenewalTimer = undefined;\n }\n\n async #poll(): Promise<number> {\n const connections = (await this.#listConnections()).filter(connection => connection.status === 'active');\n let retryInMs = this.#intervalMs;\n\n for (const connection of connections) {\n if (!this.#running || !this.#hasLease) break;\n try {\n await this.#pollConnection(connection.id);\n } catch (error) {\n if (error instanceof PlatformApiError && (error.status === 401 || error.status === 404)) {\n // Platform no longer serves this connection (revoked, expired or\n // deleted). Its status will read needs_reauth on the next listing;\n // nothing to retry here, so the other connections keep flowing.\n this.deps?.logger.warn('Platform GitLab connection needs reauthorization; skipped this cycle', {\n connectionId: connection.id,\n status: error.status,\n });\n continue;\n }\n const delay = retryDelay(error, this.#intervalMs);\n retryInMs = Math.max(retryInMs, delay);\n this.deps?.logger.error('Platform GitLab connection event polling failed', {\n connectionId: connection.id,\n error: error instanceof Error ? error.message : String(error),\n retryInMs: delay,\n });\n if (error instanceof PlatformApiError && error.status === 429) break;\n }\n }\n return retryInMs;\n }\n\n async #pollConnection(connectionId: string): Promise<void> {\n if (!this.#settings.connections[connectionId]) {\n // Event ids are Redis stream ids (`<unix ms>-<sequence>`), so a\n // synthesized id at start time skips history the same way the GitHub\n // worker's start timestamp does. Events that arrived before Factory was\n // deployed are not work Factory was asked to do.\n this.#settings.connections[connectionId] = { afterEventId: `${this.#startedAt}-0` };\n await this.#saveSettings();\n }\n\n for (let pageIndex = 0; this.#running && this.#hasLease; pageIndex += 1) {\n if (pageIndex >= MAX_PAGES_PER_CONNECTION_PER_CYCLE) {\n this.deps?.logger.debug('Platform GitLab connection page budget reached; resuming next cycle', {\n connectionId,\n pages: pageIndex,\n });\n return;\n }\n const cursor: { afterEventId: string } = this.#settings.connections[connectionId]!;\n const query = new URLSearchParams({ afterEventId: cursor.afterEventId, limit: String(EVENT_PAGE_SIZE) });\n const pollStartedAt = performance.now();\n const page = await this.#client.request<{ events: IntegrationEventEntry[]; nextCursor: string | null }>(\n 'GET',\n `/v2/connections/${encodeURIComponent(connectionId)}/events?${query}`,\n );\n this.deps?.logger.debug('Platform GitLab connection event poll completed', {\n connectionId,\n eventCount: page.events.length,\n latencyMs: Math.round(performance.now() - pollStartedAt),\n });\n if (page.events.length === 0 || !page.nextCursor) return;\n\n for (const event of page.events) {\n if (!this.#running || !this.#hasLease) return;\n await this.#processEvent(connectionId, event);\n }\n\n if (page.nextCursor === cursor.afterEventId) return;\n // A replica that lost its lease while processing this page must not\n // write a cursor over one the new holder has already advanced. The\n // page is replayed there; delivery is deduplicated by delivery id.\n if (!this.#hasLease) return;\n this.#settings.connections[connectionId] = { afterEventId: page.nextCursor };\n await this.#saveSettings();\n }\n }\n\n async #processEvent(connectionId: string, event: IntegrationEventEntry): Promise<void> {\n if (!event.id) {\n this.deps?.logger.warn('Platform GitLab event log returned an event without an id', { connectionId });\n return;\n }\n const deliveryId = `${DELIVERY_ID_PREFIX}:${connectionId}:${event.id}`;\n const parsed = parseGitLabWebhookBody(event.payload, deliveryId);\n if (!parsed) {\n // Pipelines, deployments, wiki edits and the like: acknowledged and\n // dropped, exactly as the direct route treats an unsupported event header.\n this.deps?.logger.debug('Platform GitLab event ignored: unsupported or malformed body', {\n connectionId,\n eventId: event.id,\n eventType: event.eventType,\n });\n return;\n }\n\n const result = await this.#process(parsed, {\n ingestFactoryEvent: this.#ingestFactoryEvent,\n controller: this.#controller,\n // The integration supplies subscription storage and the project-member\n // trust check, so the dispatcher's default author gate applies unchanged.\n gitlab: this.#gitlab,\n sourceConnectionId: connectionId,\n onConnectionMismatch: subscription => {\n // Expected whenever two connections reach the same project: the\n // event is delivered by the connection that created the subscription.\n this.deps?.logger.debug('Platform GitLab event skipped: subscription belongs to another connection', {\n deliveryId,\n subscriptionId: subscription.id,\n subscriptionConnectionId: subscription.data.installationExternalId,\n });\n },\n onTargetSkipped: subscription => {\n // Routine when a subscription's thread belongs to another deployment,\n // so this stays at debug rather than warning on a loop.\n this.deps?.logger.debug('Platform GitLab event skipped: thread is not held here', {\n deliveryId,\n subscriptionId: subscription.id,\n threadId: subscription.threadId,\n });\n },\n onSenderRejected: notification => {\n this.deps?.logger.debug('Platform GitLab event dropped: sender not authorized', {\n deliveryId,\n repository: notification.metadata.projectPath,\n sender: notification.metadata.sender,\n kind: notification.kind,\n });\n },\n onTargetError: (subscription, error) => {\n this.deps?.logger.error('Platform GitLab event delivery failed for a subscription', {\n deliveryId,\n subscriptionId: subscription.id,\n resourceId: subscription.resourceId,\n threadId: subscription.threadId,\n error: error instanceof Error ? error.message : String(error),\n });\n },\n });\n if (result.status !== 202) {\n this.deps?.logger.warn('Platform GitLab event was not accepted by the webhook processor', {\n connectionId,\n deliveryId,\n status: result.status,\n });\n }\n }\n\n async #saveSettings(): Promise<void> {\n await this.#storage.settings.save(CURSOR_ORG_ID, CURSOR_USER_ID, this.#settings);\n }\n\n #leaseKey(): string {\n return `${this.name}:${this.#storage.integrationId}`;\n }\n}\n\nfunction getLeaseProvider(pubsub: PubSub): LeaseProvider {\n const getProvider = (pubsub as PubSub & { getLeaseProvider?: () => LeaseProvider | undefined }).getLeaseProvider;\n if (typeof getProvider === 'function') return getProvider.call(pubsub) ?? NoopLeaseProvider;\n return isLeaseProvider(pubsub) ? pubsub : NoopLeaseProvider;\n}\n\nfunction normalizeSettings(value: PlatformGitLabEventWorkerSettings | null): PlatformGitLabEventWorkerSettings {\n if (!value || value.version !== 1 || !value.connections || typeof value.connections !== 'object') {\n return { version: 1, connections: {} };\n }\n const connections: PlatformGitLabEventWorkerSettings['connections'] = {};\n for (const [connectionId, cursor] of Object.entries(value.connections)) {\n if (typeof cursor?.afterEventId === 'string' && cursor.afterEventId.length > 0) {\n connections[connectionId] = { afterEventId: cursor.afterEventId };\n }\n }\n return { version: 1, connections };\n}\n\nfunction retryDelay(error: unknown, fallbackMs: number): number {\n if (error instanceof PlatformApiError && error.status === 429 && error.retryAfterSeconds !== null) {\n return Math.max(fallbackMs, error.retryAfterSeconds * 1_000);\n }\n return fallbackMs;\n}\n"],"mappings":";;;;;AAaA,MAAM,2BAA2B;AACjC,MAAM,kBAAkB;;;;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+B;EACnC,MAAM,KAAKxB,SAAS,SAAS,KAAK,eAAe,gBAAgB,KAAKW,SAAS;CACjF;CAEA,YAAoB;EAClB,OAAO,GAAG,KAAK,KAAK,GAAG,KAAKX,SAAS;CACvC;AACF;AAEA,SAAS,iBAAiB,QAA+B;CACvD,MAAM,cAAe,OAA2E;CAChG,IAAI,OAAO,gBAAgB,YAAY,OAAO,YAAY,KAAK,MAAM,KAAK;CAC1E,OAAO,gBAAgB,MAAM,IAAI,SAAS;AAC5C;AAEA,SAAS,kBAAkB,OAAoF;CAC7G,IAAI,CAAC,SAAS,MAAM,YAAY,KAAK,CAAC,MAAM,eAAe,OAAO,MAAM,gBAAgB,UACtF,OAAO;EAAE,SAAS;EAAG,aAAa,CAAC;CAAE;CAEvC,MAAM,cAAgE,CAAC;CACvE,KAAK,MAAM,CAAC,cAAc,WAAW,OAAO,QAAQ,MAAM,WAAW,GACnE,IAAI,OAAO,QAAQ,iBAAiB,YAAY,OAAO,aAAa,SAAS,GAC3E,YAAY,gBAAgB,EAAE,cAAc,OAAO,aAAa;CAGpE,OAAO;EAAE,SAAS;EAAG;CAAY;AACnC;AAEA,SAAS,WAAW,OAAgB,YAA4B;CAC9D,IAAI,iBAAiB,oBAAoB,MAAM,WAAW,OAAO,MAAM,sBAAsB,MAC3F,OAAO,KAAK,IAAI,YAAY,MAAM,oBAAoB,GAAK;CAE7D,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"event-worker.d.ts","sourceRoot":"","sources":["../../../../src/integrations/platform/linear/event-worker.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"event-worker.d.ts","sourceRoot":"","sources":["../../../../src/integrations/platform/linear/event-worker.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACnD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AAEtD,OAAO,KAAK,EAAE,wBAAwB,EAAE,M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AAM,CAAC;IAC1B,mBAAmB,CAAC,EAAE,MAAM,CAAC;CAC9B;AAED;;;GAGG;AACH,MAAM,WAAW,sCAAsC;IACrD,cAAc,IAAI,OAAO,CAAC,uBAAuB,EAAE,CAAC,CAAC;CACtD;AAED,MAAM,WAAW,+BAA+B;IAC9C,MAAM,EAAE,iBAAiB,CAAC;IAC1B,MAAM,EAAE,sCAAsC,CAAC;IAC/C,OAAO,EAAE,0BAA0B,CAAC;IACpC,QAAQ,EAAE,IAAI,CAAC,sBAAsB,EAAE,SAAS,CAAC,CAAC;IAClD;;;;;;;OAOG;IACH,SAAS,EAAE,IAAI,CAAC,gBAAgB,EAAE,MAAM,CAAC,CAAC;IAC1C,gFAAgF;IAChF,kBAAkB,CAAC,EAAE,CAAC,KAAK,EAAE,kBAAkB,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;IACrE,qBAAqB,CAAC,EAAE,eAAe,CAAC;IACxC,mFAAmF;IACnF,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;CACpB;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,qBAAa,yBAA0B,SAAQ,YAAY;;IACzD,QAAQ,CAAC,IAAI,4BAA4B;gBA0B7B,MAAM,EAAE,+BAA+B;IAsB7C,IAAI,CAAC,IAAI,EAAE,UAAU,GAAG,OAAO,CAAC,IAAI,CAAC;IAKrC,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IActB,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAa3B,IAAI,SAAS,IAAI,OAAO,CAEvB;CAuQF"}
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { PlatformApiError } from "../api-client.js";
|
|
2
2
|
import { NoopLeaseProvider, isLeaseProvider } from "@mastra/core/events";
|
|
3
|
-
import { randomUUID } from "crypto";
|
|
4
3
|
import { MastraWorker } from "@mastra/core/worker";
|
|
5
4
|
//#region src/integrations/platform/linear/event-worker.ts
|
|
6
5
|
const API_PREFIX = "/v1/server/linear";
|
|
@@ -47,7 +46,7 @@ var PlatformLinearEventWorker = class extends MastraWorker {
|
|
|
47
46
|
#intervalMs;
|
|
48
47
|
#reconcileIntervalMs;
|
|
49
48
|
#now;
|
|
50
|
-
#leaseOwner = randomUUID();
|
|
49
|
+
#leaseOwner = globalThis.crypto.randomUUID();
|
|
51
50
|
#running = false;
|
|
52
51
|
#timer;
|
|
53
52
|
#leaseRenewalTimer;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"event-worker.js","names":["#client","#linear","#storage","#projects","#workItems","#ingestFactoryIssue","#reconcileFactoryState","#pollEventsEnabled","#intervalMs","#reconcileIntervalMs","#now","#leaseOwner","#leaseTtlMs","#leaseProvider","#running","#startedAt","#settings","#schedule","#timer","#stopLeaseRenewal","#inFlight","#hasLease","#tick","#ensureLease","#poll","#startLeaseRenewal","#leaseRenewalTimer","#pollWorkspace","#maybeReconcile","#lastReconcileAt","#saveSettings","#dispatchEvent"],"sources":["../../../../src/integrations/platform/linear/event-worker.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\n\nimport { isLeaseProvider, NoopLeaseProvider } from '@mastra/core/events';\nimport type { LeaseProvider, PubSub } from '@mastra/core/events';\nimport { MastraWorker } from '@mastra/core/worker';\nimport type { WorkerDeps } from '@mastra/core/worker';\n\nimport type { IntegrationStorageHandle } from '../../../storage/domains/integrations/base.js';\nimport type { FactoryProjectsStorage } from '../../../storage/domains/projects/base.js';\nimport type { WorkItemsStorage } from '../../../storage/domains/work-items/base.js';\nimport type { IssueReconciler } from '../../issue-reconciler.js';\nimport type { LinearIssueIngress, LinearRulesIngress } from '../../linear/rules.js';\nimport { PlatformApiClient, PlatformApiError } from '../api-client.js';\n\nconst API_PREFIX = '/v1/server/linear';\nconst DEFAULT_POLL_INTERVAL_MS = 20_000;\nconst DEFAULT_RECONCILE_INTERVAL_MS = 5 * 60_000;\nconst EVENT_PAGE_SIZE = 500;\nconst MIN_LEASE_TTL_MS = 30_000;\nconst CURSOR_ORG_ID = '__platform_linear_event_worker__';\nconst CURSOR_USER_ID = 'worker';\nconst LEASE_KEY = 'platform-linear-events:linear';\n\ntype EventCursor = { afterEventId: string } | { afterTimestamp: number };\ntype PlatformLinearEventWorkerSettings = {\n version: 1;\n workspaces: Record<string, EventCursor>;\n};\n\nexport type PlatformLinearEventStorage = IntegrationStorageHandle<\n Record<string, unknown>,\n PlatformLinearEventWorkerSettings,\n Record<string, unknown>\n>;\n\n/**\n * Minimal envelope shape mirrored from `@platform/linear`. Kept opaque\n * (`data: unknown`) — every consumer demuxes by `type`.\n */\nexport interface LinearWebhookEnvelope {\n type: string;\n action: string | null;\n createdAt: string | null;\n webhookTimestamp: number | null;\n linearOrganizationId: string | null;\n oauthClientId: string | null;\n url: string | null;\n data: unknown;\n}\n\nexport interface LinearEventLogEntry {\n id: string;\n timestamp: number;\n envelope: LinearWebhookEnvelope;\n}\n\nexport interface PlatformLinearWorkspace {\n linearWorkspaceId: string;\n linearWorkspaceName?: string;\n}\n\n/**\n * Everything the worker needs to drive ingest + reconciliation without\n * pulling in the full `PlatformLinearIntegration` type (circular).\n */\nexport interface PlatformLinearEventDispatchIntegration {\n listWorkspaces(): Promise<PlatformLinearWorkspace[]>;\n}\n\nexport interface PlatformLinearEventWorkerConfig {\n client: PlatformApiClient;\n linear: PlatformLinearEventDispatchIntegration;\n storage: PlatformLinearEventStorage;\n projects: Pick<FactoryProjectsStorage, 'listAll'>;\n /**\n * Used to scope event dispatch to `(orgId, factoryProjectId)` pairs that\n * already have a work item linked to the incoming Linear issue. Without\n * this scoping, a workspace-scoped event would fan out to every project in\n * every org and materialize a triage card in each — a cross-tenant leak.\n * First-observation of a Linear issue happens through the user-authenticated\n * `/web/linear/issues?factoryProjectId=...` intake path instead.\n */\n workItems: Pick<WorkItemsStorage, 'list'>;\n /** Called with a single-issue rules ingress derived from an `Issue` webhook. */\n ingestFactoryIssue?: (input: LinearRulesIngress) => Promise<unknown>;\n reconcileFactoryState?: IssueReconciler;\n /** When false the worker skips event tailing and only runs the reconcile sweep. */\n pollEventsEnabled?: boolean;\n intervalMs?: number;\n reconcileIntervalMs?: number;\n now?: () => number;\n}\n\n/**\n * Tails the Platform Linear event stream (Redis-backed, per workspace) and\n * runs the same folded issue-reconcile sweep pattern as\n * `PlatformGithubEventWorker`. Issue events are translated into a normal\n * `LinearRulesIngress` so downstream rule dispatch is identical to the\n * polling path.\n *\n * Cursor state is persisted per workspace via the integration's generic\n * settings surface, keyed by a well-known worker identity. Cold start uses\n * `afterTimestamp: now - 1` to avoid replaying the 14-day stream backlog.\n *\n * ## Delivery semantics\n *\n * **At-most-once** per event. The cursor advances to the last event ID in a\n * page after all dispatch attempts on that page complete, regardless of\n * whether individual ingest calls threw. Ingest failures are logged, the\n * offending event is not retried, and drift is caught by the folded\n * `LinearIssueReconciler` sweep on its own cadence (default 5 minutes). This\n * matches `PlatformGithubEventWorker` and avoids poison-pill events blocking\n * the whole stream. Any consumer that needs exactly-once must idempotently\n * handle the same issue arriving via both the event path and the reconcile\n * path.\n */\nexport class PlatformLinearEventWorker extends MastraWorker {\n readonly name = 'platform-linear-events';\n\n readonly #client: PlatformApiClient;\n readonly #linear: PlatformLinearEventDispatchIntegration;\n readonly #storage: PlatformLinearEventStorage;\n readonly #projects: Pick<FactoryProjectsStorage, 'listAll'>;\n readonly #workItems: Pick<WorkItemsStorage, 'list'>;\n readonly #ingestFactoryIssue: ((input: LinearRulesIngress) => Promise<unknown>) | undefined;\n readonly #reconcileFactoryState: IssueReconciler | undefined;\n readonly #pollEventsEnabled: boolean;\n readonly #intervalMs: number;\n readonly #reconcileIntervalMs: number;\n readonly #now: () => number;\n readonly #leaseOwner = randomUUID();\n\n #running = false;\n #timer: ReturnType<typeof setTimeout> | undefined;\n #leaseRenewalTimer: ReturnType<typeof setInterval> | undefined;\n #inFlight: Promise<void> | undefined;\n #leaseProvider: LeaseProvider = NoopLeaseProvider;\n #leaseTtlMs: number;\n #hasLease = false;\n #startedAt = 0;\n #lastReconcileAt = 0;\n #settings: PlatformLinearEventWorkerSettings = { version: 1, workspaces: {} };\n\n constructor(config: PlatformLinearEventWorkerConfig) {\n super();\n this.#client = config.client;\n this.#linear = config.linear;\n this.#storage = config.storage;\n this.#projects = config.projects;\n this.#workItems = config.workItems;\n this.#ingestFactoryIssue = config.ingestFactoryIssue;\n this.#reconcileFactoryState = config.reconcileFactoryState;\n this.#pollEventsEnabled = config.pollEventsEnabled ?? true;\n this.#intervalMs = config.intervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n this.#reconcileIntervalMs = config.reconcileIntervalMs ?? DEFAULT_RECONCILE_INTERVAL_MS;\n if (!Number.isFinite(this.#intervalMs) || this.#intervalMs <= 0) {\n throw new Error('Platform Linear event polling interval must be a positive number.');\n }\n if (!Number.isFinite(this.#reconcileIntervalMs) || this.#reconcileIntervalMs <= 0) {\n throw new Error('Platform Linear reconcile interval must be a positive number.');\n }\n this.#leaseTtlMs = Math.max(MIN_LEASE_TTL_MS, this.#intervalMs * 3);\n this.#now = config.now ?? Date.now;\n }\n\n async init(deps: WorkerDeps): Promise<void> {\n await super.init(deps);\n this.#leaseProvider = getLeaseProvider(deps.pubsub);\n }\n\n async start(): Promise<void> {\n if (this.#running) return;\n if (!this.deps) throw new Error('PlatformLinearEventWorker: call init() before start()');\n\n this.#startedAt = this.#now() - 1;\n this.#settings = normalizeSettings(await this.#storage.settings.get(CURSOR_ORG_ID, CURSOR_USER_ID));\n this.#running = true;\n this.deps.logger.info('Platform Linear event polling started', {\n intervalMs: this.#intervalMs,\n leaseTtlMs: this.#leaseTtlMs,\n });\n this.#schedule(0);\n }\n\n async stop(): Promise<void> {\n if (!this.#running) return;\n this.#running = false;\n if (this.#timer) clearTimeout(this.#timer);\n this.#timer = undefined;\n this.#stopLeaseRenewal();\n await this.#inFlight;\n if (this.#hasLease) {\n await this.#leaseProvider.releaseLease(LEASE_KEY, this.#leaseOwner).catch(() => undefined);\n this.#hasLease = false;\n }\n }\n\n get isRunning(): boolean {\n return this.#running;\n }\n\n #schedule(delayMs: number): void {\n if (!this.#running) return;\n this.#timer = setTimeout(() => {\n this.#timer = undefined;\n const run = this.#tick();\n this.#inFlight = run;\n void run.finally(() => {\n if (this.#inFlight === run) this.#inFlight = undefined;\n });\n }, delayMs);\n this.#timer.unref?.();\n }\n\n async #tick(): Promise<void> {\n let nextDelay = this.#intervalMs;\n try {\n if (!(await this.#ensureLease())) return;\n nextDelay = await this.#poll();\n } catch (error) {\n nextDelay = retryDelay(error, this.#intervalMs);\n this.deps?.logger.error('Platform Linear event polling cycle failed', {\n error: error instanceof Error ? error.message : String(error),\n retryInMs: nextDelay,\n });\n } finally {\n this.#schedule(nextDelay);\n }\n }\n\n async #ensureLease(): Promise<boolean> {\n if (this.#hasLease) return true;\n const result = await this.#leaseProvider.acquireLease(LEASE_KEY, this.#leaseOwner, this.#leaseTtlMs);\n this.#hasLease = result.acquired;\n if (this.#hasLease) this.#startLeaseRenewal();\n return this.#hasLease;\n }\n\n #startLeaseRenewal(): void {\n if (this.#leaseRenewalTimer) return;\n this.#leaseRenewalTimer = setInterval(\n () => {\n void this.#leaseProvider\n .renewLease(LEASE_KEY, this.#leaseOwner, this.#leaseTtlMs)\n .then(renewed => {\n if (!renewed) {\n this.#hasLease = false;\n this.#stopLeaseRenewal();\n }\n })\n .catch(error => {\n this.#hasLease = false;\n this.#stopLeaseRenewal();\n this.deps?.logger.warn('Platform Linear event polling lease renewal failed', {\n error: error instanceof Error ? error.message : String(error),\n });\n });\n },\n Math.floor(this.#leaseTtlMs / 3),\n );\n this.#leaseRenewalTimer.unref?.();\n }\n\n #stopLeaseRenewal(): void {\n if (this.#leaseRenewalTimer) clearInterval(this.#leaseRenewalTimer);\n this.#leaseRenewalTimer = undefined;\n }\n\n async #poll(): Promise<number> {\n // Reconcile-only mode has no event tail to keep fresh, so tick on the\n // slower reconcile cadence instead of the polling interval.\n let retryInMs = this.#pollEventsEnabled ? this.#intervalMs : this.#reconcileIntervalMs;\n\n if (this.#pollEventsEnabled) {\n // Only list workspaces when actually tailing events: reconciliation\n // does not need the workspace list, and folding this call into\n // reconcile-only mode would let one workspace-listing outage take\n // down the reconcile sweep as well.\n let workspaces: PlatformLinearWorkspace[] = [];\n try {\n workspaces = await this.#linear.listWorkspaces();\n } catch (error) {\n const delay = retryDelay(error, this.#intervalMs);\n retryInMs = Math.max(retryInMs, delay);\n this.deps?.logger.error('Platform Linear workspace listing failed', {\n error: error instanceof Error ? error.message : String(error),\n retryInMs: delay,\n });\n }\n\n for (const workspace of workspaces) {\n if (!this.#running || !this.#hasLease) break;\n try {\n await this.#pollWorkspace(workspace.linearWorkspaceId);\n } catch (error) {\n const delay = retryDelay(error, this.#intervalMs);\n retryInMs = Math.max(retryInMs, delay);\n this.deps?.logger.error('Platform Linear workspace event polling failed', {\n linearWorkspaceId: workspace.linearWorkspaceId,\n error: error instanceof Error ? error.message : String(error),\n retryInMs: delay,\n });\n if (error instanceof PlatformApiError && error.status === 429) break;\n }\n }\n }\n\n await this.#maybeReconcile();\n\n return retryInMs;\n }\n\n async #maybeReconcile(): Promise<void> {\n if (!this.#reconcileFactoryState || !this.#running || !this.#hasLease) return;\n const now = this.#now();\n if (now - this.#lastReconcileAt < this.#reconcileIntervalMs) return;\n // Advance the clock before sweeping so a persistently failing sweep stays\n // on cadence instead of retrying every poll tick.\n this.#lastReconcileAt = now;\n const startedAt = Date.now();\n try {\n const { errors, ...counts } = await this.#reconcileFactoryState();\n const context = { ...counts, durationMs: Date.now() - startedAt };\n if (counts.failed > 0) {\n this.deps?.logger.warn('Platform Linear issue reconcile sweep completed with failures', {\n ...context,\n errors,\n });\n } else if (counts.updated > 0) {\n this.deps?.logger.info('Platform Linear issue reconcile patched stale metadata', context);\n } else {\n this.deps?.logger.debug('Platform Linear issue reconcile sweep completed', context);\n }\n } catch (error) {\n this.deps?.logger.error('Platform Linear issue reconcile failed', {\n durationMs: Date.now() - startedAt,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n async #pollWorkspace(linearWorkspaceId: string): Promise<void> {\n if (!this.#settings.workspaces[linearWorkspaceId]) {\n this.#settings.workspaces[linearWorkspaceId] = { afterTimestamp: this.#startedAt };\n await this.#saveSettings();\n }\n\n while (this.#running && this.#hasLease) {\n const cursor: EventCursor = this.#settings.workspaces[linearWorkspaceId]!;\n const query = new URLSearchParams({ limit: String(EVENT_PAGE_SIZE), type: 'Issue' });\n if ('afterEventId' in cursor) query.set('afterEventId', cursor.afterEventId);\n else query.set('after', String(cursor.afterTimestamp));\n\n const pollStartedAt = performance.now();\n const page = await this.#client.request<{ events: LinearEventLogEntry[] }>(\n 'GET',\n `${API_PREFIX}/workspaces/${encodeURIComponent(linearWorkspaceId)}/events?${query}`,\n );\n this.deps?.logger.debug('Platform Linear workspace event poll completed', {\n linearWorkspaceId,\n eventCount: page.events.length,\n latencyMs: Math.round(performance.now() - pollStartedAt),\n });\n if (page.events.length === 0) return;\n\n const lastId = page.events[page.events.length - 1]!.id;\n\n // Resolve the project set once per page instead of once per event.\n // The event stream can return up to EVENT_PAGE_SIZE (500) events; the\n // project list rarely changes within the second or two it takes to\n // dispatch a single page, and #dispatchEvent still consults storage\n // per-project to check for a linked work item.\n const projects = await this.#projects.listAll();\n\n for (const event of page.events) {\n if (!this.#running || !this.#hasLease) return;\n await this.#dispatchEvent(linearWorkspaceId, event, projects);\n }\n\n if ('afterEventId' in cursor && cursor.afterEventId === lastId) return;\n this.#settings.workspaces[linearWorkspaceId] = { afterEventId: lastId };\n await this.#saveSettings();\n\n // Short pages mean we've caught up; wait for the next tick.\n if (page.events.length < EVENT_PAGE_SIZE) return;\n }\n }\n\n async #dispatchEvent(\n linearWorkspaceId: string,\n event: LinearEventLogEntry,\n projects: readonly { id: string; orgId: string }[],\n ): Promise<void> {\n if (event.envelope.type !== 'Issue') return;\n if (!this.#ingestFactoryIssue) return;\n const issue = parseIssueEnvelope(event.envelope);\n if (!issue) {\n this.deps?.logger.warn('Platform Linear event log returned an unusable Issue payload', {\n linearWorkspaceId,\n eventId: event.id,\n });\n return;\n }\n\n // The event stream is workspace-scoped and Platform Linear has no\n // workspace→org mapping we can trust. To avoid cross-tenant fan-out (an\n // Issue from org A materializing a triage card in org B via the default\n // `linearIssueObserved` rule), only dispatch to `(orgId, factoryProjectId)`\n // pairs that already have a persisted work item for this Linear issue.\n // First-observation of a Linear issue happens through the\n // user-authenticated `/web/linear/issues?factoryProjectId=...` intake path.\n const sourceKey = `linear:${issue.identifier}`;\n let dispatched = 0;\n for (const project of projects) {\n let items;\n try {\n items = await this.#workItems.list({ orgId: project.orgId, factoryProjectId: project.id });\n } catch (error) {\n this.deps?.logger.error('Platform Linear work-item lookup failed', {\n linearWorkspaceId,\n eventId: event.id,\n projectId: project.id,\n error: error instanceof Error ? error.message : String(error),\n });\n continue;\n }\n const linked = items.some(\n item =>\n item.externalSource?.integrationId === 'linear' &&\n item.externalSource.type === 'issue' &&\n item.externalSource.externalId === sourceKey,\n );\n if (!linked) continue;\n try {\n await this.#ingestFactoryIssue({\n orgId: project.orgId,\n userId: 'platform-linear-event-worker',\n factoryProjectId: project.id,\n issues: [issue],\n });\n dispatched += 1;\n } catch (error) {\n this.deps?.logger.error('Platform Linear issue ingest failed', {\n linearWorkspaceId,\n eventId: event.id,\n projectId: project.id,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n if (dispatched === 0) {\n this.deps?.logger.debug('Platform Linear Issue event had no linked work items to update', {\n linearWorkspaceId,\n eventId: event.id,\n sourceKey,\n });\n }\n }\n\n async #saveSettings(): Promise<void> {\n await this.#storage.settings.save(CURSOR_ORG_ID, CURSOR_USER_ID, this.#settings);\n }\n}\n\nfunction getLeaseProvider(pubsub: PubSub): LeaseProvider {\n const getProvider = (pubsub as PubSub & { getLeaseProvider?: () => LeaseProvider | undefined }).getLeaseProvider;\n if (typeof getProvider === 'function') return getProvider.call(pubsub) ?? NoopLeaseProvider;\n return isLeaseProvider(pubsub) ? pubsub : NoopLeaseProvider;\n}\n\nfunction normalizeSettings(value: PlatformLinearEventWorkerSettings | null): PlatformLinearEventWorkerSettings {\n if (!value || value.version !== 1 || !value.workspaces || typeof value.workspaces !== 'object') {\n return { version: 1, workspaces: {} };\n }\n return { version: 1, workspaces: { ...value.workspaces } };\n}\n\nfunction retryDelay(error: unknown, fallbackMs: number): number {\n if (error instanceof PlatformApiError && error.status === 429 && error.retryAfterSeconds !== null) {\n return Math.max(fallbackMs, error.retryAfterSeconds * 1_000);\n }\n return fallbackMs;\n}\n\n/**\n * Translate an Issue webhook envelope into the rules-ingress shape.\n * Returns undefined when the payload lacks the identifiers we need to\n * match a work item.\n */\nfunction parseIssueEnvelope(envelope: LinearWebhookEnvelope): LinearIssueIngress | undefined {\n const data = envelope.data;\n if (!data || typeof data !== 'object' || Array.isArray(data)) return undefined;\n const raw = data as Record<string, unknown>;\n const id = typeof raw.id === 'string' ? raw.id : undefined;\n const identifier = typeof raw.identifier === 'string' ? raw.identifier : undefined;\n const title = typeof raw.title === 'string' ? raw.title : undefined;\n const url = typeof raw.url === 'string' ? raw.url : (envelope.url ?? undefined);\n if (!id || !identifier || !title || !url) return undefined;\n\n const state = optionalObject(raw.state);\n const team = optionalObject(raw.team);\n const assignee = optionalObject(raw.assignee);\n const creator = optionalObject(raw.user) ?? optionalObject(raw.creator);\n const labels = Array.isArray(raw.labels)\n ? raw.labels.flatMap(label => {\n const obj = optionalObject(label);\n return obj && typeof obj.name === 'string' ? [obj.name] : [];\n })\n : [];\n\n const createdAt = typeof raw.createdAt === 'string' ? raw.createdAt : (envelope.createdAt ?? '');\n const updatedAt = typeof raw.updatedAt === 'string' ? raw.updatedAt : createdAt;\n\n return {\n id,\n identifier,\n title,\n url,\n state: (state && typeof state.name === 'string' ? state.name : null) ?? '',\n stateType: (state && typeof state.type === 'string' ? state.type : null) ?? '',\n priorityLabel: typeof raw.priorityLabel === 'string' ? raw.priorityLabel : '',\n assignee: assignee && typeof assignee.name === 'string' ? assignee.name : null,\n creator: creator && typeof creator.name === 'string' ? creator.name : null,\n team: team && typeof team.name === 'string' ? team.name : null,\n labels,\n createdAt,\n updatedAt,\n };\n}\n\nfunction optionalObject(value: unknown): Record<string, unknown> | undefined {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined;\n return value as Record<string, unknown>;\n}\n"],"mappings":";;;;;AAcA,MAAM,aAAa;AACnB,MAAM,2BAA2B;AACjC,MAAM,gCAAgC,IAAI;AAC1C,MAAM,kBAAkB;AACxB,MAAM,mBAAmB;AACzB,MAAM,gBAAgB;AACtB,MAAM,iBAAiB;AACvB,MAAM,YAAY;;;;;;;;;;;;;;;;;;;;;;;;AA+FlB,IAAa,4BAAb,cAA+C,aAAa;CAC1D,OAAgB;CAEhB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA,cAAuB,WAAW;CAElC,WAAW;CACX;CACA;CACA;CACA,iBAAgC;CAChC;CACA,YAAY;CACZ,aAAa;CACb,mBAAmB;CACnB,YAA+C;EAAE,SAAS;EAAG,YAAY,CAAC;CAAE;CAE5E,YAAY,QAAyC;EACnD,MAAM;EACN,KAAKA,UAAU,OAAO;EACtB,KAAKC,UAAU,OAAO;EACtB,KAAKC,WAAW,OAAO;EACvB,KAAKC,YAAY,OAAO;EACxB,KAAKC,aAAa,OAAO;EACzB,KAAKC,sBAAsB,OAAO;EAClC,KAAKC,yBAAyB,OAAO;EACrC,KAAKC,qBAAqB,OAAO,qBAAqB;EACtD,KAAKC,cAAc,OAAO,cAAc;EACxC,KAAKC,uBAAuB,OAAO,uBAAuB;EAC1D,IAAI,CAAC,OAAO,SAAS,KAAKD,WAAW,KAAK,KAAKA,eAAe,GAC5D,MAAM,IAAI,MAAM,mEAAmE;EAErF,IAAI,CAAC,OAAO,SAAS,KAAKC,oBAAoB,KAAK,KAAKA,wBAAwB,GAC9E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AO,KAAA;CACrE,IAAI,CAAC,MAAM,CAAC,cAAc,CAAC,SAAS,CAAC,KAAK,OAAO,KAAA;CAEjD,MAAM,QAAQ,eAAe,IAAI,KAAK;CACtC,MAAM,OAAO,eAAe,IAAI,IAAI;CACpC,MAAM,WAAW,eAAe,IAAI,QAAQ;CAC5C,MAAM,UAAU,eAAe,IAAI,IAAI,KAAK,eAAe,IAAI,OAAO;CACtE,MAAM,SAAS,MAAM,QAAQ,IAAI,MAAM,IACnC,IAAI,OAAO,SAAQ,UAAS;EAC1B,MAAM,MAAM,eAAe,KAAK;EAChC,OAAO,OAAO,OAAO,IAAI,SAAS,WAAW,CAAC,IAAI,IAAI,IAAI,CAAC;CAC7D,CAAC,IACD,CAAC;CAEL,MAAM,YAAY,OAAO,IAAI,cAAc,WAAW,IAAI,YAAa,SAAS,aAAa;CAC7F,MAAM,YAAY,OAAO,IAAI,cAAc,WAAW,IAAI,YAAY;CAEtE,OAAO;EACL;EACA;EACA;EACA;EACA,QAAQ,SAAS,OAAO,MAAM,SAAS,WAAW,MAAM,OAAO,SAAS;EACxE,YAAY,SAAS,OAAO,MAAM,SAAS,WAAW,MAAM,OAAO,SAAS;EAC5E,eAAe,OAAO,IAAI,kBAAkB,WAAW,IAAI,gBAAgB;EAC3E,UAAU,YAAY,OAAO,SAAS,SAAS,WAAW,SAAS,OAAO;EAC1E,SAAS,WAAW,OAAO,QAAQ,SAAS,WAAW,QAAQ,OAAO;EACtE,MAAM,QAAQ,OAAO,KAAK,SAAS,WAAW,KAAK,OAAO;EAC1D;EACA;EACA;CACF;AACF;AAEA,SAAS,eAAe,OAAqD;CAC3E,IAAI,CAAC,SAAS,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,GAAG,OAAO,KAAA;CACxE,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"event-worker.js","names":["#client","#linear","#storage","#projects","#workItems","#ingestFactoryIssue","#reconcileFactoryState","#pollEventsEnabled","#intervalMs","#reconcileIntervalMs","#now","#leaseOwner","#leaseTtlMs","#leaseProvider","#running","#startedAt","#settings","#schedule","#timer","#stopLeaseRenewal","#inFlight","#hasLease","#tick","#ensureLease","#poll","#startLeaseRenewal","#leaseRenewalTimer","#pollWorkspace","#maybeReconcile","#lastReconcileAt","#saveSettings","#dispatchEvent"],"sources":["../../../../src/integrations/platform/linear/event-worker.ts"],"sourcesContent":["import { isLeaseProvider, NoopLeaseProvider } from '@mastra/core/events';\nimport type { LeaseProvider, PubSub } from '@mastra/core/events';\nimport { MastraWorker } from '@mastra/core/worker';\nimport type { WorkerDeps } from '@mastra/core/worker';\n\nimport type { IntegrationStorageHandle } from '../../../storage/domains/integrations/base.js';\nimport type { FactoryProjectsStorage } from '../../../storage/domains/projects/base.js';\nimport type { WorkItemsStorage } from '../../../storage/domains/work-items/base.js';\nimport type { IssueReconciler } from '../../issue-reconciler.js';\nimport type { LinearIssueIngress, LinearRulesIngress } from '../../linear/rules.js';\nimport { PlatformApiClient, PlatformApiError } from '../api-client.js';\n\nconst API_PREFIX = '/v1/server/linear';\nconst DEFAULT_POLL_INTERVAL_MS = 20_000;\nconst DEFAULT_RECONCILE_INTERVAL_MS = 5 * 60_000;\nconst EVENT_PAGE_SIZE = 500;\nconst MIN_LEASE_TTL_MS = 30_000;\nconst CURSOR_ORG_ID = '__platform_linear_event_worker__';\nconst CURSOR_USER_ID = 'worker';\nconst LEASE_KEY = 'platform-linear-events:linear';\n\ntype EventCursor = { afterEventId: string } | { afterTimestamp: number };\ntype PlatformLinearEventWorkerSettings = {\n version: 1;\n workspaces: Record<string, EventCursor>;\n};\n\nexport type PlatformLinearEventStorage = IntegrationStorageHandle<\n Record<string, unknown>,\n PlatformLinearEventWorkerSettings,\n Record<string, unknown>\n>;\n\n/**\n * Minimal envelope shape mirrored from `@platform/linear`. Kept opaque\n * (`data: unknown`) — every consumer demuxes by `type`.\n */\nexport interface LinearWebhookEnvelope {\n type: string;\n action: string | null;\n createdAt: string | null;\n webhookTimestamp: number | null;\n linearOrganizationId: string | null;\n oauthClientId: string | null;\n url: string | null;\n data: unknown;\n}\n\nexport interface LinearEventLogEntry {\n id: string;\n timestamp: number;\n envelope: LinearWebhookEnvelope;\n}\n\nexport interface PlatformLinearWorkspace {\n linearWorkspaceId: string;\n linearWorkspaceName?: string;\n}\n\n/**\n * Everything the worker needs to drive ingest + reconciliation without\n * pulling in the full `PlatformLinearIntegration` type (circular).\n */\nexport interface PlatformLinearEventDispatchIntegration {\n listWorkspaces(): Promise<PlatformLinearWorkspace[]>;\n}\n\nexport interface PlatformLinearEventWorkerConfig {\n client: PlatformApiClient;\n linear: PlatformLinearEventDispatchIntegration;\n storage: PlatformLinearEventStorage;\n projects: Pick<FactoryProjectsStorage, 'listAll'>;\n /**\n * Used to scope event dispatch to `(orgId, factoryProjectId)` pairs that\n * already have a work item linked to the incoming Linear issue. Without\n * this scoping, a workspace-scoped event would fan out to every project in\n * every org and materialize a triage card in each — a cross-tenant leak.\n * First-observation of a Linear issue happens through the user-authenticated\n * `/web/linear/issues?factoryProjectId=...` intake path instead.\n */\n workItems: Pick<WorkItemsStorage, 'list'>;\n /** Called with a single-issue rules ingress derived from an `Issue` webhook. */\n ingestFactoryIssue?: (input: LinearRulesIngress) => Promise<unknown>;\n reconcileFactoryState?: IssueReconciler;\n /** When false the worker skips event tailing and only runs the reconcile sweep. */\n pollEventsEnabled?: boolean;\n intervalMs?: number;\n reconcileIntervalMs?: number;\n now?: () => number;\n}\n\n/**\n * Tails the Platform Linear event stream (Redis-backed, per workspace) and\n * runs the same folded issue-reconcile sweep pattern as\n * `PlatformGithubEventWorker`. Issue events are translated into a normal\n * `LinearRulesIngress` so downstream rule dispatch is identical to the\n * polling path.\n *\n * Cursor state is persisted per workspace via the integration's generic\n * settings surface, keyed by a well-known worker identity. Cold start uses\n * `afterTimestamp: now - 1` to avoid replaying the 14-day stream backlog.\n *\n * ## Delivery semantics\n *\n * **At-most-once** per event. The cursor advances to the last event ID in a\n * page after all dispatch attempts on that page complete, regardless of\n * whether individual ingest calls threw. Ingest failures are logged, the\n * offending event is not retried, and drift is caught by the folded\n * `LinearIssueReconciler` sweep on its own cadence (default 5 minutes). This\n * matches `PlatformGithubEventWorker` and avoids poison-pill events blocking\n * the whole stream. Any consumer that needs exactly-once must idempotently\n * handle the same issue arriving via both the event path and the reconcile\n * path.\n */\nexport class PlatformLinearEventWorker extends MastraWorker {\n readonly name = 'platform-linear-events';\n\n readonly #client: PlatformApiClient;\n readonly #linear: PlatformLinearEventDispatchIntegration;\n readonly #storage: PlatformLinearEventStorage;\n readonly #projects: Pick<FactoryProjectsStorage, 'listAll'>;\n readonly #workItems: Pick<WorkItemsStorage, 'list'>;\n readonly #ingestFactoryIssue: ((input: LinearRulesIngress) => Promise<unknown>) | undefined;\n readonly #reconcileFactoryState: IssueReconciler | undefined;\n readonly #pollEventsEnabled: boolean;\n readonly #intervalMs: number;\n readonly #reconcileIntervalMs: number;\n readonly #now: () => number;\n readonly #leaseOwner = globalThis.crypto.randomUUID();\n\n #running = false;\n #timer: ReturnType<typeof setTimeout> | undefined;\n #leaseRenewalTimer: ReturnType<typeof setInterval> | undefined;\n #inFlight: Promise<void> | undefined;\n #leaseProvider: LeaseProvider = NoopLeaseProvider;\n #leaseTtlMs: number;\n #hasLease = false;\n #startedAt = 0;\n #lastReconcileAt = 0;\n #settings: PlatformLinearEventWorkerSettings = { version: 1, workspaces: {} };\n\n constructor(config: PlatformLinearEventWorkerConfig) {\n super();\n this.#client = config.client;\n this.#linear = config.linear;\n this.#storage = config.storage;\n this.#projects = config.projects;\n this.#workItems = config.workItems;\n this.#ingestFactoryIssue = config.ingestFactoryIssue;\n this.#reconcileFactoryState = config.reconcileFactoryState;\n this.#pollEventsEnabled = config.pollEventsEnabled ?? true;\n this.#intervalMs = config.intervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n this.#reconcileIntervalMs = config.reconcileIntervalMs ?? DEFAULT_RECONCILE_INTERVAL_MS;\n if (!Number.isFinite(this.#intervalMs) || this.#intervalMs <= 0) {\n throw new Error('Platform Linear event polling interval must be a positive number.');\n }\n if (!Number.isFinite(this.#reconcileIntervalMs) || this.#reconcileIntervalMs <= 0) {\n throw new Error('Platform Linear reconcile interval must be a positive number.');\n }\n this.#leaseTtlMs = Math.max(MIN_LEASE_TTL_MS, this.#intervalMs * 3);\n this.#now = config.now ?? Date.now;\n }\n\n async init(deps: WorkerDeps): Promise<void> {\n await super.init(deps);\n this.#leaseProvider = getLeaseProvider(deps.pubsub);\n }\n\n async start(): Promise<void> {\n if (this.#running) return;\n if (!this.deps) throw new Error('PlatformLinearEventWorker: call init() before start()');\n\n this.#startedAt = this.#now() - 1;\n this.#settings = normalizeSettings(await this.#storage.settings.get(CURSOR_ORG_ID, CURSOR_USER_ID));\n this.#running = true;\n this.deps.logger.info('Platform Linear event polling started', {\n intervalMs: this.#intervalMs,\n leaseTtlMs: this.#leaseTtlMs,\n });\n this.#schedule(0);\n }\n\n async stop(): Promise<void> {\n if (!this.#running) return;\n this.#running = false;\n if (this.#timer) clearTimeout(this.#timer);\n this.#timer = undefined;\n this.#stopLeaseRenewal();\n await this.#inFlight;\n if (this.#hasLease) {\n await this.#leaseProvider.releaseLease(LEASE_KEY, this.#leaseOwner).catch(() => undefined);\n this.#hasLease = false;\n }\n }\n\n get isRunning(): boolean {\n return this.#running;\n }\n\n #schedule(delayMs: number): void {\n if (!this.#running) return;\n this.#timer = setTimeout(() => {\n this.#timer = undefined;\n const run = this.#tick();\n this.#inFlight = run;\n void run.finally(() => {\n if (this.#inFlight === run) this.#inFlight = undefined;\n });\n }, delayMs);\n this.#timer.unref?.();\n }\n\n async #tick(): Promise<void> {\n let nextDelay = this.#intervalMs;\n try {\n if (!(await this.#ensureLease())) return;\n nextDelay = await this.#poll();\n } catch (error) {\n nextDelay = retryDelay(error, this.#intervalMs);\n this.deps?.logger.error('Platform Linear event polling cycle failed', {\n error: error instanceof Error ? error.message : String(error),\n retryInMs: nextDelay,\n });\n } finally {\n this.#schedule(nextDelay);\n }\n }\n\n async #ensureLease(): Promise<boolean> {\n if (this.#hasLease) return true;\n const result = await this.#leaseProvider.acquireLease(LEASE_KEY, this.#leaseOwner, this.#leaseTtlMs);\n this.#hasLease = result.acquired;\n if (this.#hasLease) this.#startLeaseRenewal();\n return this.#hasLease;\n }\n\n #startLeaseRenewal(): void {\n if (this.#leaseRenewalTimer) return;\n this.#leaseRenewalTimer = setInterval(\n () => {\n void this.#leaseProvider\n .renewLease(LEASE_KEY, this.#leaseOwner, this.#leaseTtlMs)\n .then(renewed => {\n if (!renewed) {\n this.#hasLease = false;\n this.#stopLeaseRenewal();\n }\n })\n .catch(error => {\n this.#hasLease = false;\n this.#stopLeaseRenewal();\n this.deps?.logger.warn('Platform Linear event polling lease renewal failed', {\n error: error instanceof Error ? error.message : String(error),\n });\n });\n },\n Math.floor(this.#leaseTtlMs / 3),\n );\n this.#leaseRenewalTimer.unref?.();\n }\n\n #stopLeaseRenewal(): void {\n if (this.#leaseRenewalTimer) clearInterval(this.#leaseRenewalTimer);\n this.#leaseRenewalTimer = undefined;\n }\n\n async #poll(): Promise<number> {\n // Reconcile-only mode has no event tail to keep fresh, so tick on the\n // slower reconcile cadence instead of the polling interval.\n let retryInMs = this.#pollEventsEnabled ? this.#intervalMs : this.#reconcileIntervalMs;\n\n if (this.#pollEventsEnabled) {\n // Only list workspaces when actually tailing events: reconciliation\n // does not need the workspace list, and folding this call into\n // reconcile-only mode would let one workspace-listing outage take\n // down the reconcile sweep as well.\n let workspaces: PlatformLinearWorkspace[] = [];\n try {\n workspaces = await this.#linear.listWorkspaces();\n } catch (error) {\n const delay = retryDelay(error, this.#intervalMs);\n retryInMs = Math.max(retryInMs, delay);\n this.deps?.logger.error('Platform Linear workspace listing failed', {\n error: error instanceof Error ? error.message : String(error),\n retryInMs: delay,\n });\n }\n\n for (const workspace of workspaces) {\n if (!this.#running || !this.#hasLease) break;\n try {\n await this.#pollWorkspace(workspace.linearWorkspaceId);\n } catch (error) {\n const delay = retryDelay(error, this.#intervalMs);\n retryInMs = Math.max(retryInMs, delay);\n this.deps?.logger.error('Platform Linear workspace event polling failed', {\n linearWorkspaceId: workspace.linearWorkspaceId,\n error: error instanceof Error ? error.message : String(error),\n retryInMs: delay,\n });\n if (error instanceof PlatformApiError && error.status === 429) break;\n }\n }\n }\n\n await this.#maybeReconcile();\n\n return retryInMs;\n }\n\n async #maybeReconcile(): Promise<void> {\n if (!this.#reconcileFactoryState || !this.#running || !this.#hasLease) return;\n const now = this.#now();\n if (now - this.#lastReconcileAt < this.#reconcileIntervalMs) return;\n // Advance the clock before sweeping so a persistently failing sweep stays\n // on cadence instead of retrying every poll tick.\n this.#lastReconcileAt = now;\n const startedAt = Date.now();\n try {\n const { errors, ...counts } = await this.#reconcileFactoryState();\n const context = { ...counts, durationMs: Date.now() - startedAt };\n if (counts.failed > 0) {\n this.deps?.logger.warn('Platform Linear issue reconcile sweep completed with failures', {\n ...context,\n errors,\n });\n } else if (counts.updated > 0) {\n this.deps?.logger.info('Platform Linear issue reconcile patched stale metadata', context);\n } else {\n this.deps?.logger.debug('Platform Linear issue reconcile sweep completed', context);\n }\n } catch (error) {\n this.deps?.logger.error('Platform Linear issue reconcile failed', {\n durationMs: Date.now() - startedAt,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n async #pollWorkspace(linearWorkspaceId: string): Promise<void> {\n if (!this.#settings.workspaces[linearWorkspaceId]) {\n this.#settings.workspaces[linearWorkspaceId] = { afterTimestamp: this.#startedAt };\n await this.#saveSettings();\n }\n\n while (this.#running && this.#hasLease) {\n const cursor: EventCursor = this.#settings.workspaces[linearWorkspaceId]!;\n const query = new URLSearchParams({ limit: String(EVENT_PAGE_SIZE), type: 'Issue' });\n if ('afterEventId' in cursor) query.set('afterEventId', cursor.afterEventId);\n else query.set('after', String(cursor.afterTimestamp));\n\n const pollStartedAt = performance.now();\n const page = await this.#client.request<{ events: LinearEventLogEntry[] }>(\n 'GET',\n `${API_PREFIX}/workspaces/${encodeURIComponent(linearWorkspaceId)}/events?${query}`,\n );\n this.deps?.logger.debug('Platform Linear workspace event poll completed', {\n linearWorkspaceId,\n eventCount: page.events.length,\n latencyMs: Math.round(performance.now() - pollStartedAt),\n });\n if (page.events.length === 0) return;\n\n const lastId = page.events[page.events.length - 1]!.id;\n\n // Resolve the project set once per page instead of once per event.\n // The event stream can return up to EVENT_PAGE_SIZE (500) events; the\n // project list rarely changes within the second or two it takes to\n // dispatch a single page, and #dispatchEvent still consults storage\n // per-project to check for a linked work item.\n const projects = await this.#projects.listAll();\n\n for (const event of page.events) {\n if (!this.#running || !this.#hasLease) return;\n await this.#dispatchEvent(linearWorkspaceId, event, projects);\n }\n\n if ('afterEventId' in cursor && cursor.afterEventId === lastId) return;\n this.#settings.workspaces[linearWorkspaceId] = { afterEventId: lastId };\n await this.#saveSettings();\n\n // Short pages mean we've caught up; wait for the next tick.\n if (page.events.length < EVENT_PAGE_SIZE) return;\n }\n }\n\n async #dispatchEvent(\n linearWorkspaceId: string,\n event: LinearEventLogEntry,\n projects: readonly { id: string; orgId: string }[],\n ): Promise<void> {\n if (event.envelope.type !== 'Issue') return;\n if (!this.#ingestFactoryIssue) return;\n const issue = parseIssueEnvelope(event.envelope);\n if (!issue) {\n this.deps?.logger.warn('Platform Linear event log returned an unusable Issue payload', {\n linearWorkspaceId,\n eventId: event.id,\n });\n return;\n }\n\n // The event stream is workspace-scoped and Platform Linear has no\n // workspace→org mapping we can trust. To avoid cross-tenant fan-out (an\n // Issue from org A materializing a triage card in org B via the default\n // `linearIssueObserved` rule), only dispatch to `(orgId, factoryProjectId)`\n // pairs that already have a persisted work item for this Linear issue.\n // First-observation of a Linear issue happens through the\n // user-authenticated `/web/linear/issues?factoryProjectId=...` intake path.\n const sourceKey = `linear:${issue.identifier}`;\n let dispatched = 0;\n for (const project of projects) {\n let items;\n try {\n items = await this.#workItems.list({ orgId: project.orgId, factoryProjectId: project.id });\n } catch (error) {\n this.deps?.logger.error('Platform Linear work-item lookup failed', {\n linearWorkspaceId,\n eventId: event.id,\n projectId: project.id,\n error: error instanceof Error ? error.message : String(error),\n });\n continue;\n }\n const linked = items.some(\n item =>\n item.externalSource?.integrationId === 'linear' &&\n item.externalSource.type === 'issue' &&\n item.externalSource.externalId === sourceKey,\n );\n if (!linked) continue;\n try {\n await this.#ingestFactoryIssue({\n orgId: project.orgId,\n userId: 'platform-linear-event-worker',\n factoryProjectId: project.id,\n issues: [issue],\n });\n dispatched += 1;\n } catch (error) {\n this.deps?.logger.error('Platform Linear issue ingest failed', {\n linearWorkspaceId,\n eventId: event.id,\n projectId: project.id,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n if (dispatched === 0) {\n this.deps?.logger.debug('Platform Linear Issue event had no linked work items to update', {\n linearWorkspaceId,\n eventId: event.id,\n sourceKey,\n });\n }\n }\n\n async #saveSettings(): Promise<void> {\n await this.#storage.settings.save(CURSOR_ORG_ID, CURSOR_USER_ID, this.#settings);\n }\n}\n\nfunction getLeaseProvider(pubsub: PubSub): LeaseProvider {\n const getProvider = (pubsub as PubSub & { getLeaseProvider?: () => LeaseProvider | undefined }).getLeaseProvider;\n if (typeof getProvider === 'function') return getProvider.call(pubsub) ?? NoopLeaseProvider;\n return isLeaseProvider(pubsub) ? pubsub : NoopLeaseProvider;\n}\n\nfunction normalizeSettings(value: PlatformLinearEventWorkerSettings | null): PlatformLinearEventWorkerSettings {\n if (!value || value.version !== 1 || !value.workspaces || typeof value.workspaces !== 'object') {\n return { version: 1, workspaces: {} };\n }\n return { version: 1, workspaces: { ...value.workspaces } };\n}\n\nfunction retryDelay(error: unknown, fallbackMs: number): number {\n if (error instanceof PlatformApiError && error.status === 429 && error.retryAfterSeconds !== null) {\n return Math.max(fallbackMs, error.retryAfterSeconds * 1_000);\n }\n return fallbackMs;\n}\n\n/**\n * Translate an Issue webhook envelope into the rules-ingress shape.\n * Returns undefined when the payload lacks the identifiers we need to\n * match a work item.\n */\nfunction parseIssueEnvelope(envelope: LinearWebhookEnvelope): LinearIssueIngress | undefined {\n const data = envelope.data;\n if (!data || typeof data !== 'object' || Array.isArray(data)) return undefined;\n const raw = data as Record<string, unknown>;\n const id = typeof raw.id === 'string' ? raw.id : undefined;\n const identifier = typeof raw.identifier === 'string' ? raw.identifier : undefined;\n const title = typeof raw.title === 'string' ? raw.title : undefined;\n const url = typeof raw.url === 'string' ? raw.url : (envelope.url ?? undefined);\n if (!id || !identifier || !title || !url) return undefined;\n\n const state = optionalObject(raw.state);\n const team = optionalObject(raw.team);\n const assignee = optionalObject(raw.assignee);\n const creator = optionalObject(raw.user) ?? optionalObject(raw.creator);\n const labels = Array.isArray(raw.labels)\n ? raw.labels.flatMap(label => {\n const obj = optionalObject(label);\n return obj && typeof obj.name === 'string' ? [obj.name] : [];\n })\n : [];\n\n const createdAt = typeof raw.createdAt === 'string' ? raw.createdAt : (envelope.createdAt ?? '');\n const updatedAt = typeof raw.updatedAt === 'string' ? raw.updatedAt : createdAt;\n\n return {\n id,\n identifier,\n title,\n url,\n state: (state && typeof state.name === 'string' ? state.name : null) ?? '',\n stateType: (state && typeof state.type === 'string' ? state.type : null) ?? '',\n priorityLabel: typeof raw.priorityLabel === 'string' ? raw.priorityLabel : '',\n assignee: assignee && typeof assignee.name === 'string' ? assignee.name : null,\n creator: creator && typeof creator.name === 'string' ? creator.name : null,\n team: team && typeof team.name === 'string' ? team.name : null,\n labels,\n createdAt,\n updatedAt,\n };\n}\n\nfunction optionalObject(value: unknown): Record<string, unknown> | undefined {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined;\n return value as Record<string, unknown>;\n}\n"],"mappings":";;;;AAYA,MAAM,aAAa;AACnB,MAAM,2BAA2B;AACjC,MAAM,gCAAgC,IAAI;AAC1C,MAAM,kBAAkB;AACxB,MAAM,mBAAmB;AACzB,MAAM,gBAAgB;AACtB,MAAM,iBAAiB;AACvB,MAAM,YAAY;;;;;;;;;;;;;;;;;;;;;;;;AA+FlB,IAAa,4BAAb,cAA+C,aAAa;CAC1D,OAAgB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C7F,MAAM,YAAY,OAAO,IAAI,cAAc,WAAW,IAAI,YAAY;CAEtE,OAAO;EACL;EACA;EACA;EACA;EACA,QAAQ,SAAS,OAAO,MAAM,SAAS,WAAW,MAAM,OAAO,SAAS;EACxE,YAAY,SAAS,OAAO,MAAM,SAAS,WAAW,MAAM,OAAO,SAAS;EAC5E,eAAe,OAAO,IAAI,kBAAkB,WAAW,IAAI,gBAAgB;EAC3E,UAAU,YAAY,OAAO,SAAS,SAAS,WAAW,SAAS,OAAO;EAC1E,SAAS,WAAW,OAAO,QAAQ,SAAS,WAAW,QAAQ,OAAO;EACtE,MAAM,QAAQ,OAAO,KAAK,SAAS,WAAW,KAAK,OAAO;EAC1D;EACA;EACA;CACF;AACF;AAEA,SAAS,eAAe,OAAqD;CAC3E,IAAI,CAAC,SAAS,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,GAAG,OAAO,KAAA;CACxE,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"integration.d.ts","sourceRoot":"","sources":["../../../../src/integrations/platform/linear/integration.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"integration.d.ts","sourceRoot":"","sources":["../../../../src/integrations/platform/linear/integration.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAEpD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAIxD,OAAO,KAAK,EAAE,MAAM,EAA0D,MAAM,iCAAiC,CAAC;AACtH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AAC1D,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,2CAA2C,CAAC;AACxF,OAAO,KAAK,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAE9F,OAAO,KA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AAW,GAAG,QAAQ,CAAC,GAC1E,OAAO;IA8DJ,cAAc,IAAI,OAAO,CAAC,eAAe,EAAE,CAAC;CA2NnD;AAiFD,wBAAgB,cAAc,CAAC,WAAW,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,MAAM,CAE7E;AAmBD,wBAAgB,kBAAkB,CAAC,WAAW,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CAE9E;AAED,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,MAAM,GAAG;IAAE,WAAW,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAa5F;AAED;;;;GAIG;AACH,MAAM,MAAM,aAAa,GACvB;IAAE,IAAI,EAAE,SAAS,CAAC;IAAC,WAAW,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AAEtH,qEAAqE;AACrE,wBAAgB,aAAa,CAAC,QAAQ,EAAE,MAAM,GAAG,aAAa,CAK7D"}
|
|
@@ -7,7 +7,6 @@ import { buildLinearRoutes } from "../../linear/routes.js";
|
|
|
7
7
|
import { buildLinearAgentTools } from "../../linear/agent-tools.js";
|
|
8
8
|
import { PlatformLinearEventWorker } from "./event-worker.js";
|
|
9
9
|
import { registerApiRoute } from "@mastra/core/server";
|
|
10
|
-
import { createHash } from "crypto";
|
|
11
10
|
//#region src/integrations/platform/linear/integration.ts
|
|
12
11
|
const API_PREFIX = "/v1/server/linear";
|
|
13
12
|
const PAGE_SIZE = 30;
|
|
@@ -493,7 +492,7 @@ var PlatformLinearIntegration = class {
|
|
|
493
492
|
});
|
|
494
493
|
}
|
|
495
494
|
}
|
|
496
|
-
const cursors = decodeCursor(cursor, sourceIds, attributionSourceIds);
|
|
495
|
+
const cursors = await decodeCursor(cursor, sourceIds, attributionSourceIds);
|
|
497
496
|
const normalizedLabels = normalizeLabels(labels);
|
|
498
497
|
const nextState = {};
|
|
499
498
|
let hasNextPage = false;
|
|
@@ -516,7 +515,7 @@ var PlatformLinearIntegration = class {
|
|
|
516
515
|
workspace
|
|
517
516
|
}));
|
|
518
517
|
}))).flat(), sourceIds),
|
|
519
|
-
nextCursor: hasNextPage ? encodeCursor(nextState, sourceIds, attributionSourceIds) : null
|
|
518
|
+
nextCursor: hasNextPage ? await encodeCursor(nextState, sourceIds, attributionSourceIds) : null
|
|
520
519
|
};
|
|
521
520
|
}
|
|
522
521
|
async #findIssue(sourceId, issueId, sourceIds, routedSourceIds) {
|
|
@@ -704,32 +703,33 @@ function normalizeLabels(labels) {
|
|
|
704
703
|
function canonicalSourceIds(sourceIds) {
|
|
705
704
|
return [...new Set(sourceIds)].sort();
|
|
706
705
|
}
|
|
707
|
-
function linearSourceSetFingerprint(sourceIds, attributionSourceIds) {
|
|
706
|
+
async function linearSourceSetFingerprint(sourceIds, attributionSourceIds) {
|
|
708
707
|
const scope = {
|
|
709
708
|
sourceIds: canonicalSourceIds(sourceIds),
|
|
710
709
|
attributionSourceIds: canonicalSourceIds(attributionSourceIds)
|
|
711
710
|
};
|
|
712
|
-
|
|
711
|
+
const bytes = new TextEncoder().encode(JSON.stringify(scope));
|
|
712
|
+
return Buffer.from(await globalThis.crypto.subtle.digest("SHA-256", bytes)).toString("base64url");
|
|
713
713
|
}
|
|
714
714
|
function invalidLinearCursor() {
|
|
715
715
|
return Object.assign(/* @__PURE__ */ new Error("Linear cursor is invalid or stale."), { code: "invalid_cursor" });
|
|
716
716
|
}
|
|
717
|
-
function decodeCursor(cursor, sourceIds, attributionSourceIds) {
|
|
717
|
+
async function decodeCursor(cursor, sourceIds, attributionSourceIds) {
|
|
718
718
|
if (!cursor) return {};
|
|
719
719
|
try {
|
|
720
720
|
const parsed = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
|
|
721
721
|
const canonical = canonicalSourceIds(sourceIds);
|
|
722
|
-
if (parsed.v !== 1 || parsed.sourceSet !== linearSourceSetFingerprint(sourceIds, attributionSourceIds) || !Array.isArray(parsed.cursors) || parsed.cursors.length !== canonical.length || !parsed.cursors.every((value) => value === null || typeof value === "string")) throw invalidLinearCursor();
|
|
722
|
+
if (parsed.v !== 1 || parsed.sourceSet !== await linearSourceSetFingerprint(sourceIds, attributionSourceIds) || !Array.isArray(parsed.cursors) || parsed.cursors.length !== canonical.length || !parsed.cursors.every((value) => value === null || typeof value === "string")) throw invalidLinearCursor();
|
|
723
723
|
return Object.fromEntries(canonical.map((sourceId, index) => [sourceId, parsed.cursors[index]]));
|
|
724
724
|
} catch {
|
|
725
725
|
throw invalidLinearCursor();
|
|
726
726
|
}
|
|
727
727
|
}
|
|
728
|
-
function encodeCursor(state, sourceIds, attributionSourceIds) {
|
|
728
|
+
async function encodeCursor(state, sourceIds, attributionSourceIds) {
|
|
729
729
|
const canonical = canonicalSourceIds(sourceIds);
|
|
730
730
|
const cursor = {
|
|
731
731
|
v: 1,
|
|
732
|
-
sourceSet: linearSourceSetFingerprint(sourceIds, attributionSourceIds),
|
|
732
|
+
sourceSet: await linearSourceSetFingerprint(sourceIds, attributionSourceIds),
|
|
733
733
|
cursors: canonical.map((sourceId) => state[sourceId] ?? null)
|
|
734
734
|
};
|
|
735
735
|
return Buffer.from(JSON.stringify(cursor)).toString("base64url");
|