@shivaedev/effect-pg-boss 0.7.1 → 0.8.1

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.
Files changed (51) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README.md +40 -3
  3. package/dist/server/definition.d.ts +2 -1
  4. package/dist/server/definition.d.ts.map +1 -1
  5. package/dist/server/definition.js +3 -0
  6. package/dist/server/definition.js.map +1 -1
  7. package/dist/server/error.d.ts +1 -0
  8. package/dist/server/error.d.ts.map +1 -1
  9. package/dist/server/error.js +12 -0
  10. package/dist/server/error.js.map +1 -1
  11. package/dist/server/internal/batchHandler.d.ts.map +1 -1
  12. package/dist/server/internal/batchHandler.js +15 -2
  13. package/dist/server/internal/batchHandler.js.map +1 -1
  14. package/dist/server/internal/clientCache.d.ts +7 -0
  15. package/dist/server/internal/clientCache.d.ts.map +1 -0
  16. package/dist/server/internal/clientCache.js +51 -0
  17. package/dist/server/internal/clientCache.js.map +1 -0
  18. package/dist/server/internal/clientErrors.d.ts +8 -0
  19. package/dist/server/internal/clientErrors.d.ts.map +1 -0
  20. package/dist/server/internal/clientErrors.js +49 -0
  21. package/dist/server/internal/clientErrors.js.map +1 -0
  22. package/dist/server/internal/deadlineOf.d.ts +3 -0
  23. package/dist/server/internal/deadlineOf.d.ts.map +1 -0
  24. package/dist/server/internal/deadlineOf.js +7 -0
  25. package/dist/server/internal/deadlineOf.js.map +1 -0
  26. package/dist/server/internal/ensureQueue.d.ts.map +1 -1
  27. package/dist/server/internal/ensureQueue.js +19 -2
  28. package/dist/server/internal/ensureQueue.js.map +1 -1
  29. package/dist/server/internal/lifecycle.d.ts +2 -2
  30. package/dist/server/internal/lifecycle.d.ts.map +1 -1
  31. package/dist/server/internal/lifecycle.js +36 -79
  32. package/dist/server/internal/lifecycle.js.map +1 -1
  33. package/dist/server/internal/register.d.ts +2 -2
  34. package/dist/server/internal/register.d.ts.map +1 -1
  35. package/dist/server/internal/register.js +10 -5
  36. package/dist/server/internal/register.js.map +1 -1
  37. package/dist/server/service.d.ts.map +1 -1
  38. package/dist/server/service.js +4 -12
  39. package/dist/server/service.js.map +1 -1
  40. package/docs/roadmap.md +6 -5
  41. package/package.json +6 -5
  42. package/src/server/definition.ts +4 -1
  43. package/src/server/error.ts +15 -1
  44. package/src/server/internal/batchHandler.ts +15 -2
  45. package/src/server/internal/clientCache.ts +61 -0
  46. package/src/server/internal/clientErrors.ts +64 -0
  47. package/src/server/internal/deadlineOf.ts +8 -0
  48. package/src/server/internal/ensureQueue.ts +20 -2
  49. package/src/server/internal/lifecycle.ts +37 -97
  50. package/src/server/internal/register.ts +10 -6
  51. package/src/server/service.ts +5 -14
@@ -2,30 +2,8 @@ import { Effect } from "effect";
2
2
  import type { ConstructorOptions, StopOptions } from "pg-boss";
3
3
  import { defaultClientFactory, type PgBossClient, type PgBossClientFactory } from "#client.ts";
4
4
  import { toPgBossError } from "#error.ts";
5
-
6
- interface CachedClient {
7
- readonly client: Promise<PgBossClient>;
8
- references: number;
9
- }
10
-
11
- const CacheKey = Symbol.for("@shivaedev/effect-pg-boss/client-cache");
12
- const sharedCache: unknown = Reflect.get(globalThis, CacheKey);
13
- const clientCache: Map<string | symbol, unknown> = sharedCache instanceof Map ? sharedCache : new Map<string | symbol, unknown>();
14
- Reflect.set(globalThis, CacheKey, clientCache);
15
-
16
- function isCachedClient(value: unknown): value is CachedClient {
17
- return (
18
- typeof value === "object"
19
- && value !== null
20
- && Reflect.get(value, "client") instanceof Promise
21
- && typeof Reflect.get(value, "references") === "number"
22
- );
23
- }
24
-
25
- function cachedClient(key: string | symbol): CachedClient | undefined {
26
- const entry = clientCache.get(key);
27
- return isCachedClient(entry) ? entry : undefined;
28
- }
5
+ import { acquireCachedClient, releaseCachedClient } from "./clientCache.ts";
6
+ import { logClientError, observeClientErrors } from "./clientErrors.ts";
29
7
 
