π¨ The ultimate agentic social media scheduling tool π€
TypeScript nextjsopen-sourceopen-source-social-media-scheduling-toolosspostiz-cloudpostiz-hostedredisscheduling-toolsocial-media-scheduling-tooltypescript
feat: workflow changes
Nevo David1f5f24e5fd55
diff --git a/apps/backend/src/services/auth/auth.service.ts b/apps/backend/src/services/auth/auth.service.tsindex eceac92ef..31e2c528c 100644--- a/apps/backend/src/services/auth/auth.service.ts+++ b/apps/backend/src/services/auth/auth.service.ts@@ -7,7 +7,6 @@ import { OrganizationService } from '@gitroom/nestjs-libraries/database/prisma/oimport { AuthService as AuthChecker } from '@gitroom/helpers/auth/auth.service';import { AuthProviderManager } from '@gitroom/backend/services/auth/providers/providers.manager';import dayjs from 'dayjs';-import { NotificationService } from '@gitroom/nestjs-libraries/database/prisma/notifications/notification.service';import { ForgotReturnPasswordDto } from '@gitroom/nestjs-libraries/dtos/auth/forgot-return.password.dto';import { EmailService } from '@gitroom/nestjs-libraries/services/email.service';import { NewsletterService } from '@gitroom/nestjs-libraries/newsletter/newsletter.service';@@ -17,7 +16,6 @@ export class AuthService {constructor(private _userService: UsersService,private _organizationService: OrganizationService,- private _notificationService: NotificationService,private _emailService: EmailService,private _providerManager: AuthProviderManager) {}@@ -73,11 +71,10 @@ export class AuthService {: false;const obj = { addedOrg, jwt: await this.jwt(create.users[0].user) };- await this._emailService.sendEmail(+ await this._emailService.sendEmailSync(body.email,'Activate your account',- `Click <a href="${process.env.FRONTEND_URL}/auth/activate/${obj.jwt}">here</a> to activate your account`,- 'top'+ `Click <a href="${process.env.FRONTEND_URL}/auth/activate/${obj.jwt}">here</a> to activate your account`);return obj;}@@ -225,7 +222,7 @@ export class AuthService {expires: dayjs().add(20, 'minutes').format('YYYY-MM-DD HH:mm:ss'),});- await this._notificationService.sendEmail(+ await this._emailService.sendEmailSync(user.email,'Reset your password',`You have requested to reset your passsord. <br />Click <a href="${process.env.FRONTEND_URL}/auth/forgot/${resetValues}">here</a> to reset your password<br />The link will expire in 20 minutes`@@ -278,11 +275,10 @@ export class AuthService {const jwt = await this.jwt(user);- await this._emailService.sendEmail(+ await this._emailService.sendEmailSync(user.email,'Activate your account',- `Click <a href="${process.env.FRONTEND_URL}/auth/activate/${jwt}">here</a> to activate your account`,- 'top'+ `Click <a href="${process.env.FRONTEND_URL}/auth/activate/${jwt}">here</a> to activate your account`);return true;diff --git a/apps/orchestrator/src/workflows/send.email.workflow.ts b/apps/orchestrator/src/workflows/send.email.workflow.tsindex fc1038880..82c706293 100644--- a/apps/orchestrator/src/workflows/send.email.workflow.ts+++ b/apps/orchestrator/src/workflows/send.email.workflow.ts@@ -10,6 +10,7 @@ import {SendEmail,sendEmailSignal,} from '@gitroom/orchestrator/signals/send.email.signal';+import { emailQueues } from '@gitroom/nestjs-libraries/temporal/email.queues';const { sendEmail } = proxyActivities<EmailActivity>({startToCloseTimeout: '10 minute',@@ -17,8 +18,27 @@ const { sendEmail } = proxyActivities<EmailActivity>({cancellationType: 'ABANDON',});+const { sendEmail: sendPriorityEmail } = proxyActivities<EmailActivity>({+ startToCloseTimeout: '10 minute',+ taskQueue: emailQueues.priority.taskQueue,+ cancellationType: 'ABANDON',+});++const { sendEmail: sendBulkEmail } = proxyActivities<EmailActivity>({+ startToCloseTimeout: '10 minute',+ taskQueue: emailQueues.bulk.taskQueue,+ cancellationType: 'ABANDON',+});++// One workflow per email, the Resend rate limit is enforced on the email task queues+export async function sendSingleEmailWorkflow(email: SendEmail) {+ const send = email.addTo === 'top' ? sendPriorityEmail : sendBulkEmail;+ await send(email.to, email.subject, email.html, email.replyTo);+}+const RATE_LIMIT_MS = 700;+// Deprecated: no longer started, kept registered so the running `send_email` can drain its queueexport async function sendEmailWorkflow({queue = [],}: {diff --git a/libraries/nestjs-libraries/src/emails/resend.provider.ts b/libraries/nestjs-libraries/src/emails/resend.provider.tsindex c0519b0f1..6aa9bd467 100644--- a/libraries/nestjs-libraries/src/emails/resend.provider.ts+++ b/libraries/nestjs-libraries/src/emails/resend.provider.ts@@ -14,20 +14,20 @@ export class ResendProvider implements EmailInterface {emailFromAddress: string,replyTo?: string) {- try {- const sends = await resend.emails.send({- from: `${emailFromName} <${emailFromAddress}>`,- to,- subject,- html,- ...(replyTo && { reply_to: replyTo }),- });+ const sends = await resend.emails.send({+ from: `${emailFromName} <${emailFromAddress}>`,+ to,+ subject,+ html,+ ...(replyTo && { reply_to: replyTo }),+ });- return sends;- } catch (err) {- console.log(err);+ // The SDK returns API errors (like 429 rate limits) instead of throwing,+ // throw so sendEmailSync retries the send+ if (sends.error) {+ throw new Error(`${sends.error.name}: ${sends.error.message}`);}- return { sent: false };+ return sends;}}diff --git a/libraries/nestjs-libraries/src/services/email.service.ts b/libraries/nestjs-libraries/src/services/email.service.tsindex 75157f58d..b2d31f68f 100644--- a/libraries/nestjs-libraries/src/services/email.service.ts+++ b/libraries/nestjs-libraries/src/services/email.service.ts@@ -5,6 +5,7 @@ import { EmptyProvider } from '@gitroom/nestjs-libraries/emails/empty.provider';import { NodeMailerProvider } from '@gitroom/nestjs-libraries/emails/node.mailer.provider';import { TemporalService } from 'nestjs-temporal-core';import { timer } from '@gitroom/helpers/utils/timer';+import { randomUUID } from 'crypto';@Injectable()export class EmailService {@@ -41,15 +42,16 @@ export class EmailService {addTo: 'top' | 'bottom',replyTo?: string) {+ if (!to || !subject) {+ return;+ }+return this._temporalService.client.getRawClient()- ?.workflow.signalWithStart('sendEmailWorkflow', {+ ?.workflow.start('sendSingleEmailWorkflow', {taskQueue: 'main',- workflowId: 'send_email',- signal: 'sendEmail',- args: [{ queue: [] }],- signalArgs: [{ to, subject, html, replyTo, addTo }],- workflowIdConflictPolicy: 'USE_EXISTING',+ workflowId: `send_email_${randomUUID()}`,+ args: [{ to, subject, html, replyTo, addTo }],});}diff --git a/libraries/nestjs-libraries/src/temporal/email.queues.ts b/libraries/nestjs-libraries/src/temporal/email.queues.tsnew file mode 100644index 000000000..18ee1898c--- /dev/null+++ b/libraries/nestjs-libraries/src/temporal/email.queues.ts@@ -0,0 +1,12 @@+// Resend allows 10 requests per second for the whole team (ratelimit-limit+// header). The limits are enforced by the Temporal server across every worker+// polling the queue. The server splits a queue's rate over its 4 partitions,+// so after an idle period a burst can briefly go above the rate. 5/s together+// keeps that burst small, sends rejected by Resend are retried by+// sendEmailSync, and the rest is left for the auth emails sent directly.+export const emailQueues = {+ // Notifications, billing, invites ('top')+ priority: { taskQueue: 'email', perSecond: 3 },+ // Digests and streak emails ('bottom')+ bulk: { taskQueue: 'email-bulk', perSecond: 2 },+};diff --git a/libraries/nestjs-libraries/src/temporal/temporal.module.ts b/libraries/nestjs-libraries/src/temporal/temporal.module.tsindex f188933d3..74a98f35f 100644--- a/libraries/nestjs-libraries/src/temporal/temporal.module.ts+++ b/libraries/nestjs-libraries/src/temporal/temporal.module.ts@@ -1,5 +1,6 @@import { TemporalModule } from 'nestjs-temporal-core';import { socialIntegrationList } from '@gitroom/nestjs-libraries/integrations/integration.manager';+import { emailQueues } from '@gitroom/nestjs-libraries/temporal/email.queues';export const getTemporalModule = (isWorkers: boolean,@@ -38,46 +39,61 @@ export const getTemporalModule = (...(isWorkers? {workers: [- { identifier: 'main', maxConcurrentJob: undefined },- ...socialIntegrationList,- ]- .filter((f) => f.identifier.indexOf('-') === -1)- .map((integration) => ({- integration,- taskQueue: integration.identifier.split('-')[0],- }))- .filter(({ taskQueue }) => !excludeQueues.includes(taskQueue))- .map(({ integration, taskQueue }) => {- // Split the per-provider cap across the servers sharing this- // queue. Floor (never below 1) so the global total never exceeds- // the provider's limit. Providers whose limit is smaller than the- // server count must be pinned via EXCLUDE_QUEUE instead.- const concurrency = integration.maxConcurrentJob- ? Math.max(- 1,- Math.floor(integration.maxConcurrentJob / divider)- )- : undefined;+ ...[+ { identifier: 'main', maxConcurrentJob: undefined },+ ...socialIntegrationList,+ ]+ .filter((f) => f.identifier.indexOf('-') === -1)+ .map((integration) => ({+ integration,+ taskQueue: integration.identifier.split('-')[0],+ }))+ .filter(({ taskQueue }) => !excludeQueues.includes(taskQueue))+ .map(({ integration, taskQueue }) => {+ // Split the per-provider cap across the servers sharing this+ // queue. Floor (never below 1) so the global total never exceeds+ // the provider's limit. Providers whose limit is smaller than the+ // server count must be pinned via EXCLUDE_QUEUE instead.+ const concurrency = integration.maxConcurrentJob+ ? Math.max(+ 1,+ Math.floor(integration.maxConcurrentJob / divider)+ )+ : undefined;- // Workflows only ever run on the `main` queue; the other Workers- // are activity-only, so skip the workflow bundle (webpack build,- // workflow thread + V8 isolate, sticky cache) on them.- return {+ // Workflows only ever run on the `main` queue; the other Workers+ // are activity-only, so skip the workflow bundle (webpack build,+ // workflow thread + V8 isolate, sticky cache) on them.+ return {+ taskQueue,+ ...(taskQueue === 'main' ? { workflowsPath: path! } : {}),+ activityClasses: activityClasses!,+ autoStart: true,+ workerOptions: {+ maxConcurrentActivityTaskExecutions: concurrency || 1000000,+ // By default the SDK throttles heartbeat sends to 60s, so+ // against the workflow's heartbeatTimeout one dropped send+ // or a minute of event-loop lag eats most of the margin.+ // Sending every 15s keeps the recorded heartbeat fresh even+ // when individual sends fail or fire late.+ maxHeartbeatThrottleInterval: '15s',+ },+ };+ }),+ // Activity-only Workers for emails, rate limited server side+ // across all workers to stay under the Resend limit+ ...Object.values(emailQueues)+ .filter(({ taskQueue }) => !excludeQueues.includes(taskQueue))+ .map(({ taskQueue, perSecond }) => ({taskQueue,- ...(taskQueue === 'main' ? { workflowsPath: path! } : {}),activityClasses: activityClasses!,autoStart: true,workerOptions: {- maxConcurrentActivityTaskExecutions: concurrency || 1000000,- // By default the SDK throttles heartbeat sends to 60s, so- // against the workflow's heartbeatTimeout one dropped send- // or a minute of event-loop lag eats most of the margin.- // Sending every 15s keeps the recorded heartbeat fresh even- // when individual sends fail or fire late.- maxHeartbeatThrottleInterval: '15s',+ maxConcurrentActivityTaskExecutions: 10,+ maxTaskQueueActivitiesPerSecond: perSecond,},- };- }),+ })),+ ],}: {}),});