File size: 8,294 Bytes
b152fd5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
/**
 * PluginJobCoordinator β€” bridges the plugin lifecycle manager with the
 * job scheduler and job store.
 *
 * This service listens to lifecycle events and performs the corresponding
 * scheduler and job store operations:
 *
 * - **plugin.loaded** β†’ sync job declarations from manifest, then register
 *   the plugin with the scheduler (computes `nextRunAt` for active jobs).
 *
 * - **plugin.disabled / plugin.unloaded** β†’ unregister the plugin from the
 *   scheduler (cancels in-flight runs, clears tracking state).
 *
 * ## Why a separate coordinator?
 *
 * The lifecycle manager, scheduler, and job store are independent services
 * with clean single-responsibility boundaries. The coordinator provides
 * the "glue" between them without adding coupling. This pattern is used
 * throughout Paperclip (e.g. heartbeat service coordinates timers + runs).
 *
 * @see PLUGIN_SPEC.md Β§17 β€” Scheduled Jobs
 * @see ./plugin-job-scheduler.ts β€” Scheduler service
 * @see ./plugin-job-store.ts β€” Persistence layer
 * @see ./plugin-lifecycle.ts β€” Plugin state machine
 */

import type { PluginLifecycleManager } from "./plugin-lifecycle.js";
import type { PluginJobScheduler } from "./plugin-job-scheduler.js";
import type { PluginJobStore } from "./plugin-job-store.js";
import { pluginRegistryService } from "./plugin-registry.js";
import type { Db } from "@paperclipai/db";
import { logger } from "../middleware/logger.js";

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

/**
 * Options for creating a PluginJobCoordinator.
 */
export interface PluginJobCoordinatorOptions {
  /** Drizzle database instance. */
  db: Db;
  /** The plugin lifecycle manager to listen to. */
  lifecycle: PluginLifecycleManager;
  /** The job scheduler to register/unregister plugins with. */
  scheduler: PluginJobScheduler;
  /** The job store for syncing declarations. */
  jobStore: PluginJobStore;
}

/**
 * The public interface of the job coordinator.
 */
export interface PluginJobCoordinator {
  /**
   * Start listening to lifecycle events.
   *
   * This wires up the `plugin.loaded`, `plugin.disabled`, and
   * `plugin.unloaded` event handlers.
   */
  start(): void;

  /**
   * Stop listening to lifecycle events.
   *
   * Removes all event subscriptions added by `start()`.
   */
  stop(): void;
}

// ---------------------------------------------------------------------------
// Implementation
// ---------------------------------------------------------------------------

/**
 * Create a PluginJobCoordinator.
 *
 * @example
 * ```ts
 * const coordinator = createPluginJobCoordinator({
 *   db,
 *   lifecycle,
 *   scheduler,
 *   jobStore,
 * });
 *
 * // Start listening to lifecycle events
 * coordinator.start();
 *
 * // On server shutdown
 * coordinator.stop();
 * ```
 */