30
8
  export interface AcquireClientOptions {
31
9
  readonly clientCacheKey?: string | symbol | undefined;
@@ -39,86 +17,48 @@ export interface AcquiredClient {
39
17
  readonly reused: boolean;
40
18
  }
41
19
 
42
- function startClient(options: AcquireClientOptions): Promise<PgBossClient> {
20
+ async function startClient(options: AcquireClientOptions, report: (error: Error) => void): Promise<PgBossClient> {
43
21
  const client = (options.clientFactory ?? defaultClientFactory)(options.constructor);
44
- return client.start().then(
45
- () => client,
46
- async (error) => {
47
- try {
48
- await client.stop();
49
- } catch {
50
- // Preserve the startup failure; stop is best effort on failed acquisition.
51
- }
52
- throw error;
53
- },
54
- );
22
+ observeClientErrors(client, report);
23
+ try {
24
+ await client.start();
25
+ return client;
26
+ } catch (error) {
27
+ try {
28
+ await client.stop();
29
+ } catch {
30
+ // Preserve the startup failure; stop is best effort on failed acquisition.
31
+ }
32
+ throw error;
33
+ }
55
34
  }
56
35
 
57
- export const acquireClient = (options: AcquireClientOptions): Effect.Effect<AcquiredClient, import("#error.ts").PgBossError> =>
58
- Effect.tryPromise({
59
- catch: (error) => toPgBossError("start", error),
60
- try: async () => {
61
- const cacheKey = options.clientCacheKey;
62
- if (cacheKey === undefined) {
63
- return {
64
- client: await startClient(options),
65
- reused: false,
66
- };
67
- }
68
-
69
- const existing = cachedClient(cacheKey);
70
- if (existing !== undefined) {
71
- existing.references += 1;
72
- try {
73
- return {
74
- cacheKey,
75
- client: await existing.client,
76
- reused: true,
77
- };
78
- } catch (error) {
79
- existing.references -= 1;
80
- throw error;
81
- }
82
- }
83
-
84
- const entry: CachedClient = {
85
- client: startClient(options),
86
- references: 1,
87
- };
88
- clientCache.set(cacheKey, entry);
89
- try {
90
- return {
91
- cacheKey,
92
- client: await entry.client,
93
- reused: false,
94
- };
95
- } catch (error) {
96
- if (clientCache.get(cacheKey) === entry) {
97
- clientCache.delete(cacheKey);
98
- }
99
- throw error;
100
- }
101
- },
36
+ export function acquireClient(options: AcquireClientOptions): Effect.Effect<AcquiredClient, import("#error.ts").PgBossError> {
37
+ return Effect.contextWith((context) => {
38
+ const run = Effect.runForkWith(context);
39
+ function report(error: Error) {
40
+ run(logClientError(error));
41
+ }
42
+ return Effect.tryPromise({
43
+ catch: (error) => toPgBossError("start", error),
44
+ try: async () => {
45
+ const cacheKey = options.clientCacheKey;
46
+ return cacheKey === undefined
47
+ ? { client: await startClient(options, report), reused: false }
48
+ : { cacheKey, ...(await acquireCachedClient(cacheKey, () => startClient(options, report))) };
49
+ },
50
+ });
102
51
  });
52
+ }
103
53
 
104
- export const releaseClient = (acquired: AcquiredClient, stopOptions?: StopOptions): Effect.Effect<void> =>
105
- Effect.tryPromise({
54
+ export function releaseClient(acquired: AcquiredClient, stopOptions?: StopOptions): Effect.Effect<void> {
55
+ return Effect.tryPromise({
106
56
  catch: (error) => toPgBossError("stop", error),
107
57
  try: async () => {
108
- if (acquired.cacheKey === undefined) {
109
- await acquired.client.stop(stopOptions);
110
- return;
111
- }
112
-
113
- const entry = cachedClient(acquired.cacheKey);
114
- if (entry === undefined) {
115
- return;
58
+ const client = acquired.cacheKey === undefined ? acquired.client : await releaseCachedClient(acquired.cacheKey);
59
+ if (client !== undefined) {
60
+ await client.stop(stopOptions);
116
61
  }
117
- entry.references -= 1;
118
- if (entry.references > 0) {
119
- return;
120
- }
121
- clientCache.delete(acquired.cacheKey);
122
- await acquired.client.stop(stopOptions);
123
62
  },
124
63
  }).pipe(Effect.catch((error) => Effect.logError(error)));
64
+ }
@@ -9,7 +9,7 @@ import {
9
9
  type ScheduleDefinition,
10
10
  type ScheduledWorker,
11
11
  } from "#definition.ts";
12
- import { PgBossPayloadError, PgBossQueueOptionsError, toPgBossError } from "#error.ts";
12
+ import { PgBossError, PgBossPayloadError, PgBossQueueOptionsError, toPgBossError } from "#error.ts";
13
13
  import { batchHandler } from "#internal/batchHandler.ts";
14
14
  import { ensureQueue } from "#internal/ensureQueue.ts";
15
15
  import { payloadOf, traceJob } from "#internal/tracing.ts";
@@ -51,7 +51,11 @@ async function prepareQueues(client: PgBossClient, registrations: readonly JobRe
51
51
  }
52
52
  for (const registration of registrations) {
53
53
  const definition = registrationDefinition(registration);
54
- await ensureQueue(client, definition.name, definition.queueOptions);
54
+ try {
55
+ await ensureQueue(client, definition.name, definition.queueOptions);
56
+ } catch (error) {
57
+ throw error instanceof PgBossQueueOptionsError ? error : toPgBossError("register", error, definition.name);
58
+ }
55
59
  }
56
60
  }
57
61
 
@@ -85,7 +89,7 @@ async function registerQueue(client: PgBossClient, registration: QueueWorker | Q
85
89
  }
86
90
  await client.work(
87
91
  name,
88
- queue.workerOptions,
92
+ { ...queue.workerOptions, includeMetadata: true },
89
93
  batchHandler(client, name, (job) => runQueueWorker(registration, job, context)),
90
94
  );
91
95
  }
@@ -94,7 +98,7 @@ async function registerSchedule(client: PgBossClient, worker: ScheduledWorker, c
94
98
  const { schedule } = worker;
95
99
  await client.work(
96
100
  schedule.name,
97
- schedule.workerOptions,
101
+ { ...schedule.workerOptions, includeMetadata: true },
98
102
  batchHandler(client, schedule.name, (job) => Effect.provide(traceJob(worker.effect, job, schedule.name), context)),
99
103
  );
100
104
  await client.schedule(schedule.name, schedule.cron, null, schedule.scheduleOptions);
@@ -113,9 +117,9 @@ export const registerJobs = <R>(
113
117
  registrations: readonly JobRegistration[],
114
118
  context: Context.Context<R>,
115
119
  replaceWorkers: boolean,
116
- ): Effect.Effect<void, import("#error.ts").PgBossError | PgBossQueueOptionsError> =>
120
+ ): Effect.Effect<void, PgBossError | PgBossQueueOptionsError> =>
117
121
  Effect.tryPromise({
118
- catch: (error) => (error instanceof PgBossQueueOptionsError ? error : toPgBossError("register", error)),
122
+ catch: (error) => (error instanceof PgBossQueueOptionsError || error instanceof PgBossError ? error : toPgBossError("register", error)),
119
123
  try: async () => {
120
124
  registrationNames(registrations);
121
125
  await prepareQueues(client, registrations, replaceWorkers);
@@ -4,6 +4,7 @@ import type { PgBossClientFactory } from "#client.ts";
4
4
  import type { JobPayloadSchema, JobRegistration, QueueDefinition, RegistrationRequirements } from "#definition.ts";
5
5
  import type { PgBossError, PgBossPayloadError, PgBossQueueOptionsError } from "#error.ts";
6
6
  import type { JobsHealth, QueueCounts } from "#health.ts";
7
+ import { logClientError, subscribeClientErrors } from "#internal/clientErrors.ts";
7
8
  import { acquireClient, releaseClient } from "#internal/lifecycle.ts";
8
9
  import { registerJobs, registrationName } from "#internal/register.ts";
9
10
  import { makeService } from "#internal/service.ts";
@@ -42,10 +43,6 @@ export interface PgBossDefinition<TIdentifier extends string = string> extends C
42
43
  >;
43
44
  }
44
45
 
45
- function logClientError(error: Error): Effect.Effect<void> {
46
- return Effect.logError({ event: "pg_boss_error", message: error.message });
47
- }
48
-
49
46
  export const makePgBoss = <const TIdentifier extends string>(identifier: TIdentifier): PgBossDefinition<TIdentifier> => {
50
47
  const Service = Context.Service<TIdentifier, PgBossService>(identifier);
51
48
 
@@ -74,20 +71,14 @@ export const makePgBoss = <const TIdentifier extends string>(identifier: TIdenti
74
71
  const errorListener = (error: Error) => {
75
72
  void Effect.runPromise(Effect.exit(Effect.provide(reportError(error), context)));
76
73
  };
77
- acquired.client.on("error", errorListener);
74
+ const unsubscribe = subscribeClientErrors(acquired.client, errorListener);
78
75
  const registration = registerJobs(acquired.client, jobs, context, acquired.reused);
79
76
  return yield* registration.pipe(
80
- Effect.as({ acquired, errorListener, service }),
81
- Effect.onError(() => {
82
- acquired.client.off("error", errorListener);
83
- return releaseClient(acquired, stop);
84
- }),
77
+ Effect.as({ acquired, service, unsubscribe }),
78
+ Effect.onError(() => releaseClient(acquired, stop).pipe(Effect.ensuring(Effect.sync(unsubscribe)))),
85
79
  );
86
80
  }),
87
- (resource) => {
88
- resource.acquired.client.off("error", resource.errorListener);
89
- return releaseClient(resource.acquired, stop);
90
- },
81
+ (resource) => releaseClient(resource.acquired, stop).pipe(Effect.ensuring(Effect.sync(resource.unsubscribe))),
91
82
  );
92
83
 
93
84
  return Layer.effect(