export function createPluginJobCoordinator(
  options: PluginJobCoordinatorOptions,
): PluginJobCoordinator {
  const { db, lifecycle, scheduler, jobStore } = options;
  const log = logger.child({ service: "plugin-job-coordinator" });
  const registry = pluginRegistryService(db);

  // -----------------------------------------------------------------------
  // Event handlers
  // -----------------------------------------------------------------------

  /**
   * When a plugin is loaded (transitions to `ready`):
   * 1. Look up the manifest from the registry
   * 2. Sync job declarations from the manifest into the DB
   * 3. Register the plugin with the scheduler (computes nextRunAt)
   */
  async function onPluginLoaded(payload: { pluginId: string; pluginKey: string }): Promise<void> {
    const { pluginId, pluginKey } = payload;
    log.info({ pluginId, pluginKey }, "plugin loaded β€” syncing jobs and registering with scheduler");

    try {
      // Get the manifest from the registry
      const plugin = await registry.getById(pluginId);
      if (!plugin?.manifestJson) {
        log.warn({ pluginId, pluginKey }, "plugin loaded but no manifest found β€” skipping job sync");
        return;
      }

      // Sync job declarations from the manifest
      const manifest = plugin.manifestJson;
      const jobDeclarations = manifest.jobs ?? [];

      if (jobDeclarations.length > 0) {
        log.info(
          { pluginId, pluginKey, jobCount: jobDeclarations.length },
          "syncing job declarations from manifest",
        );
        await jobStore.syncJobDeclarations(pluginId, jobDeclarations);
      }

      // Register with the scheduler (computes nextRunAt for active jobs)
      await scheduler.registerPlugin(pluginId);
    } catch (err) {
      log.error(
        {
          pluginId,
          pluginKey,
          err: err instanceof Error ? err.message : String(err),
        },
        "failed to sync jobs or register plugin with scheduler",
      );
    }
  }

  /**
   * When a plugin is disabled (transitions to `error` with "disabled by
   * operator" or genuine error): unregister from the scheduler.
   */
  async function onPluginDisabled(payload: {
    pluginId: string;
    pluginKey: string;
    reason?: string;
  }): Promise<void> {
    const { pluginId, pluginKey, reason } = payload;
    log.info(
      { pluginId, pluginKey, reason },
      "plugin disabled β€” unregistering from scheduler",
    );

    try {
      await scheduler.unregisterPlugin(pluginId);
    } catch (err) {
      log.error(
        {
          pluginId,
          pluginKey,
          err: err instanceof Error ? err.message : String(err),
        },
        "failed to unregister plugin from scheduler",
      );
    }
  }

  /**
   * When a plugin is unloaded (uninstalled): unregister from the scheduler.
   */
  async function onPluginUnloaded(payload: {
    pluginId: string;
    pluginKey: string;
    removeData: boolean;
  }): Promise<void> {
    const { pluginId, pluginKey, removeData } = payload;
    log.info(
      { pluginId, pluginKey, removeData },
      "plugin unloaded β€” unregistering from scheduler",
    );

    try {
      await scheduler.unregisterPlugin(pluginId);

      // If data is being purged, also delete all job definitions and runs
      if (removeData) {
        log.info({ pluginId, pluginKey }, "purging job data for uninstalled plugin");
        await jobStore.deleteAllJobs(pluginId);
      }
    } catch (err) {
      log.error(
        {
          pluginId,
          pluginKey,
          err: err instanceof Error ? err.message : String(err),
        },
        "failed to unregister plugin from scheduler during unload",
      );
    }
  }

  // -----------------------------------------------------------------------
  // State
  // -----------------------------------------------------------------------

  let attached = false;

  // We need stable references for on/off since the lifecycle manager
  // uses them for matching. We wrap the async handlers in sync wrappers
  // that fire-and-forget (swallowing unhandled rejections via the try/catch
  // inside each handler).
  const boundOnLoaded = (payload: { pluginId: string; pluginKey: string }) => {
    void onPluginLoaded(payload);
  };
  const boundOnDisabled = (payload: { pluginId: string; pluginKey: string; reason?: string }) => {
    void onPluginDisabled(payload);
  };
  const boundOnUnloaded = (payload: { pluginId: string; pluginKey: string; removeData: boolean }) => {
    void onPluginUnloaded(payload);
  };

  // -----------------------------------------------------------------------
  // Public API
  // -----------------------------------------------------------------------

  return {
    start(): void {
      if (attached) return;
      attached = true;

      lifecycle.on("plugin.loaded", boundOnLoaded);
      lifecycle.on("plugin.disabled", boundOnDisabled);
      lifecycle.on("plugin.unloaded", boundOnUnloaded);

      log.info("plugin job coordinator started β€” listening to lifecycle events");
    },

    stop(): void {
      if (!attached) return;
      attached = false;

      lifecycle.off("plugin.loaded", boundOnLoaded);
      lifecycle.off("plugin.disabled", boundOnDisabled);
      lifecycle.off("plugin.unloaded", boundOnUnloaded);

      log.info("plugin job coordinator stopped");
    },
  };
}